In YII Framework, the Captcha doesn't show(conflict with accessControl) - php

In my site, only when I remove the filters() method, the captcha can show up. other time the captcha doesn't work. and my php gd support is enable.
now I am using a custome WebUser, if I remove it from config, the captcha also works well.
by the way, if I access user/captcha directly, it only show a picture box, but not content, maybe can not load the picture..
here are some code segments in my UserController:
actions();
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
'minLength' => 4,
'maxLength' => 4,
'testLimit' => 99999
)
);
}
filters():
public function filters()
{
// return the filter configuration for this controller, e.g.:
return array(
"accessControl",
);
}
accessRulse():
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('captcha'),
'users'=>array('*'),
),
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','login','signup'),
'expression'=>'Yii::app()->user->isGuest',
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('cpassword','info','logout'),
'expression'=>'!Yii::app()->user->isGuest',
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'users'=>array('admin#example.com'),
),
array('deny', // deny all users
'users'=>array('*'),
'message'=>'Access Denied.',
),
);
}
My WebUsers.php
<?php
// this file must be stored in:
// protected/components/WebUser.php
class WebUser extends CWebUser {
// Store model to not repeat query.
private $_model;
// Return first name.
// access it by Yii::app()->user->first_name
public function getDisplayName(){
$user = $this->loadUser(Yii::app()->user->id);
if($user)
return $user->display_name;
}
public function getGroupId(){
$user = $this->loadUser(Yii::app()->user->id);
return $user->group_id;
}
// This is a function that checks the field 'role'
// in the User model to be equal to 1, that means it's admin
// access it by Yii::app()->user->isAdmin()
public function isAdmin(){
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->group_id) == 1;
}
public function isGroupAAS(){
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->group_id) == 1001;
}
// Load user model.
protected function loadUser($id=null)
{
if($this->_model===null)
{
if($id!==null)
$this->_model=User::model()->findByPk($id);
}
return $this->_model;
}
protected function afterLogin($fromCookie){
$user = $this->loadUser($this->id);
$user->last_login_ip = Yii::app()->request->userHostAddress;
$user->last_login_time = new CDbExpression('NOW()');
$user->save();
}
}
?>

In your controller, make sure this is defined.
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
Then, allow the action as following.
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('captcha'),
'users'=>array('*'),
),
array('deny', // deny all users
'users'=>array('*'),
'message'=>'Access Denied.',
),
);
}
and in the form,
<?php $this->widget('CCaptcha'); ?><br>
<?php echo CHtml::textField('captcha'); ?>
if this doesnt work, try this way..
<?php $this->widget('CCaptcha', array('captchaAction' => 'site/captcha')); ?>
to validate the capthca, define it as following in your action
$captcha=Yii::app()->getController()->createAction("captcha");
$code = $captcha->verifyCode;
if($code === $_REQUEST['captcha']){
}
Your code looks fine and compare your code with this answer or please provide the source code to take a look at.

Give access to your captcha showing method ie actions
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('actions'),
'users'=>array('*'),
),

I have tested your code with one of my SiteController & it's (captcha action) working fine under contact action. Could you kindly post full UserController code to review & identify the exact cause?

