zl程序教程

您现在的位置是:首页 >  其他

当前栏目

用yii2进行注册接口+登录接口+带token就能登录+登录后的到底是谁?(一个人使用的版本)接口:

2023-03-15 23:27:46 时间

第一步: 注册:核心代码:

/*注册*/
      /* $request = Yii::$app->request;
        $username = $request->post('username');
        $password = $request->post('password');
        Yii::$app->db->createCommand()->insert('user', [
            'username' => $username,
            'password' => $password,
        ])->execute();*/

postman下:

mysql结构:(重点:id自增)

第二步: 在common/model/下里面新建一张表(User.php):复制粘贴

<?php
namespace commonmodels;

class User extends /*yiiaseObject*/ yiidbActiveRecord implements yiiwebIdentityInterface
{
    /*public $id;
    public $username;
    public $password;
    public $authKey;
    public $accessToken;

    private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'admin',
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ],
        '101' => [
            'id' => '101',
            'username' => 'demo',
            'password' => 'demo',
            'authKey' => 'test101key',
            'accessToken' => '101-token',
        ],
    ];
    */

    /**
     * @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);
        //return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
        /*foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;*/
    }

    /**
     * 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;
        /*foreach (self::$users as $user) {
            if (strcasecmp($user['username'], $username) === 0) {
                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;
    }
    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
        $this->generateAuthKey();
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Generates new token for email verification
     */
    public function generateEmailVerificationToken()
    {
        $this->verification_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

token是什么?

第三步:第一次登录的时候生成token:然后我们可以拿着这个token去登录,不需要用户名+密码了.这相当于一个识别吧.

生成token的核心代码(并把token插入到数据库中)。

$request = Yii::$app->request;
        $username = $request->post('username');
        $password = $request->post('password');

        //echo $authKey;
        $id = Yii::$app->db->createCommand('SELECT id FROM user WHERE username=:username and password=:password')
            ->bindValue(':username', $username)
            ->bindValue(':password', $password)
            ->queryOne();
        if($id) {
            $authKey=Yii::$app->security->generateRandomString();
            Yii::$app->db->createCommand()->update("{{%user}}", [
                "authKey" => $authKey
            ], ['id' => $id])->execute();
            return $this->json("token=" . $authKey);
        }

第四步:带token的登录:(数据库中的token与输入的token保持一致就可以登录了),并显示登录的是谁??? 核心代码:

 $request = Yii::$app->request;
        $token = $request->post("token");
        $username = Yii::$app->db->createCommand("SELECT username FROM user WHERE authKey=:token")
            ->bindValue(':token', $token)
            ->queryOne();
        if($username)
        {
            return $this->json($username,"使用token登录成功");
        }