You may use [[isGuest]] to determine whether the current user is a guest or not. If the user is a guest, the [[identity]] property would return null. Otherwise, it would be an instance of IdentityInterface. You may call various methods to change the user authentication status: - User::login: sets the specified identity and remembers the authentication status in session and cookie. - User::logout: marks the user as a guest and clears the relevant information from session and cookie. - User::setIdentity: changes the user identity without touching session or cookie. This is best used in stateless RESTful API implementation. Note that User only maintains the user authentication status. It does NOT handle how to authenticate a user. The logic of how to authenticate a user should be done in the class implementing IdentityInterface. You are also required to set [[identityClass]] with the name of this class. User is configured as an application component in Application by default. You can access that instance via Yii::$app->user. You can modify its configuration by adding an array to your application config under components as it is shown in the following example: ~~~ 'user' => [ 'identityClass' => 'app\models\User', // User must implement the IdentityInterface 'enableAutoLogin' => true, 'loginUrl' => ['user/login'], ... ] ~~~
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends yii\base\Component
コード例 #1
1
 /**
  * @inheritdoc
  */
 public function afterLogout($identity)
 {
     parent::afterLogout($identity);
     // обновляем время авторизации и статус online
     if ($identity && $identity instanceof \nepster\users\models\User) {
         $identity->time_activity = time();
         $identity->save(false);
     }
 }
コード例 #2
0
 /**
  * check the permission, if we rewrite and controller, the controller id and module id is not changed
  * @param \yii\base\Action $action
  * @param \yii\web\User $user
  * @param \yii\web\Request $request
  * @return bool
  */
 public function matchActionAccess($action, $user, $request)
 {
     if ($user->getIsGuest()) {
         return false;
     }
     /** @var \core\auth\Module $authModule */
     $authModule = \Yii::$app->getModule('core_auth');
     foreach ($authModule->getAdmins() as $key => $admin) {
         if ($user->getIdentity()->username == $admin['username']) {
             return true;
         }
     }
     if ($action->controller->module instanceof Application) {
         $key = 'default' . '_' . $action->controller->id . '_' . $action->id;
     } else {
         $key = $action->getUniqueId();
         $key = explode('/', $key);
         array_shift($key);
         $key = implode('_', $key);
     }
     $key = lcfirst(implode('', array_map(function ($k) {
         return ucfirst($k);
     }, explode('-', $key))));
     return $user->can($key, $this->params);
 }
コード例 #3
0
 /**
  * Denies the access of the user.
  * The default implementation will redirect the user to the login page if he is a guest;
  * if the user is already logged, a 403 HTTP exception will be thrown.
  * @param Yii\web\User $user the current user
  * @throws Yii\web\ForbiddenHttpException if the user is already logged in.
  */
 protected function denyAccess($user)
 {
     if ($user->getIsGuest()) {
         $user->loginRequired();
     } else {
         $this->ajaxOnly();
     }
 }
コード例 #4
0
 /**
  * Denies the access of the user.
  * The default implementation will redirect the user to the login page if he is a guest;
  * if the user is already logged, a 403 HTTP exception will be thrown.
  * @param  User $user the current user
  * @throws ForbiddenHttpException if the user is already logged in.
  */
 protected function denyAccess($user)
 {
     if ($user->getIsGuest()) {
         $user->loginRequired();
     } else {
         throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
     }
 }
コード例 #5
0
ファイル: AccessControl.php プロジェクト: xidiao/gxfenxi
 /**
  * 拒绝访问
  * @param \yii\web\User $user
  * @throws ForbiddenHttpException
  */
 protected function denyAccess($user)
 {
     if ($user->getIsGuest()) {
         Yii::$app->getSession()->setFlash('danger', Yii::t('common', 'You have not login, please login first.'));
         $user->loginRequired();
     } else {
         //检查权限是否有配置
         //             $this->checkAuthItem();
         throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
     }
 }
コード例 #6
0
 /**
  * Проверка на возможность отображать элемент меню.
  *
  * @param array $item
  * @return bool
  */
 private function canShowMenuItem($item)
 {
     if (!isset($item['roles'])) {
         return true;
     }
     foreach ($item['roles'] as $role) {
         if ($this->user->can($role)) {
             return true;
         }
     }
     return false;
 }
コード例 #7
0
 /**
  * Matches the web User object against the specified platform roles.
  * 
  * @param \yii\web\User $user
  * @return bool
  */
 public function matchUserRoles($user)
 {
     if (empty($this->userRoles)) {
         return true;
     }
     foreach ($this->userRoles as $role) {
         if (Role::check($role, $user->getRole())) {
             return true;
         }
     }
     return false;
 }
コード例 #8
0
ファイル: Menu.php プロジェクト: pbabilas/bcode
 /**
  * @return string
  */
 public function run()
 {
     $li = [];
     /**
      * @var string $categoryName
      * @var array $modules
      */
     foreach ($this->itemsList as $categoryName => $modules) {
         $li[] = Html::tag('li', $categoryName, ['class' => 'header']);
         $hasAnyItem = false;
         /** @var Module $module */
         foreach ($modules as $module) {
             $modulePermissionName = sprintf('access%s', ucfirst($module->name));
             if ($this->user->can($modulePermissionName) == false) {
                 continue;
             }
             $hasAnyItem = true;
             if ($controllers = $module->getAdminControllers()) {
                 $isActive = $this->moduleName == $module->name;
                 $aContent = [];
                 if (count($controllers) > 1) {
                     $aContent[] = Html::tag('i', '', ['class' => sprintf('fa fa-%s', $module->icon)]);
                     $aContent[] = Html::tag('span', $module->long_name);
                     $aContent[] = Html::tag('i', '', ['class' => 'fa fa-angle-left pull-right']);
                     $a = Html::tag('a', join("\n", $aContent), ['href' => '#']);
                     $optionsMain = $isActive ? ['class' => 'treeview active'] : ['class' => 'treeview'];
                     $li_2 = [];
                     foreach ($controllers as $controller) {
                         $isActive = $this->moduleName == $module->name && $this->controllerName == $controller;
                         $icon = Html::tag('i', '', ['class' => 'fa fa-circle-o']);
                         $aContent2 = sprintf('%s `%s.%s`', $icon, $module->name, $controller);
                         $a2 = Html::tag('a', $aContent2, ['href' => sprintf('/admin/%s/%s', $module->name, $controller)]);
                         $options = $isActive ? ['class' => 'active'] : [];
                         $li_2[] = Html::tag('li', $a2, $options);
                     }
                     $ul_2 = Html::ul($li_2, ['class' => 'treeview-menu', 'encode' => false]);
                     $li[] = Html::tag('li', $a . "\n" . $ul_2, $optionsMain);
                 } else {
                     $aContent[] = Html::tag('i', '', ['class' => sprintf('fa fa-%s', $module->icon)]);
                     $aContent[] = Html::tag('span', $module->long_name);
                     $a = Html::tag('a', join("\n", $aContent), ['href' => sprintf('/admin/%s', $module->name)]);
                     $options = $isActive ? ['class' => 'active'] : [];
                     $li[] = Html::tag('li', $a, $options);
                 }
             }
         }
         if ($hasAnyItem == false) {
             array_pop($li);
         }
     }
     return Html::ul($li, ['class' => $this->defaultClassName, 'encode' => false]);
 }
コード例 #9
0
ファイル: TokenAuth.php プロジェクト: voodoo-mobile/yii2-api
 /**
  * Authenticates the current user.
  *
  * @param \yii\web\User     $user
  * @param \yii\web\Request  $request
  * @param \yii\web\Response $response
  *
  * @return \yii\web\IdentityInterface the authenticated user identity. If authentication information is not
  *                                    provided, null will be returned.
  * @throws \yii\web\UnauthorizedHttpException if authentication information is provided but is invalid.
  */
 public function authenticate($user, $request, $response)
 {
     /** @var array $request */
     /** @noinspection PhpUndefinedFieldInspection */
     $request = Json::decode($request->rawBody);
     $token = ArrayHelper::getValue($request, $this->accessTokenPath);
     if (!$token || !($identity = $user->loginByAccessToken($token))) {
         \Yii::$app->session->remove(TokenAuth::DEFAULT_TOKEN_PATH);
         throw new UnauthorizedHttpException('Incorrect or expired token provided');
     }
     \Yii::$app->session->set(TokenAuth::DEFAULT_TOKEN_PATH, $token);
     return $identity;
 }
コード例 #10
0
ファイル: AdminAccessControl.php プロジェクト: Liv1020/cms
 /**
  * Denies the access of the user.
  * The default implementation will redirect the user to the login page if he is a guest;
  * if the user is already logged, a 403 HTTP exception will be thrown.
  * @param User $user the current user
  * @throws ForbiddenHttpException if the user is already logged in.
  */
 protected function denyAccess($user)
 {
     $rr = new RequestResponse();
     if ($user->getIsGuest()) {
         $authUrl = UrlHelper::construct("admin/auth")->setCurrentRef()->enableAdmin()->createUrl();
         if (\Yii::$app->request->isAjax && !\Yii::$app->request->isPjax) {
             $rr->redirect = $authUrl;
             return (array) $rr;
         } else {
             \Yii::$app->getResponse()->redirect($authUrl);
         }
     } else {
         throw new ForbiddenHttpException(\Yii::t('yii', \Yii::t('app', 'You are not allowed to perform this action.')));
     }
 }
コード例 #11
0
ファイル: WebUser.php プロジェクト: ChristopheBrun/hLib
 /**
  * @inheritdoc
  */
 public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
 {
     if ($this->enableSession && (!$checkAjax || !Yii::$app->getRequest()->getIsAjax())) {
         Yii::$app->session->setFlash('flash-warning', HUsers::t('messages', 'This page is restricted to authenticated users'));
     }
     return parent::loginRequired($checkAjax, $checkAcceptHeader);
 }
コード例 #12
0
ファイル: User.php プロジェクト: vladim1/yii2-user
 /**
  * Initializes the User component
  */
 public function init()
 {
     if ($this->identityClass == null) {
         $this->identityClass = 'comyii\\user\\models\\User';
     }
     parent::init();
 }
コード例 #13
0
 public function interception($event)
 {
     if (!isset(Yii::$app->i18n->translations['db_rbac'])) {
         Yii::$app->i18n->translations['db_rbac'] = ['class' => 'yii\\i18n\\PhpMessageSource', 'sourceLanguage' => 'ru-Ru', 'basePath' => '@developeruz/db_rbac/messages'];
     }
     $route = Yii::$app->getRequest()->resolve();
     //Проверяем права по конфигу
     $this->createRule();
     $user = Instance::ensure(Yii::$app->user, User::className());
     $request = Yii::$app->getRequest();
     $action = $event->action;
     if (!$this->cheсkByRule($action, $user, $request)) {
         //И по AuthManager
         if (!$this->checkPermission($route)) {
             //Если задан $login_url и пользователь не авторизован
             if (Yii::$app->user->isGuest && $this->login_url) {
                 Yii::$app->response->redirect($this->login_url)->send();
                 exit;
             }
             //Если задан $redirect_url
             if ($this->redirect_url) {
                 Yii::$app->response->redirect($this->redirect_url)->send();
                 exit;
             } else {
                 throw new ForbiddenHttpException(Yii::t('db_rbac', 'Недостаточно прав'));
             }
         }
     }
 }
コード例 #14
0
ファイル: User.php プロジェクト: cdcchen/yii-plus
 public function init()
 {
     parent::init();
     if ($this->userConfig !== null) {
         $this->userConfig = Instance::ensure($this->userConfig, UserConfig::className());
     }
 }
コード例 #15
0
ファイル: RbacControl.php プロジェクト: wangpengzhen/web
 /**
  * 初始化方法
  */
 public function init()
 {
     parent::init();
     //获取user实例
     $this->user = Instance::ensure($this->user, User::className());
     $this->user_info = $this->user->identity;
 }
コード例 #16
0
ファイル: User.php プロジェクト: ahb360/cms
 public function afterLogin($identity, $cookieBased, $duration)
 {
     parent::afterLogin($identity, $cookieBased, $duration);
     $identity->failedAttempts = 0;
     $identity->lastLoggedInAt = time();
     $identity->save();
 }
コード例 #17
0
 /**
  * 
  * overwrite 存到session
  */
 public function getIdentity($autoRenew = true)
 {
     if (!Yii::$app->session["_userInfo"]) {
         Yii::$app->session["_userInfo"] = parent::getIdentity($autoRenew);
     }
     return Yii::$app->session["_userInfo"];
 }
コード例 #18
0
ファイル: User.php プロジェクト: rkit/bootstrap-yii2
 /**
  * Checks if the user can perform the operation as specified by the given permission.
  *
  * Note that you must configure "authManager" application component in order to use this method.
  * Otherwise an exception will be thrown.
  *
  * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
  * @param array $params name-value pairs that would be passed to the rules associated
  * with the roles and permissions assigned to the user. A param with name 'user' is added to
  * this array, which holds the value of [[id]].
  * @param boolean $allowCaching whether to allow caching the result of access check.
  * When this parameter is true (default), if the access check of an operation was performed
  * before, its result will be directly returned when calling this method to check the same
  * operation. If this parameter is false, this method will always call
  * [[\yii\rbac\ManagerInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
  * caching is effective only within the same request and only works when `$params = []`.
  * @return boolean whether the user can perform the operation as specified by the given permission.
  * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
  */
 public function can($permissionName, $params = [], $allowCaching = true)
 {
     if (!$this->getIsGuest() && $this->getIdentity()->isSuperUser()) {
         return true;
     }
     return parent::can($permissionName, $params, $allowCaching);
 }
コード例 #19
0
ファイル: AccessControl.php プロジェクト: WiconWang/CS-Iris
 /**
  * Get user
  * @return User
  */
 public function getUser()
 {
     if (!$this->_user instanceof User) {
         $this->_user = Instance::ensure($this->_user, User::className());
     }
     return $this->_user;
 }
コード例 #20
0
 public function beforeValidate()
 {
     if ($this->getIsNewRecord()) {
         $this->created_at = time();
     }
     $this->updated_at = time();
     return parent::beforeValidate();
 }
コード例 #21
0
 /**
  * 
  * 管理員就全給過
  * @param type $permissionName
  * @param type $params
  * @param type $allowCaching
  * @return boolean
  */
 public function can($permissionName, $params = [], $allowCaching = true)
 {
     //直接給所有權限
     if ($this->identity->role == 1) {
         return true;
     }
     return parent::can($permissionName, $params, $allowCaching);
 }
コード例 #22
0
ファイル: Auth.php プロジェクト: kalyabin/comitka
 /**
  * Logout user if it's blocked
  */
 public function renewAuthStatus()
 {
     parent::renewAuthStatus();
     /* @var $identity User */
     if ($this->identity instanceof User && !$this->identity->canSignIn() && !$this->isGuest) {
         $this->logout();
     }
 }
コード例 #23
0
ファイル: User.php プロジェクト: yanglaw/yii2-auth
 public function checkAccess($operation, $params = [], $allowCaching = true)
 {
     // Always return true when SuperAdmin user
     if ($this->getIsSuperAdmin()) {
         return true;
     }
     return parent::can($operation, $params, $allowCaching);
 }
コード例 #24
0
 /**
  * @param string $default
  *
  * @return string
  */
 protected function getIdentifier($default)
 {
     $id = $default;
     if ($this->user instanceof User && !$this->user->getIsGuest()) {
         $id = $this->user->getId();
     }
     return $id;
 }
コード例 #25
0
ファイル: User.php プロジェクト: gromver/yii2-platform
 /**
  * @inheritdoc
  */
 public function can($permissionName, $params = [], $allowCaching = true)
 {
     // Always return true when SuperAdmin user
     if ($this->getIsSuperAdmin()) {
         return true;
     }
     return parent::can($permissionName, $params, $allowCaching);
 }
コード例 #26
0
ファイル: User.php プロジェクト: travis83bui/yii2-user
 /**
  * @inheritdoc
  */
 protected function afterLogin($identity, $cookieBased, $duration)
 {
     parent::afterLogin($identity, $cookieBased, $duration);
     if (\Yii::$app->getModule('user')->trackable) {
         $this->identity->setAttribute('logged_in_from', ip2long(\Yii::$app->getRequest()->getUserIP()));
         $this->identity->setAttribute('logged_in_at', time());
         $this->identity->save(false);
     }
 }
コード例 #27
0
ファイル: AccessRule.php プロジェクト: csboyty/jinyuanwuye
 /**
  * 覆写方法
  * @param \yii\web\User $user
  * @return bool|void
  */
 protected function matchRole($user)
 {
     //如果没有给点roles,那么是所有的角色都可以用
     if (count($this->roles) === 0) {
         return true;
     }
     //分析所有配资了得roles,在controller的behaviors里面配置
     foreach ($this->roles as $role) {
         //?代表游客
         if ($role === "?") {
             return true;
         } elseif (!$user->getIsGuest() && $role === $user->identity->role) {
             //判断其他的权限
             return true;
         }
     }
     return false;
 }
コード例 #28
0
ファイル: User.php プロジェクト: igaojie/yii-QA
 /**
  * @inheritdoc
  */
 protected function afterLogin($identity, $cookieBased, $duration)
 {
     $identity = $this->identity;
     $identity->setAttribute('last_visit_at', TIMESTAMP);
     //        $identity->setAttribute('last_login_ip', ip2long(Yii::$app->getRequest()->getUserIP()));
     $identity->setAttribute('last_login_ip', Yii::$app->getRequest()->getUserIP());
     $identity->save(false);
     parent::afterLogin($identity, $cookieBased, $duration);
 }
コード例 #29
0
ファイル: User.php プロジェクト: hughcube/yii2-web
 public function logout($destroySession = true)
 {
     if (!$this->getIsGuest()) {
         /** @type IdentityAuthTrait $identity */
         $identity = $this->getIdentity();
         return $identity->deleteToken($this->tokenType);
     }
     return parent::logout($destroySession);
 }
コード例 #30
0
 public function checkEmail($attribute)
 {
     if (!$this->hasErrors()) {
         $user = User::find()->where(['email' => $attribute])->one();
         if (!$user) {
             $this->addError($attribute, 'Incorrect email.');
         }
     }
 }