I'm currently working on an existing website created in codeigniter.
Whenever a user enters a page, he gets redirected to frontpage.php, that checks if the user is logged in, if not he gets redirected to the login page.
Now, I have one page where this frontpage.php shouldnt be executed, and any user can enter it.
Any help is greatly appreciated.
Had a similar problem and solved it this way by using some online tutorials
1: Make a seperate loginpage (ex login.php) prior to the 'frontpage.php'.
2: Pass the login, password and a session variable to the frontpage.
3: Recode you 'frontpage.php' to check for the session variable passed by 'login.php'.
If u entered the page trough the normal way it will use the normal login.
if u entered the page trough the new 'login.php' page it will be picked up by the recoded 'frontpage.php' and bypass the normal way.
Hope this helps
Grtz
Re-route everything to your pages controller and use this as your default
$route['default_controller'] = 'pages';
$route['(.*)'] = 'pages/index/$1';
-
class Pages extends CI_Controller
{
protected $currentUser = null;
public function __construct()
{
parent::__construct();
$this->currentUser = Auth::getCurrentUserObject(); //check user is logged in
}
public function index($uri='home')
{
$sizeOfSegments = sizeof($this->uri->rsegments);
if ($sizeOfSegments >= 3)
{
$uri = $this->uri->rsegments[3];
}
else
{
$uri = 'home';
}
$pageFound = Page::find($uri); //query the database
if (!$pageFound)
{
return show_404($uri); // find out where there were headed
}
unset($sizeOfSegments, $uri);
if(is_null($this->currentUser) OR !$this->currentUserHasPermissionToViewThisPage OR !$pageIsNotPublic)
{
return redirect('login');
}
$this->load->view();
}
}
make new controller
class Newpage extends CI_Controller {
public function index(){
$this->load->view('newpage');
}
}
now goto
yourhost.com/index.php/newpage
May be your default Controller have a coding of checking whether user is logged or not. Please remove or change the code in controller.
I think you need to delete the controller, it works like that!
Related
I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.
I have created a log in form for my admin pages and it works, but for now everyone who logs in can access those pages.
My users are also belong to usergroups and my users table in the database has a group_id column. The admin group has an id of 1.
What I'd like to do is that if someone who belongs to the admin group logs in can access the admin pages, but if the user belongs to a different group and tries to log in be redirected to main page or anywhere.
What I'm trying to do is add a similar code to the admin pages controllers
class Dashboard extends MY_Controller {
public function __construct() {
parent::__construct();
// Access control
if(!$this->session->userdata('logged_in')) {
redirect('admin/login');
}
}
}
My model
class Authenticate_model extends CI_Model {
public function login_user($username, $password){
//Secure password
$enc_password = md5($password);
//Validate
$this->db->where('username',$username);
$this->db->where('password',$enc_password);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row();
} else {
return false;
}
}
}
You can do it yourself, provide validation and set $SESSION variable to retrieve if the user is logged in. But this is too much work, and error prone.
I recommend you to use this popular library: https://github.com/benedmunds/CodeIgniter-Ion-Auth. It is really easy to set up, you just need to copy some files and you are ready to go.
If you really want to do it your self(thats the question) then you need to store in SESSION two variables - logged_in and is_admin.
I would recomend two create library with function:
function is_logged_in($admin = FALSE){
$is_logged = $this->session->userdata('logged_in');
if($admin){
$is_logged = $this->session->userdata('is_admin')
}
return $is_logged;
}
This assumes that you store two booleans "logged_in" and "is_admin" in SESSION.(If user has group_id = 1 then you would store TRUE in is_admin)
Then you can protect your site members only pages
if(!$this->your_authenticatation_library->is_logged_in()){redirect('notMembersControler')}
and admin page:
if(!$this->your_authenticatation_library->is_logged_in(TRUE)){redirect('notMembersControler')}
Thats the basic idea, you need to work around depending on what you are up to. Hope this helps!
After spending so many days, am trying to get some help from experts.
I am stuck with login redirection in my yii2 application only in chrome browser,
This is my controller class,
class InvitationsController extends Controller
{
public function beforeAction($action)
{ $array=array('index','imageupload','template','category','subcategory','slug','chooseanotherdesign');
if(!in_array($action->id, $array))
{
if (\Yii::$app->getUser()->isGuest &&
\Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
) {
\Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl,FALSE);
}
}
return parent::beforeAction($action);
}
public function actionGenerateevent(){
$redirectUrl="";
if(Yii::$app->request->post()){
unset(Yii::$app->session['copyinvitation']);
unset(Yii::$app->session['eventform']);
Yii::$app->session['eventform']=Yii::$app->request->post();
}
if (!Yii::$app->user->isGuest)
{
$eventid=$this->invitation->savecontinue(Yii::$app->session['eventform']);
$eventdata=$this->invitation->getEventById($eventid);
$refurl=Yii::$app->session['eventform']['refererurl'];
$aa['Events']=$eventdata;
$aa['refererurl']=$refurl;
Yii::$app->session['eventform']=$aa;
$redirectUrl = Yii::$app->urlManager->createAbsoluteUrl(['invitations/event/'.$eventdata['event_token']]);
return $this->redirect($redirectUrl);
}
}
}
My workflow
step1: submitting formdata to controller xx-action
step2: If user login it will proceed further action
Else
am trying to store the values in session then redirecting the page to login
step 3: after successful login am return back to same xx-action
This workflow is working fine in firefox but chrome it's making infinitive loop its not going through the login page.
Please refer am attached the screenshot
Please help me to solve this issue.
I can't infere how are you calling your actionGenerateevent() but you seems to have an error there:
$redirectUrl=""; //empty
...
return $this->redirect($redirectUrl); //still empty
Since you are not setting your $redirectUrl, your redirect is redirecting you to the current (same) url again and again, causing the loop.
This is the function used by redirectUrl() method: Url::to(). Its docs says:
an empty string: the currently requested URL will be returned;
a bit new to CI, googled and overflowed alot and still got no answer
User enters site.
After succesful auth got redirected to main page
Link on the url stays the same with class/method
If u refresh page on a main - u always got question about repopulate form (chrome/firefox 100%)
the solution may be: after success redirect to another class or method
but i don't know how to do it, documentation seems more like reference to me
code is here: http://paste.ubuntu.com/696751/ line 28 - how to do redirect to another class or method with a redirection to another view too?
Well an example in CodeIgniter may be:
class login extends CI_Controller
{
function index ()
{
$this->load->library('form_validation');
$this->load->helper('url');
//Set form validation rules here: http://codeigniter.com/user_guide/libraries/form_validation.html
if ($this->form_validation->run() == TRUE)
{
//login user here
redirect('login/sucLogin'); // or just redirect to '/' if you want to send them to your home page
}
else
$this->load->view('loginForm'); //make form
}
function sucLogin ()
{
echo 'Successfully logged in';
echo anchor('/', 'Go Home');
}
}
Check to see if the user submitted the form
Validate the login credentials
Redirect on success
public function login()
{
if ($_POST)
{
$login = $this->input->post('login');
$password = md5($this->input->post('password'));
$q = $this->db
->where('login', $login)
->where('password', $password)
->limit(1)
->get('userbase');
if ($q->num_rows > 0 )
{
redirect('enter/main');
}
}
$returnlogin['login'] = $login;
$this->load->helpers('form');
$this->load->view('login_form',$returnlogin);
}
public function main()
{
$this->load->view('main');
}
The issue here is that when my user logs into my app, they always are redirected to the default controller.
I would like the user to be redirected to the page they were on before logging in.
So for example, if the user is reading forum post #12 (reading does not require login) and then decides to post an answer (answering requires login), once they login they should go back to post #12.
I am using PHP/Codeigniter 2.0.2 and the Tank_Auth library, and have in several of my controllers
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {
//load stuff
}
My question is
What is the best way to set a return URL (Cookie? GET?), and how would that be implemented?
If you're familiar with Tank_Auth, in which files should I make these changes?
Any roadmaps are welcome, even if you don't use Tank_Auth.
I Recently implemented this solution on a webpage I was working.
In the controller/auth file add a reference to the user_agent library:
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('security');
$this->load->library('tank_auth');
$this->lang->load('tank_auth');
$this->load->library('user_agent'); //This is the line you are adding
}
In the views/auth/login_form.php and taking advantage of the CodeIgniter's user_agent library add a hidden input tag which will contain the referrer url as follows:
<?=form_hidden('redirect_url', $this->agent->referrer());?>
<?php echo form_submit('submit', 'Let me in'); ?>
<?php echo form_close(); ?>
After that, all you have to do is redirect the users to the content of the input named "redirect_url" when the user posts the login data to the login action:
/**
* Login user on the site
*
* #return void
*/
function login()
{
/*.... Beginning of the login action function...
....
....
*/
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],$data['login_by_email'])) //valid
{
redirect( $this->input->post('redirect_url'));
}
}
This works great for me... It's fine and simple. I believe it can help you.
Let me know about anything.
This is the solution I've been using with tank_auth, it's probably not the best, but I've found it works well for me.
In the controller
if (!$this->tank_auth->is_logged_in()){
$encoded_uri = preg_replace('"/"', '_', $_SERVER['REQUEST_URI']);
redirect('/login/'.$encoded_uri);
}elseif($this->tank_auth->is_logged_in(FALSE)){ // logged in, not activated
redirect('/user/reactivate/');
}else{
//Logged IN Stuff Here
}
Modified Tank Auth Login Function (controllers/auth.php)
function login($return_to = "")
{
if ($this->form_validation->run()) {
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],
$data['login_by_email'])) {
//...Other Stuff Here
$decoded_uri = preg_replace('"_"','/',$return_to);
redirect($decoded_uri);
}
}
}
You may need to change the preg_replace to something else if your urls have _ in them, I just used that because it works for me
EDIT
I've updated the function, this is one from another project that we heavily modified the tank auth stuff, so if stuff is a bit different, I'm sorry
As for the passing the encode_uri stuff, I've added the following to the routes.php file (config/routes.php)
$route['auth/login/(:any)'] = 'auth/login/$1';
$route['auth/login'] = 'auth/login'; //Probably don't need this one now
Hi I solved it as follows
In your controller
Add this: $this->load->library(array('tank_auth');
if (!$this->tank_auth->is_logged_in()) {
$encoded_uri = preg_replace('"/"', '_', $this->uri->uri_string());
redirect('/auth/login/'.$encoded_uri);
} else {
// Logged IN Stuff Here
}
In Tank Auth Controller (controllers/auth.php)
function login($return_to = "")
{
if ($this->form_validation->run()) {
if ($this->tank_auth->login(
$this->form_validation->set_value('login'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('remember'),
$data['login_by_username'],
$data['login_by_email'])) {
// success
$decoded_uri = preg_replace('"_"','/',$return_to);
redirect($decoded_uri);
}
}
}
I replaced $_SERVER['REQUEST_URI'] with this $this->uri->uri_string() because that allow you get /controller/method/...etc. to redirect later in tank auth controller
That work perfect for me and how said #Cubed Eye "You may need to change the preg_replace to something else if your urls have _ in them"
Thanks to #Cubed Eye
I hope this helps someone else too.