Example #1
0
 /**
  * Get user
  * @return User
  */
 public function getUser()
 {
     if (!$this->_user instanceof User) {
         $this->_user = Instance::ensure($this->_user, User::className());
     }
     return $this->_user;
 }
 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', 'Недостаточно прав'));
             }
         }
     }
 }
Example #3
0
 /**
  * 初始化方法
  */
 public function init()
 {
     parent::init();
     //获取user实例
     $this->user = Instance::ensure($this->user, User::className());
     $this->user_info = $this->user->identity;
 }
Example #4
0
 /**
  * Initializes the [[rules]] array by instantiating rule objects from configurations.
  */
 public function init()
 {
     parent::init();
     $this->user = Instance::ensure($this->user, User::className());
     if ($this->user->identity !== null) {
         $this->user->identity->getRules();
     }
 }
Example #5
0
 /**
  * when user login in backend , it should be 'Administrator' or ,'Merchant'
  */
 public static function beforeLogin()
 {
     Event::on(\yii\web\User::className(), \yii\web\User::EVENT_BEFORE_LOGIN, function ($event) {
         $user = $event->identity;
         $auth = new DbManager();
         $auth->init();
         $role = $auth->getRolesByUser($user->id);
         $event->isValid = in_array(current($role)->name, ['Administrator', 'Merchant']);
     });
 }
Example #6
0
 /**
  * @param \yii\base\Application $app
  */
 public function bootstrap($app)
 {
     Event::on(User::className(), User::EVENT_AFTER_LOGIN, function () {
         $storage = Instance::ensure(\Yii::$app->cart->storage, MultipleStorage::className());
         if (get_class($storage) == 'hscstudio\\cart\\MultipleStorage') {
             $cart = Instance::ensure(\Yii::$app->cart, Cart::className());
             $storage->sync($cart);
         }
     });
 }
Example #7
0
 /**
  * Initialize
  * @throws \yii\base\InvalidConfigException
  */
 public function init()
 {
     parent::init();
     $this->db = Instance::ensure($this->db, Connection::className());
     $this->authManager = Instance::ensure($this->authManager, BaseManager::className());
     $this->user = Instance::ensure($this->user, User::className());
     if (empty($this->cache)) {
         $this->cache = $this->createCacheComponent();
     } else {
         $this->cache = Instance::ensure($this->cache, Cache::className());
     }
 }
Example #8
0
 /**
  * Initializes the [[rules]] array by instantiating rule objects from configurations.
  */
 public function init()
 {
     if ($this->user === null) {
         $this->user = Adm::getInstance()->user;
     }
     $this->user = Instance::ensure($this->user, User::className());
     foreach ($this->rules as $i => $rule) {
         if (is_array($rule)) {
             $this->rules[$i] = Yii::createObject(array_merge($this->ruleConfig, $rule));
         }
     }
 }
Example #9
0
 /**
  * 注册登录事件
  * @throws \Exception
  * @return boolean
  */
 public static function userLoginAfter()
 {
     Event::on(User::className(), User::EVENT_AFTER_LOGIN, function ($event) {
         // user identity
         if (isset($event->identity) && $event->identity instanceof \common\models\User) {
             $user = $event->identity;
             $attrs = [];
             foreach ($attrs as $_attr) {
                 \Yii::$app->session->set($_attr, isset($user->{$_attr}) ? $user->{$_attr} : false);
             }
         }
         return true;
     });
 }
Example #10
0
 public function init()
 {
     $this->user = Instance::ensure($this->user, User::className());
     $rolesObject = Yii::$app->authManager->getRolesByUser($this->user->id);
     if (!empty($rolesObject)) {
         foreach ($rolesObject as $roles => $object) {
             foreach ($object->data as $route) {
                 $this->_actions[] = $route;
             }
         }
     }
     $this->rules = [['actions' => $this->_actions, 'allow' => true]];
     parent::init();
 }
