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
}
Related
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;
}
I have already check and when I create users and passwords and then I try to login and is successful, however if for example I install on other device my project and set up my DB I enter to my system how can I access for first time if I dont have users created?
1) I tried to create user and password on my database but it cant recognize the password due to hashing methods.
How can i access for the first time and then create users as normal?
My login access controller:
public function login() {
//if already logged-in, redirect
if($this->Session->check('Auth.User')){
$this->redirect(array('action' => 'index'));
}
// if we get the post information, try to authenticate
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Bienvenido, '. $this->Auth->user('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Usuario o password invalidos'));
}
}
$this->layout = 'login';
}
appcontroller:
class AppController extends Controller {
//public $components = array('DebugKit.Toolbar');
public $components = array(
//'DebugKit.Toolbar',
'Session',
'Auth' => array(
'authorize' => 'Controller',
'actionPath' => 'controllers/',
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'You must be logged in to view this page.',
'loginError' => 'Invalid Username or Password entered, please try again.'
),
);
// only allow the login controllers only
public function beforeFilter() {
$this->Auth->allow('login','view','index','logout','getData');
}
public function isAuthorized($user) {
// Here is where we should verify the role and give access based on role
if (isset($user['role']) && $user['role'] === 'adm') {
return true;
}
if (in_array($this->action, array('add','getData','getDataArticulos','addDetFac','descargar','getNit'))) {
if (isset($user['role']) && $user['role'] === 'vend')
return true;
else
return $this->Session->setFlash(__('Acceso denegado.'), 'error');
}
return $this->Session->setFlash(__('Acceso denegado.'), 'error');
}
}
At first allow add method.
public function beforeFilter() {
$this->Auth->allow('login','view','index','logout','getData','add');
}
Then create a user, write in your browser URL your_project_path/users/add
After add 1st user remove add from Auth allow.
I would like to login on frontend and backend with different credentials, from different tables, so I now have different forms, models, rules, etc ...
I tryed to set stateKeyPrefix as Yii had, but it does not work.
Anyone know how to login how I want to?
The following method returns true, because I am already logged n on the frontend;
public function actionLogin() {
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginAdminForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
You should define stateKeyPrefix in user config:
'user'=>array(
'stateKeyPrefix'=>'yourDifferentPrefixForEveryDomain',
...
),
And different sessionName in session component:
'session' => array (
'sessionName' => 'differentSessionNameForEveryDomain',
...
),
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;
}
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'),
), ...