This interface can typically be implemented by a user model class. For example, the following code shows how to implement this interface by a User ActiveRecord class: ~~~ class User extends ActiveRecord implements IdentityInterface { public static function findIdentity($id) { return static::findOne($id); } public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['access_token' => $token]); } public function getId() { return $this->id; } public function getAuthKey() { return $this->authKey; } public function validateAuthKey($authKey) { return $this->authKey === $authKey; } } ~~~
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Ejemplo n.º 1
0
 /**
  * Inserts or updates RemoteUser.
  * @return IdentityInterface user
  */
 public function setRemoteUser(ClientInterface $client, IdentityInterface $user)
 {
     $model = $this->getRemoteUser($client);
     $model->client_id = $user->getId();
     $model->save();
     return $user;
 }
Ejemplo n.º 2
0
 /**
  * Sends an identity cookie.
  * This method is used when [[enableAutoLogin]] is true.
  * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
  * information in the cookie.
  * @param IdentityInterface $identity
  * @param integer $duration number of seconds that the user can remain in logged-in status.
  * @see loginByCookie()
  */
 protected function sendIdentityCookie($identity, $duration)
 {
     $cookie = new Cookie($this->identityCookie);
     $cookie->value = json_encode([$identity->getId(), $identity->getAuthKey(), $this->getRole(), $duration], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
     $cookie->expire = time() + $duration;
     Yii::$app->getResponse()->getCookies()->add($cookie);
 }
Ejemplo n.º 3
0
 /**
  * Before user sign in. Returns true if user can sign in.
  *
  * @param IdentityInterface $identity the user identity information
  * @param boolean $cookieBased whether the login is cookie-based
  * @param integer $duration number of seconds that the user can remain in logged-in status.
  * If 0, it means login till the user closes the browser or the session is manually destroyed.
  * @return boolean whether the user should continue to be logged in
  */
 public function beforeLogin($identity, $cookieBased, $duration)
 {
     /* @var $identity User */
     if ($identity instanceof User && !$identity->canSignIn()) {
         return false;
     }
     return parent::beforeLogin($identity, $cookieBased, $duration);
 }
Ejemplo n.º 4
0
 /**
  * AssignmentModel constructor.
  *
  * @param IdentityInterface $user
  * @param array $config
  *
  * @throws InvalidConfigException
  */
 public function __construct(IdentityInterface $user, $config = [])
 {
     $this->user = $user;
     $this->userId = $user->getId();
     $this->manager = Yii::$app->authManager;
     if ($this->userId === null) {
         throw new InvalidConfigException('The "userId" property must be set.');
     }
     parent::__construct($config);
 }
Ejemplo n.º 5
0
 /**
  * @param array $relations list of model relations to check, supports dot notation for indirect relations
  * @param IdentityInterface $user if null, Yii::$app->user->identity will be used
  * @return bool
  */
 public function isRelated($relations, $user = null)
 {
     /** @var \yii\db\ActiveRecord $owner */
     $owner = $this->owner;
     if ($owner->getIsNewRecord()) {
         return true;
     }
     $key = sha1(serialize($relations) . $user->getId());
     $token = !YII_DEBUG ? '' : $this->modelClass . ' (' . print_r($owner->getPrimaryKey(), true) . ') through ' . json_encode($relations) . ' for ' . $user->getId();
     \Yii::trace('Checking access to ' . $token, 'relationAuthorizer');
     if (array_key_exists($key, $this->isRelatedCache)) {
         return $this->isRelatedCache[$key];
     }
     $schema = $owner->getDb()->getSchema();
     $t = $schema->quoteSimpleTableName('t');
     $pks = $owner->primaryKey();
     $pkConditions = [];
     $pkParams = [];
     foreach ($pks as $index => $pk) {
         $pkConditions[$t . '.' . $schema->quoteSimpleColumnName($pk)] = ':pk' . $index;
         $pkParams[':pk' . $index] = $owner->{$pk};
     }
     $pkConditions = 'ROW(' . implode(',', array_keys($pkConditions)) . ') ' . '= ROW(' . implode(',', $pkConditions) . ')';
     $relationQuery = $owner->find()->getRelatedUserQuery($owner, $relations, $user, $pkConditions, $pkParams, $owner->primaryKey);
     if (!empty($relationQuery->where)) {
         $query = 'SELECT ' . $owner->getDb()->getQueryBuilder()->buildCondition($relationQuery->where, $relationQuery->params);
         $match = $owner->getDb()->createCommand($query, $relationQuery->params)->queryScalar();
         if ($match) {
             \Yii::trace('Allowing access to ' . $token, 'relationAuthorizer');
             return $this->isRelatedCache[$key] = true;
         } else {
             \Yii::trace('Denying access to ' . $token . ', not related ' . 'through existing relations.', 'relationAuthorizer');
             return $this->isRelatedCache[$key] = false;
         }
     }
     // model and user has no direct or indirect relation spanning at least 1 model
     \Yii::trace('Denying access to ' . $token . ', no common relations found.', 'relationAuthorizer');
     return $this->isRelatedCache[$key] = null;
 }
Ejemplo n.º 6
0
 /**
  * Connects auth client with user.
  *
  * @param ClientInterface $client auth client
  * @param IdentityInterface $identity the user identity
  * @return boolean whether the auth client is connected to user
  */
 public function connectAuthClient(ClientInterface $client, IdentityInterface $identity)
 {
     /** @var Auth $authClass */
     $authClass = $this->module->authModel;
     /** @var Auth $auth */
     $auth = $authClass::findByClient($client);
     if (!$auth) {
         $auth = $authClass::getInstance($client);
     }
     if (!$auth->user || $auth->isNewRecord) {
         $auth->user_id = $identity->getId();
         $auth->save();
     }
     return $auth->user_id ? true : false;
 }
Ejemplo n.º 7
0
 /**
  * Set owner of file
  * @param IdentityInterface $user
  * @return $this
  */
 public function setUser(IdentityInterface $user)
 {
     $this->user_id = $user->getId();
     return $this;
 }
 /**
  * Returns queries that contain necessary joins and condition
  * to select only those records which are related directly or indirectly
  * with the current user.
  * @param ActiveRecord $model     must have the AuthorizerBehavior attached
  * @param array $relations        list of model relations to check, supports dot notation for indirect relations
  * @param IdentityInterface $user if null, Yii::$app->user->identity will be used
  * @param array $baseConditions
  * @param array $baseParams
  * @return ActiveQuery[]
  */
 public function getCompositeRelatedUserQuery($model, array $relations, $user, $baseConditions = [], $baseParams = [])
 {
     $schema = $model->getDb()->getSchema();
     $userPk = array_map([$schema, 'quoteSimpleColumnName'], $user::primaryKey());
     $result = [];
     if (count($userPk) > 1) {
         throw new InvalidCallException('Composite primary key in User model is not supported.');
     } else {
         $userPk = reset($userPk);
     }
     $mainQuery = $model->find();
     if (empty($mainQuery->from)) {
         $mainQuery->from = [$model->tableName() . ' t'];
     }
     $mainQuery->distinct = true;
     foreach ($relations as $relationName) {
         if (($pos = strpos($relationName, '.')) === false) {
             $relation = $model->getRelation($relationName);
             if (!$relation->multiple) {
                 $query = $mainQuery;
             } else {
                 $query = $model->find();
                 if (empty($query->from)) {
                     $query->from = [$model->tableName() . ' t'];
                 }
             }
             $query->innerJoinWith([$relationName => function ($query) use($relation, $relationName) {
                 /** @var ActiveRecord $modelClass */
                 $modelClass = $relation->modelClass;
                 return $query->from([$modelClass::tableName() . ' ' . $relationName]);
             }]);
             $column = $schema->quoteSimpleTableName($relationName) . '.' . $userPk;
             $query->orWhere($column . ' IS NOT NULL AND ' . $column . ' = :current_user_id');
             $query->addParams([':current_user_id' => $user->getId()]);
             if ($relation->multiple) {
                 $query->andWhere($baseConditions, $baseParams);
                 $result[] = $query;
             }
         } else {
             $userRelationName = substr($relationName, $pos + 1);
             $relationName = substr($relationName, 0, $pos);
             $relation = $model->getRelation($relationName);
             /** @var ActiveRecord $relationModel */
             $relationModel = new $relation->modelClass();
             $userRelation = $relationModel->getRelation($userRelationName);
             $userQuery = $relationModel->find();
             if (empty($userQuery->from)) {
                 $userQuery->from = [$relationModel->tableName() . ' t'];
             }
             $userQuery->distinct();
             $userQuery->select($this->quoteColumn('t', $relationModel::primaryKey(), $schema));
             //$userQuery->innerJoinWith($userRelationName);
             $userQuery->innerJoinWith([$userRelationName => function ($query) use($userRelation, $userRelationName) {
                 /** @var ActiveRecord $modelClass */
                 $modelClass = $userRelation->modelClass;
                 return $query->from([$modelClass::tableName() . ' ' . $userRelationName]);
             }]);
             $userQuery->andWhere($schema->quoteSimpleTableName($userRelationName) . '.' . $userPk . ' = :current_user_id');
             $command = $userQuery->createCommand($model->getDb());
             $query = $model->find();
             if (empty($query->from)) {
                 $query->from = [$model->tableName() . ' t'];
             }
             $query->distinct();
             //$query->innerJoinWith($relationName);
             $query->innerJoinWith([$relationName => function ($query) use($relation, $relationName) {
                 /** @var ActiveRecord $modelClass */
                 $modelClass = $relation->modelClass;
                 return $query->from([$modelClass::tableName() . ' ' . $relationName]);
             }]);
             $fk = $this->quoteColumn($relationName, $relationModel::primaryKey(), $schema);
             $query->orWhere('COALESCE(' . (is_array($relationModel::primaryKey()) ? 'ROW(' . $fk . ')' : $fk) . ' IN (' . $command->getSql() . '), false)');
             $query->addParams([':current_user_id' => $user->getId()]);
             $query->andWhere($baseConditions, $baseParams);
             $result[] = $query;
         }
     }
     $mainQuery->andWhere($baseConditions, $baseParams);
     $result[] = $mainQuery;
     return $result;
 }