how can I redirect login page if do not login in yii framework? - yii

I have the actionLogin and create cookie like here :
public function actionLogin()
{
$this->layout = 'login';
$model=new LoginForm;
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
if($model->validate() && $model->login()){
$cookie = new CHttpCookie('loginSuccess',$model->username);
$cookie->expire = 604800;
Yii::app()->request->cookies['loginSuccess'] = $cookie;
$this->redirect('/ktbeauty/index.php/categories/index');
}
}
$this->render('login',array(
'model'=>$model,
));
}
And Now I have some controllers which must check to login before access controllers, if not login, it must redirect to login page, how can I work for this ?
thankyou very much

in the action of your controller you can try something like this
public function actionGoToLogin()
{
if(!Yii::app()->user->isGuest)
{
// do something if user is authenticated
}
else
{
Yii::app()->user->loginRequired();
// or if you want you can redirect using Yii::app()->createUrl('controller/login');
}
}

In Controller, you have a function as below:
public function accessRules() {
Here you can define the actions and users who can access those functions.
If you are not logged in, then it'll redirected to login page by default.
This feature available by default in YII.
check this URL:
http://www.yiiframework.com/wiki/169/configuring-controller-access-rules-to-default-deny/

Related

Laravel: How to see if user is logged in in Base Controller?

I want to be able to change a field called "last_accessed" in the users table on each and every request the user makes.
I have a controller called "ContentController" which extends "Controller". So I figured just adding code in the constructor of "Controller":
public function __construct()
{
$user = \Auth::user();
if (Auth::check()) {
print 'Good';
}
else print "Bad";
}
No matter what I do, I can't it to see that I'm authorized.
Can someone please tell me:
Why is AUTH not working in the base controller?
How can I update the last_accessed field upon each view if this controller idea of mine isn't possible?
Because that doesn't work in __construct(). There is a workaround. It works but I'm not sure if some other Laravel users will accept my answer. What you should do is create a middleware and work from there. You can use an anonymous function, which in this case, mimics a middleware:
public function __construct(Request $request)
{
$this->middleware(function ($request, $next) {
$user = $request->user();
if ($user) {
print 'Good';
}
else print "Bad";
return $next($request);
});
}
If no user is logged in, $user will be null.

Yii redirecting the admin and authenticated user to the desired page

I am new to yii. I want my admin upon login from webapp/user/login to redirect to the page I want which is localhost/webapp/story right now it is redirecting me to the index.php.
I have also registered a user and given that user a role which is authenticated and I want that when my user(the authenticated user) logs in via webapp/user/login then that user is redirected to index.php.
so there are two things:
1. redirecting admin to the desired page which is webapp/story.
2. redirecting the authenticated user to index.php.
I am using yii user and right extension. Please help me with this.
The code LoginController is below:
<?php
class LoginController extends Controller
{
public $defaultAction = 'login';
/**
* Displays the login page
*/
public function actionLogin()
{
if (Yii::app()->user->isGuest) {
$model=new UserLogin;
// collect user input data
if(isset($_POST['UserLogin']))
{
$model->attributes=$_POST['UserLogin'];
// validate user input and redirect to previous page if valid
if($model->validate()) {
$this->lastViset();
if (Yii::app()->user->returnUrl=='/index.php')
$this->redirect(Yii::app()->controller->module->returnUrl);
else// yehen par kuch aye ga according
$this->redirect(Yii::app()->user->returnUrl);
}
}
// display the login form
$this->render('/user/login',array('model'=>$model));
} else
$this->redirect(Yii::app()->controller->module->returnUrl);
}
private function lastViset() {
$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
$lastVisit->lastvisit = time();
$lastVisit->save();
}
}
I think could be somethings like this
<?php
class LoginController extends Controller
{
public $defaultAction = 'login';
/**
* Displays the login page
*/
public function actionLogin()
{
if (Yii::app()->user->isGuest) {
$model=new UserLogin;
// collect user input data
if(isset($_POST['UserLogin']))
{
$model->attributes=$_POST['UserLogin'];
// validate user input and redirect to previous page if valid
if($model->validate()) {
$this->lastViset();
// Old code commentede
//if (Yii::app()->user->returnUrl=='/index.php')
// $this->redirect(Yii::app()->controller->module->returnUrl);
//else// yehen par kuch aye ga according
// $this->redirect(Yii::app()->user->returnUrl);
// new code
if (UserModule::isAdmin()){
$this->redirect(array('story/index'));
}
else {
$this->redirect(Yii::app()->user->returnUrl);
}
}
}
// display the login form
$this->render('/user/login',array('model'=>$model));
} else
$this->redirect(Yii::app()->controller->module->returnUrl);
}
private function lastViset() {
$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
$lastVisit->lastvisit = time();
$lastVisit->save();
}
}

Filter in Yii is not returning

I am trying to user filters in YII.
here is my code.
public function filters()
{
return array(
'provideronly +uploadclients,fileview,editprofile,getinvitedusers',
);
}
public function filterProvideronly($filterchain)
{
if(Yii::app()->user->providerId==-1)
{
$this->redirect(array('site/error','id'=>403,'message'=>'You are unauthorized to view this page'));
return false;
}
return true;
}
When the user is unauthorized to use the controller it is redirecting to error page. but when the user is authorized , it is showing a blank page..
what is wrong in this code ?
Instead of return true you need to put $filterChain->run(); so yii can see that the filter ended.

How to set default action dynamically in Yii

i want to change default action of a controller depends on which user is logged in.
Ex. There are two users in my site : publisher and author and i want to set publisher action as default action when a publisher is logged in, and same for author.
what should i do? when can I check my roles and set their relevant actions?
Another way to do this would be setting the defaultAction property in your controller's init() method. Somewhat like this:
<?php
class MyAwesomeController extends Controller{ // or extends CController depending on your code
public function init(){
parent::init(); // no need for this call if you don't have anything in your parent init()
if(array_key_exists('RolePublisher', Yii::app()->authManager->getRoles(Yii::app()->user->id)))
$this->defaultAction='publisher'; // name of your action
else if (array_key_exists('RoleAuthor', Yii::app()->authManager->getRoles(Yii::app()->user->id)))
$this->defaultAction='author'; // name of your action
}
// ... rest of your code
}
?>
Check out CAuthManager's getRoles(), to see that the returned array will have format of 'role'=>CAuthItem object, which is why i'm checking with array_key_exists().
Incase you don't know, the action name will be only the name without the action part, for example if you have public function actionPublisher(){...} then action name should be: publisher.
Another, simpler, thing you can do is keep the default action the same, but that default action simply calls an additional action function depending on what kind of user is logged in. So for example you have the indexAction function conditionally calling this->userAction or this->publisherAction depending on the check for who is logged in.
I think you can save "first user page" in user table. And when a user is authenticated, you can load this page from database. Where you can do this? I think best place is UserIdentity class. After that, you could get this value in SiteController::actionLogin();
You can get or set "first page" value:
if (null === $user->first_page) {
$firstPage = 'site/index';
} else {
$firstPage = $user->first_page;
}
This is a complete class:
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = User::model()->findByAttributes(array('username' => $this->username));
if ($user === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} else if ($user->password !== $user->encrypt($this->password)) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
} else {
$this->_id = $user->id;
if (null === $user->first_page) {
$firstPage = 'site/index';
} else {
$firstPage = $user->first_page;
}
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
/**
* Displays the login page
*/
public function actionLogin()
{
$model = new LoginForm;
// if it is ajax validation request
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if (isset($_POST['LoginForm'])) {
$model->attributes = $_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login())
$this->redirect(Yii::app()->user->first_page);
}
// display the login form
$this->render('login', array('model' => $model));
}
Also, you can just write right code only in this file. In SiteController file.

