Yii2 登录Model

<?php

namespace app\models;

use Yii;

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public $auth_key='sun';
    
    public $access_token='sun';
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'username', 'password', 'email', 'create_by', 'create_at'], 'required'],
            [['username'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '唯一序号',
            'username' => '账号',
            'password' => '密码',
            'email' => '邮箱地址',
            'create_by' => '创建人',
            'create_at' => '创建日期',
        ];
    }
    /**
     * 根据参数ID获取用户数据
     * @param type $id
     * @return type
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }
    
    /**
     * 获取令牌
     * @param type $token
     * @param type $type
     * @return \static
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        //return static::findOne(['access_token' => $token]);
        return new static($this->access_token);
    }
    
    /**
     * 根据参数获取用户帐号信息
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        $user = self::find()->where(['username' => $username])->asArray()->one();
    
        if($user)
        {
            return new static($user);
        }
        return null;
    }
    
    /**
     * 获取当前用户ID
     * @return type
     */
    public function getId()
    {
        return $this->id;
    }
    
    /**
     * 获取授权密钥
     * @return type
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }
    
    /**
     * 授权密钥验证
     * @param type $authKey
     * @return type
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }
    
    /**
     * 密码验证
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        //return $this->password === $password;
        //生成密码时用 Yii::$app->getSecurity()->generatePasswordHash(明文密码)
        return Yii::$app->getSecurity()->validatePassword($password, $this->password);
    }    
}

 

posted on 2016-03-10 21:53  沈恩忍  阅读(466)  评论(0编辑  收藏  举报

导航