Just add 'captcha' in the actions array like this
public function accessRules()
{
return array(array('allow', // allow admin user to perform these actions
'actions'=>array('index','view','add','captcha'),
'users'=>array('admin'),
), ...

Related

Why the accessRules doesen't work in my yii module, the yii version is 1.1

I want to make the authenticated users can access my
admin(module)/sysMessage(controller)/index(action)
My accessRules is as below:
public function accessRules()
{
return array(
array('allow', // allow only users in the 'admin' role access to our actions
'actions'=>array('index','view', 'create', 'update', 'admin', 'delete'),
'roles'=>array('admin'),
),
array('allow',
'actions'=>array('index','view'),
'roles'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
But, when the authenticated users tried to access my
admin(module)/sysMessage(controller)/index(action), they got this message:
"Error 403 You are not authorized to perform this action."
Could you tell me why?
When we use the module/controller/action, we should check the
/yiiroot/trackstar/protected/modules/admin/yourModule.php
I changed the "public function beforeControllerAction" as below, so the problem be solved.
refer:Create AccessRules in modules Yii Framework
public function beforeControllerAction($controller, $action)
{
if(parent::beforeControllerAction($controller, $action))
{
// this method is called before any module controller action is performed
// you may place customized code here
if(Yii::app()->user->isGuest){
$url = Yii::app()->createUrl(Yii::app()->user->loginUrl);
Yii::app()->user->returnUrl = Yii::app()->createUrl('/admin/');
Yii::app()->request->redirect($url);
}
else {
return true;
}
}
else
return false;
}

Yii: Unable to load the url page " Error 404 Unable to resolve the request "user/userpage"."

I am a yiibie, i am trying to get user data from the user table against there id. For that I have made a userpage.php file in the views and also written a function in the user controller named Userpage to get the user data from the table. After doing all this when I write the url "localhost/projectname/user/userpage?id="anyid" it gives me an error
Error 404
Unable to resolve the request "user/userpage".
here is the code for my UserController
<?php
class UserController extends RController
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/admin';
/**
* #return array action filters
*/
public function filters()
{
return array(
// 'accessControl', // perform access control for CRUD operations
// 'postOnly + delete', // we only allow deletion via POST request
'rights',
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
public function actionUserpage($id)
{
$this->layout='main';
$this->render('userpage',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new User;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$rnd = rand(0,9999); // generate random number between 0-9999
$model->attributes=$_POST['User'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;
if($model->save())
{
$uploadedFile->saveAs(Yii::app()->basePath.'/'.$fileName); // image will uplode to rootDirectory/event/
$this->redirect(array('admin'));
}
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$_POST['User']['image'] = $model->image;
$model->attributes=$_POST['User'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::app()->basePath.'/'.$model->image);
}
$this->redirect(array('admin'));
}
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('User');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new User('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['User']))
$model->attributes=$_GET['User'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return User the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=User::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param User $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
and this is the code for my view file(userpage.php)
<div class="profile">
<div class="row">
<div class="col-md-4">
<img src="<?php echo Yii::app()->request->baseurl;?>/img/<?php echo $model->profile->picture;?>" class="img-responsive"><br>
</div>
<div class="col-md-6">
<h2 class="profile-name"><?php echo $model->username;?></h2>
<hYii: Unable to load the url page " Error 404 Unable to resolve the request "user/userpage"."
And this is the config/main.php
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'theme' => 'bootstrap',
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'emergency response system',
// preloading 'log' component
'preload'=>array('log'),
'aliases' => array(
'bootstrap' => 'ext.bootstrap'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
'bootstrap.behaviors.*',
'bootstrap.helpers.*',
'bootstrap.widgets.*',
'application.modules.user.models.*',
'application.modules.user.components.*',
'application.modules.rights.*',
'application.modules.rights.components.*',
'application.extensions.EAjaxUpload.*',//for multiuploadfiles
'application.extensions.kml.*'
),
'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'ers',
'generatorPaths' => array(
'bootstrap.gii', ),
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
'user' => array(
'tableUsers' => 'user',
'tableProfiles' => 'profiles',
'tableProfileFields' => 'profiles_fields',
// # encrypting method (php hash function)
// 'hash' => 'md5',
//
// # send activation email
// 'sendActivationMail' => true,
//
// # allow access for non-activated users
// 'loginNotActiv' => false,
//
// # activate user on registration (only sendActivationMail = false)
// 'activeAfterRegister' => false,
//
// # automatically login from registration
// 'autoLogin' => true,
//
// # registration path
// 'registrationUrl' => array('/user/registration'),
//
// # recovery password path
// 'recoveryUrl' => array('/user/recovery'),
//
// # login form path
// 'loginUrl' => array('/user/login'),
//
// # page after login
// 'returnUrl' => array('/user/profile'),
//
// # page after logout
// 'returnLogoutUrl' => array('/user/login'),
),
'rights'=>array(
'install'=>true,
// 'superuserName'=>'Admin', // Name of the role with super user privileges.
// 'authenticatedName'=>'Authenticated', // Name of the authenticated user role.
// 'userIdColumn'=>'id', // Name of the user id column in the database.
// 'userNameColumn'=>'username', // Name of the user name column in the database.
// 'enableBizRule'=>true, // Whether to enable authorization item business rules.
// 'enableBizRuleData'=>true, // Whether to enable data for business rules.
// 'displayDescription'=>true, // Whether to use item description instead of name.
// 'flashSuccessKey'=>'RightsSuccess', // Key to use for setting success flash messages.
// 'flashErrorKey'=>'RightsError', // Key to use for setting error flash messages.
// 'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested.
// 'layout'=>'rights.views.layouts.main', // Layout to use for displaying Rights.
// 'appLayout'=>'application.views.layouts.main', // Application layout.
// 'cssFile'=>'rights.css', // Style sheet file to use for Rights.
// 'install'=>false, // Whether to enable installer.
// 'debug'=>false,
),
),
// application components
'components'=>array(
'user'=>array(
'class'=>'RWebUser',
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl'=>array('/user/login'),
),
'authManager'=>array(
'class'=>'RDbAuthManager',
'connectionID'=>'db',
'defaultRoles'=>array('Authenticated', 'Guest'),
// 'itemTable'=>'authitem',
// 'itemChildTable'=>'authitemchild',
// 'assignmentTable'=>'authassignment',
// 'rightsTable'=>'rights',
),
'bootstrap' => array(
'class' => 'bootstrap.components.BsApi',),
// uncomment the following to enable URLs in path-format
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=>false,
'rules'=>array(
//'<controller:\w+>'=>'<controller>/list',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
'<controller:\w+>/<id:\d+>/<title>'=>'<controller>/view',
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
),
),
// database settings are configured in database.php
//'db'=>require(dirname(__FILE__).'/database.php'),
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=response_system',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
array(
'class'=>'CWebLogRoute',
),
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster#example.com',
),
);
check you have a proper view named
userpage.php
in the view directory for user
(the related view directory for user depend of the user component you use.)
check the namespace or the config/main.php of your app for find the right dir.
Check also if you have properly assigned userpage in the accessRules of your User model.
And be absoluty sure you are using a valid $id value. because if the value of id is not found in db should raise this kind of message
and try adding prettyUrl = true otherwise you can't use your notation
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=>false,
'enablePrettyUrl' => true, // Disable r= routes
'rules'=>array(
//'<controller:\w+>'=>'<controller>/list',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
'<controller:\w+>/<id:\d+>/<title>'=>'<controller>/view',
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
),
),
you need to also register your userpage action in your public function accessRules() function , without it you can not access this action from a url.
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','userpage'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
Please note, the above change will let only users to use the userpage action, if you want it to be public add it to 'users'=>array('*'), array

Retreving specific row from database in yii

I am working on a job site,And want to show only the jobs posted by a particular user in cgridview.My actuall aim is to authenticate the user so that only jobs posted by him/her will be visible in cgridview.I have done the following stuff,but not working.
In controller:
public function actionViewJob() {
$user_id = Yii::app()->session['user_id'];
/* For User Authentication */
if (Yii::app()->user->getId() === null)
$this->redirect(array('site/login'));
/* For User Authentication */
/* Have tried the following codes to filter */
$model= ViewJob::model()->findAll(array(
'select'=>'*',"condition"=>"user_id='$user_id'",
));
// $model=ViewJob::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
// $model = ViewJob::model()->findAll("user_id=$user_id");
$model = new Viewjob('search');
$params = array('model' => $model,
);
$this->render('viewjob', $params);
}
In view
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' =>$model->search()
// 'filter' => $model, /* not using this option ,so commented it */
))
In model
// Do I really Need This Function //
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('user_id', $this->user_id, true);
return new CActiveDataProvider('viewjob', array(
'criteria'=>$criteria,
));
},,
What am I doing wrong here.It is still fetching all the available rows in table.
You define $model 3 times:
$model= ViewJob::model()->findAll(array(
'select'=>'*',"condition"=>"user_id='$user_id'",
));
Then
$model = new Viewjob('search');
And
'dataProvider' =>$model->search()
Choose one that you need, better last. And add to controller
$model->user_id = $user_id
It will works.
Create new CDbCriteria object and add condition using it and pass it to model.
In Controller:
public function actionViewJob() {
$criteria = new CDbCriteria ();
$criteria->condition = 'user_id=' . Yii::app()->user->id;
$model = ViewJob::model()->findAll($criteria);
$params = array('model' => $model);
$this->render('viewjob', $params);
}
And in View, simply:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' =>$model
Also for use Authentication, in your controller you don't need to check, if user has the user id, simply add access rules, which will automatically redirect user to the login page to view the job and once they are logged-in, will return them to the same page. So, add this at the top of our controller..
class YourController extends Controller {
public function filters() {
return array(
'accessControl', // perform access control
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow authenticate user actions
'actions' => array('viewjob'),
'users' => array('#'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}

How to view data only made by the user?

I created a link and what it's supposed to do is take me to the page where it displays all the announcements that I posted but instead it shows me all of the announcements inside the database.
here is my link:
<a class="more" href="<?php echo Yii::app()->createUrl('announcement')?>" ><?php switch_lang('View Announcements', '查看更多', FALSE)?></a>
This is the controller for announcement for the actionView() :
public function actionView()
{
$post=$this->loadModel();
if(Persons::model()->compare_country(explode("|",$post->country)))
{
$post->view_count = $post->view_count + 1;
Yii::app()->db->createCommand("UPDATE content SET view_count = {$post->view_count} WHERE id = {$post->id}")->execute();
//$post->save();
$comment=$this->newComment($post, 'view');
if (!empty(Yii::app()->session['announcement_message']))
{
Yii::app()->user->setFlash('message',Yii::app()->session['announcement_message']);
Yii::app()->session['announcement_message'] = null;
}
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
'view'=>'view',
));
}
else
{
$this->redirect(Yii::app()->createAbsoluteUrl('news/index',array('page'=>'1')));
}
}
Yii supports the concept of the data owner in its access control implementation.
The first step to implementing this in your own application is to instruct the controller to enable this rule. This is done by overwriting the filters() function.
class ContentController extends Controller {
public function filters() {
return array(
'accessControl'
);
}
public function accessRules() {
}
}
The 'accessControl' flag specifies that access control is applied for data management. The actual business rules are defined in the accessRules() function, and specifying the access control expression that will be evaluated to provide the desired control. And example of the function implementation is.
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('view'),
'users' => array('*'),
),
array('allow', // allow authenticated user to perform 'add' action
'actions' => array('add'),
'users' => array('#'),
),
array('allow', // allow only the owner to perform 'modify' 'delete' actions
'actions' => array('modify', 'delete'),
'expression' => array('ContentController','isMyRecord')
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
The isMyRecord is a method that will be run that returns true or false to indicate if the action should be allowed.
public function isMyRecord(){
$content_id = $_GET["content_id"];
$person = Example::model()->findByPk($content_id);
if ($example->owner_id === Yii::app()->user->id)
return true;
else
return false;
}

Yii check if user is logged before every page

I have to check if user is logged before rendering every page example:
http://mypage.com/site/about
at begining check if user is logged in, if not - redirect tom login page
I don't want to add it in every single componene, how to to this?
You can also check using this if it is true then user is not logged in else logged in
if(Yii::app()->user->isGuest){
//not logged user
}else{
//loggedin user
}
Use access rule to achevie this would be a better way:
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'contact' actions
'actions'=>array('index','contact'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'delete' and 'update' actions
'actions'=>array('update','delete'),
'users'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
if you really want one-place checking,,then go to component/controller and do it in the controller. because all controller inherits from that controller.
You can write a check in the init() function of the controller. Which will redirect the user if he is not logged in
public function init()
{
if(!isset(Yii::app()->session['user']))
{
$this->redirect(array('login/'));
}
}
This works for me
public function beforeAction(CAction $action)
{
if(!isset(Yii::app()->user->user_id) && !($action->controller->id == 'site' && $action->id == 'login'))
{
$this->redirect(array('site/login'));
}
return true;
}
You need to just add the above function in component/Controller.php
For a global solution add accessControl to your base controller (by default protected/components/CController.php).
public function filters(){
return array('accessControl');
}
public function accessRules()
{
return array(
array('allow',
'users'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
Then in the controller with your login action edit the accessRules to allow all users to access the login page
public function accessRules()
{
return array_merge(array(
'allow',
'actions'=>array('login'),
'users'=>array('*'),
),parent::accessRules()
);
}
Extend components/Controller with beforeAction
public function beforeAction(CAction $action)
{
if(!isset(Yii::app()->session['user']) && !($action->controller->id == 'site' && $action->id == 'login'))
{
$this->redirect(array('site/login'));
}
return true;
}
you can add global behavior to your config:
'as access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error', 'resend', 'forgot'],
'allow' => true,
],
// allow authenticated users
[
'allow' => true,
'roles' => ['#'],
],
]
],
http://stuff.cebe.cc/yii2docs/guide-concept-configurations.html#configuration-format
Sorry for zombie posting, but I use isGuest.
if (Yii::app()->user->isGuest)
{
$this->redirect('login/page');
}
Write a code to check if the user is logged in or not in a different file.
Then include that php page in every file.
You will just have to write the following code.
include('checklogin.php');
In the checklogin.php page, you may write the following to check if the cookie is set.
isset(cookie('<name_of_cookie>'))
{
//User in already logged in
}
else
{
//Redirect to login page
}

Categories