codeigniter sess_destroy() not working properly,what m i doing wrong?

I am a newbie in codeigniter. I am using an an login form to login as an admin. When the admin logs in with the correct user name and password s/he is directed to the home page with a session variable.and then if he clicks the log out button the session is supposed to be destroyed and redirect the user to log in page i.e log in form page.
The 1st controller is admin:
<?php
class Admin extends CI_Controller
{
function index()
{
$data['main_content'] = 'admin/log_in';
$this -> load -> view('includes/admin/admin_template', $data);
}
function log_in()
{
$this->load->model('admin_model');
$query = $this -> admin_model -> validate();
if ($query)// if the user's credentials validated...
{
$data = array('user_name' => $this -> input -> post('user_name'), 'is_logged_in' => true);
$this -> session -> set_userdata($data);
redirect('admin/home/admin_home');
} else// incorrect username or password
{
$this -> index();
}
}
function log_out()
{
$this->session->sess_destroy();
redirect('/admin/admin','refresh');
}
}
The second controller is the home controller:
<?php
class Home extends CI_Controller
{
function __construct()
{
parent:: __construct();
$this->is_logged_in();
}
function is_logged_in()
{
$is_logged_in = $this -> session -> userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true)
{
$this -> load -> view('admin/forbidden');
}
}
function admin_home()
{
$data['main_content'] = 'home_view';
$this->load->view('admin/home_view');
}
}
The model is admin_model:
<?php
class Admin_model extends CI_Model
{
function __construct()
{
parent:: __construct();
}
function validate()
{
$this->db->where('user_name',$this->input->post('user_name'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('user');
if($query->num_rows==1)
{
return true;
}
}
}
Now, it supposed the user to logout and destroy the session, but if I click the back button of my browser I can get page back which was supposed not to be and the session is not destroyed.
please tell me what I am doing wrong here. I am using codeigniter 2.1.0.
after going through all the troubles and searching in various places i have finally found a proper solution to this question.the problem arrived because the browser was showing the cached pages.it was not the session that was creating the problem and it was working properly.
here is the solution:
in the home controller adding a function to clear the cache and calling it in the constructor function does the trick :)
here is the home controller with the solution:
<?php
class Home extends CI_Controller
{
function __construct()
{
parent:: __construct();
$this->is_logged_in();
$this->clear_cache();
}
function is_logged_in()
{
if (!$this->session->userdata('is_logged_in'))
{
redirect('/admin/admin');
}
}
function clear_cache()
{
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
}
function admin_home()
{
$data['main_content'] = 'home_view';
$this->load->view('admin/home_view');
}
}
now thanks goes to this link " logout feature in code igniter ",here is where i have found the solution and it works perfectly :)
If you logout then although the session is destroyed, the session userdata remains for the duration of the current CI page build.
As a precautionary measure you should do:
function log_out()
{
$this->session->sess_destroy();
// null the session (just in case):
$this->session->set_userdata(array('user_name' => '', 'is_logged_in' => ''));
redirect('/admin/admin');
}
See: http://codeigniter.com/forums/viewthread/110993/P130/#662369