首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >用yii2进行注册接口+登录接口+带token就能登录+登录后的到底是谁?(一个人使用的版本)接口:

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

作者头像
贵哥的编程之路
发布2021-11-24 15:10:13
发布2021-11-24 15:10:13
7830
举报

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

代码语言:javascript
复制
/*注册*/
      /* $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):复制粘贴

代码语言:javascript
复制
<?php
namespace common\models;

class User extends /*\yii\base\Object*/ \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    /*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插入到数据库中)。

代码语言:javascript
复制
$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保持一致就可以登录了),并显示登录的是谁??? 核心代码:

代码语言:javascript
复制
 $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登录成功");
        }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/11/23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档