用户登录——Yii2框架图书管理系统(Ⅰ)

0x00

Yii2 basic 版本中提供了login验证的接口,但是默认是从一个数组验证用户名和密码的,而我们的需要时从数据库读取记录,验证身份。

0x01

首先在数据库中建立一个表user。
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(32) NOT NULL, `authKey` varchar(100) NOT NULL DEFAULT '', `accessToken` varchar(100) NOT NULL DEFAULT '', `isAdmin` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`)

0x02

模型User.php如下,替换掉原来的User.php就可以实现数据表验证登陆了

namespace app\models;

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'user';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['username', 'password'], 'required'],
        [['username'], 'string', 'max' => 50],
        [['password'], 'string', 'max' => 32],
        [['authKey'], 'string', 'max' => 100],
        [['accessToken'], 'string', 'max' => 100],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'username' => 'Username',
        'password' => 'Password',
        'authKey' => 'AuthKey',
        'accessToken' => 'AccessToken',
    ];
}

/**
 * @inheritdoc
 */
public static function findIdentity($id)
{
    return static::findOne($id);        
}

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $type = null)
{
    return static::findOne(['access_token' => $token]);
}

/**
 * Finds user by username
 *
 * @param  string      $username
 * @return static|null
 */
public static function findByUsername($username)
{
      $user = User::find()
        ->where(['username' => $username])
        ->asArray()
        ->one();

        if($user){
        return new static($user);
    }
    return null;      
}

/**
 * @inheritdoc
 */
public function getId()
{
    return $this->id;
}

/**
 * @inheritdoc
 */
public function getAuthKey()
{
    return $this->authKey;
}

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey)
{
    return $this->authKey === $authKey;
}

/**
 * Validates password
 *
 * @param  string  $password password to validate
 * @return boolean if password provided is valid for current user
 */
public function validatePassword($password)
{
    return $this->password === $password;
}
}

0x03

findIdentity是根据传递的id返回对应的用户信息,getId返回用户id,getAuthKey和validateAuthKey是作用于登陆中的--记住我。这个authKey是唯一的,当再次登陆时,从cookie中获取authKey传递给validateAuthKey,验证通过,就登陆成功。

0x04 权限管理

Yii::$app->user->isGuest判断是否登录。
Yii::$app->identity->user 在这个变量下可以获取user表的信息用作验证。
例如!Yii::$app->user->isGuest&&Yii::$app->identity->user->isAdmin判断是否为管理员。

0x05 Open Source

xmsec/BookMnagementSystem

Updated At: Author:xmsec
Chief Water dispenser Manager of Lancet, delivering but striving.
Github
comments powered by Disqus