Example #11
0
 public function interception($event)
 {
     $route = Yii::$app->getRequest()->resolve();
     //Проверяем права по конфигу
     $this->createRule();
     $user = Instance::ensure(Yii::$app->user, User::className());
     $request = Yii::$app->getRequest();
     $action = $event->sender->requestedAction;
     if (!$this->cheсkByRule($action, $user, $request)) {
         //И по AuthManager
         if (!$this->checkPermission($route)) {
             throw new BadRequestHttpException('Не достаточно прав');
         }
     }
 }
Example #12
0
 public function init()
 {
     /** @var $module Module */
     if (empty($this->user) && ($module = Yii::$app->getModule('admin')) != null) {
         $this->user = $module->adminComponent;
     }
     ActionFilter::init();
     if (empty($this->rules)) {
         $this->rules = [['actions' => [], 'allow' => true, 'roles' => ['@']]];
     }
     $this->user = Instance::ensure($this->user, User::className());
     foreach ($this->rules as $i => $rule) {
         if (is_array($rule)) {
             $this->rules[$i] = Yii::createObject(array_merge($this->ruleConfig, $rule));
         }
     }
 }
Example #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)) {
             throw new ForbiddenHttpException(Yii::t('db_rbac', 'Недостаточно прав'));
         }
     }
 }
 /**
  * Run a generation of swagger json-document
  * @throws \yii\base\InvalidConfigException
  */
 public function actionJson()
 {
     // workaround for identity absence in console application
     Yii::$container->set('user', ['class' => User::className(), 'identityClass' => 'common\\models\\User']);
     // Document generation
     $doc = new Document();
     Yii::$app->set('doc', $doc);
     $controllers = $this->getControllers();
     /** @var \yii\base\Controller $controller */
     foreach ($controllers as $key => $controller) {
         $tag = new Tag();
         $tag->name = $key;
         $doc->addTag($tag);
         $actions = $this->getActions($controller);
         foreach ($actions as $actionName => $action) {
             $doc->handleAction($action);
         }
     }
     $doc->generateFile(Yii::getAlias($this->module->jsonPath));
     $this->stdout('Done' . PHP_EOL);
 }
Example #15
0
 /** @inheritdoc */
 public function bootstrap($app)
 {
     /** @var $module Module */
     if ($app->hasModule('users') && ($module = $app->getModule('users')) instanceof Module) {
         $this->_modelMap = array_merge($this->_modelMap, $module->modelMap);
         foreach ($this->_modelMap as $name => $definition) {
             $class = "mii\\modules\\users\\models\\" . $name;
             \Yii::$container->set($class, $definition);
             $modelName = is_array($definition) ? $definition['class'] : $definition;
             $module->modelMap[$name] = $modelName;
             if (in_array($name, ['User', 'Profile', 'Token', 'Account'])) {
                 \Yii::$container->set($name . 'Query', function () use($modelName) {
                     return $modelName::find();
                 });
             }
         }
         \Yii::$container->setSingleton(Finder::className(), ['userQuery' => \Yii::$container->get('UserQuery'), 'profileQuery' => \Yii::$container->get('ProfileQuery'), 'tokenQuery' => \Yii::$container->get('TokenQuery'), 'accountQuery' => \Yii::$container->get('AccountQuery')]);
         if ($app instanceof ConsoleApplication) {
             $module->controllerNamespace = 'mii\\modules\\users\\commands';
             $app->get('i18n')->translations['users*'] = ['class' => PhpMessageSource::className(), 'basePath' => __DIR__ . '/messages'];
         } else {
             try {
                 $app->user->enableAutoLogin = true;
                 $app->user->loginUrl = ['/users/security/login'];
                 $app->user->identityClass = $module->modelMap['User'];
             } catch (InvalidConfigException $e) {
                 $app->set('user', ['class' => User::className(), 'enableAutoLogin' => true, 'loginUrl' => ['/users/security/login'], 'identityClass' => $module->modelMap['User']]);
             }
             $configUrlRule = ['prefix' => $module->urlPrefix, 'rules' => $module->urlRules];
             if ($module->urlPrefix != 'users') {
                 $configUrlRule['routePrefix'] = 'users';
             }
             $app->get('urlManager')->rules[] = new GroupUrlRule($configUrlRule);
             $app->get('urlManager')->addRules(['PUT,PATCH /' . $this->id . '/apis/<id>' => $this->id . '/api/update', 'DELETE /' . $this->id . '/apis/<id>' => $this->id . '/api/delete', 'GET,HEAD /' . $this->id . '/apis/<id>' => $this->id . '/api/view', 'POST /' . $this->id . '/apis' => $this->id . '/api/create', 'GET,HEAD /' . $this->id . '/apis' => $this->id . '/api/index', 'OPTIONS /' . $this->id . '/apis/<id>' => $this->id . '/api/options', 'OPTIONS /' . $this->id . '/apis' => $this->id . '/api/options'], false);
             if (!$app->has('authClientCollection')) {
                 $app->set('authClientCollection', ['class' => Collection::className()]);
             }
         }
         $app->get('i18n')->translations['users*'] = ['class' => PhpMessageSource::className(), 'basePath' => __DIR__ . '/messages'];
         $defaults = ['welcomeSubject' => \Yii::t('users', 'Welcome to {0}', \Yii::$app->name), 'confirmationSubject' => \Yii::t('users', 'Confirm account on {0}', \Yii::$app->name), 'reconfirmationSubject' => \Yii::t('users', 'Confirm email change on {0}', \Yii::$app->name), 'recoverySubject' => \Yii::t('users', 'Complete password reset on {0}', \Yii::$app->name)];
         \Yii::$container->set('mii\\modules\\users\\Mailer', array_merge($defaults, $module->mailer));
     }
 }
