码迷,mamicode.com
首页 > 其他好文 > 详细

Yii2 登录Model

时间:2016-03-10 23:14:06      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

<?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);
    }    
}

 

Yii2 登录Model

标签:

原文地址:http://www.cnblogs.com/ser0632/p/5263643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!