Example #16
0
 public function getUser()
 {
     return $this->hasOne(User::className(), ['id_user' => 'id']);
 }
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     $this->user = Instance::ensure($this->user, User::className());
 }
Example #18
0
 /**
  * Bootstrap method to be called during application bootstrap stage.
  * @param Application $app the application currently running
  */
 public function bootstrap($app)
 {
     /**
      * Move orders/order params from guest to logged/signed user
      */
     Event::on(\yii\web\User::className(), \yii\web\User::EVENT_AFTER_LOGIN, function ($event) {
         /** @var UserEvent $event */
         $orders = \Yii::$app->session->get('orders', []);
         foreach ($orders as $k => $id) {
             /** @var app\modules\shop\models\Order $order */
             $order = app\modules\shop\models\Order::findOne(['id' => $id]);
             if (!empty($order) && 0 === intval($order->user_id)) {
                 $order->user_id = $event->identity->id;
                 $order->save();
             }
         }
     });
 }
Example #19
0
<?php

/**
 * @author Eugene Terentev <*****@*****.**>
 */
\yii\base\Event::on(\yii\web\User::className(), \yii\web\User::EVENT_AFTER_LOGIN, function ($event) {
    //同步登陆ucenter
    \common\util\UcenterUtil::syncLogin($event);
    //记录前台登陆日志
    $user = $event->identity;
    $model = new \common\models\UserLoginLog();
    $model->user_id = $user->id;
    $model->username = $user->username;
    $model->login_ip = \Yii::$app->request->getUserIP();
    $model->login_time = time();
    $model->os = \Yii::$app->request->getUserAgent();
    $model->category = __METHOD__;
    $model->save(false);
});
//同步退出ucenter
\yii\base\Event::on(\yii\web\User::className(), \yii\web\User::EVENT_AFTER_LOGOUT, function ($event) {
    \common\util\UcenterUtil::logout();
});
//同步删除ucenter的用户
\yii\base\Event::on(\dektrium\user\models\User::className(), \dektrium\user\models\User::EVENT_AFTER_DELETE, function ($event) {
    $ucUser = \common\util\UcenterUtil::getUser($event->sender->username);
    \common\util\UcenterUtil::ucUserDelete($ucUser[0]);
    //删除discuz中common_member中用户信息
    $dzHelper = new \common\util\DzHelper();
    $dzHelper->deleteDzUserByUsername($ucUser[1]);
});
Example #20
0
 /**
  * Initializes the [[rules]] array by instantiating rule objects from configurations.
  */
 public function init()
 {
     parent::init();
     $this->user = Instance::ensure($this->user, User::className());
     foreach ($this->rules as $i => $rule) {
         if (is_array($rule)) {
             $this->rules[$i] = Yii::createObject(array_merge($this->ruleConfig, $rule));
         }
     }
 }
Example #21
0
 /**
  * Tests login method.
  */
 public function testLogin()
 {
     $user = \Yii::createObject(User::className());
     test::double(Finder::className(), ['findUserByUsernameOrEmail' => $user]);
     $form = Yii::createObject(LoginForm::className());
     $form->beforeValidate();
     test::double($form, ['validate' => false]);
     verify($form->login())->false();
     test::double($form, ['validate' => true]);
     test::double(\yii\web\User::className(), ['login' => false]);
     verify($form->login())->false();
     test::double(\yii\web\User::className(), ['login' => true]);
     verify($form->login())->true();
 }
Example #22
0
 /**
  * Initializes the class map.
  */
 protected function initClassMap()
 {
     $this->classMap = ArrayHelper::merge([self::CLASS_ACCOUNT => Account::className(), self::CLASS_TOKEN => AccountToken::className(), self::CLASS_PROVIDER => AccountProvider::className(), self::CLASS_LOGIN_HISTORY => AccountLoginHistory::className(), self::CLASS_PASSWORD_HISTORY => AccountPasswordHistory::className(), self::CLASS_LOGIN_FORM => LoginForm::className(), self::CLASS_PASSWORD_FORM => PasswordForm::className(), self::CLASS_SIGNUP_FORM => SignupForm::className(), self::CLASS_CONNECT_FORM => ConnectForm::className(), self::CLASS_FORGOT_PASSWORD_FORM => ForgotPasswordForm::className(), self::CLASS_WEB_USER => User::className(), self::CLASS_CAPTCHA => Captcha::className(), self::CLASS_CAPTCHA_ACTION => CaptchaAction::className(), self::CLASS_PASSWORD_BEHAVIOR => PasswordAttributeBehavior::className(), self::CLASS_PASSWORD_VALIDATOR => PasswordStrengthValidator::className()], $this->classMap);
 }
Example #23
0
 /**
  * Bootstrap method to be called during application bootstrap stage.
  * @param Application $app the application currently running
  */
 public function bootstrap($app)
 {
     /**
      * Move orders/order params from guest to logged/signed user
      */
     Event::on(\yii\web\User::className(), \yii\web\User::EVENT_AFTER_LOGIN, [app\modules\shop\handlers\UserHandler::className(), 'moveOrdersGuestToRegistered']);
 }
Example #24
0
 /**
  * @param array $roles
  * @return bool
  */
 private static function checkAccessRoles($roles)
 {
     if (empty($roles)) {
         return false;
     }
     /** @var User $user */
     $user = Instance::ensure('user', User::className());
     $roles = ArrayHelper::toArray($roles);
     foreach ($roles as $role) {
         if ($role === '?' && $user->getIsGuest()) {
             return true;
         } elseif ($role === '@' && !$user->getIsGuest()) {
             return true;
         } elseif ($user->can($role)) {
             return true;
         }
     }
     return false;
 }
Example #25
0
 /**
  * Check if the current user has access to the audit functionality
  * @return bool
  * @throws \yii\base\InvalidConfigException
  */
 public function checkAccess()
 {
     if ($this->accessUsers === null && $this->accessRoles === null) {
         return true;
     }
     $user = \yii\di\Instance::ensure('user', \yii\web\User::className());
     if ($this->accessUsers && in_array(Yii::$app->user->id, $this->accessUsers)) {
         return true;
     }
     if ($this->accessRoles) {
         foreach ($this->accessRoles as $role) {
             if ($role === '?') {
                 if ($user->getIsGuest()) {
                     return true;
                 }
             } elseif ($role === '@') {
                 if (!$user->getIsGuest()) {
                     return true;
                 }
             } elseif ($user->can($role)) {
                 return true;
             }
         }
     }
     return false;
 }