jayrui612 2017-10-18 17:26:37 14425次浏览 0条评论 2 1 0

之前项目中用户信息基本都是表单提交数据 user模型验证用户名密码 写入session来操作的
一直对yii2自带的user组件好奇 也看过很多网上教程 感觉都比较懵懵懂懂的 特别是新手朋友 很难体会 特写下自己捣鼓体验
纯属本人感想

第一步:gii生成用户表的model

第二步:修改components下 user组件

'user' => [
    'identityClass' => 'backend\models\DbUserBase',
    'enableAutoLogin' => false,
    'enableSession' => true,//登录用
    'loginUrl' =>'',
    'identityCookie' => ['name' => '_identity-frontend-api', 'httpOnly' => true],
],

将identityclass 认证 指向你gii生成的model

接下来我们就要修改DbUserBase模型了 使他实现yii2的IdentityInterface 的user认证接口
源码可以在 use yii\web\IdentityInterface;去查看

本身yii已经在 common\models\User 已经给你写好示例的代码了

<?php
namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;


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

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

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

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

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

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * 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);
    }

    /**
     * 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();
    }

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

自己将里面需要的复制到DbUserBase 图省事可以把attributeLabels 后面的都复制过去

好了 yii2 user组件已经改写完成 还没用完尼 怎么调用尼

第三步:登录

view就不贴上了 就是表单的东西 action指定到你要处理的控制器下就行了

<?php
/**
 * Created by PhpStorm.
 * User: jay
 * Date: 2017/8/16
 * Time: 9:32
 */
namespace backend\controllers;
use yii;
use yii\web\Controller;
use common\models\LoginForm;
use backend\models\DbUserBase;
/**
 * Class LoginController
 * @package backend\controllers
 */
class LoginController extends Controller
{
    /**
     * 用户登录
     */
    public function actionLogin()
    {
        $model = new LoginForm();
        if(Yii::$app->request->isPost){
            $params = Yii::$app->request->post();
            //$userbase = DbUserBase::find()->where(['user_name' => $params['LoginForm']['username']])->asArray()
            //->one();
            //通过user认证里面的方法去获取用户数据
            $userbase = DbUserBase::findIdentityByUserName($params['LoginForm']['username']);
            //下面都是次要的只是密码检验和验证码操作
             if(!Yii::$app->getSecurity()->validatePassword($params['LoginForm']['password'],$userbase['password']))
                 return "<script>alert('密码错误!');window.history.back();</script>";
            if($userbase['status'] == 1)
                return "<script>alert('您的账号已被禁用!');window.history.back();</script>";
            // 验证拖动验证码
            if(!CommController::Checkyzm())
                return "<script>alert('验证码错误!'); window.history.back();</script>";
            //注意这步是重要的 是将user组件和用户进行绑定吧 可以这么理解
            Yii::$app->user->login($userbase);
            //这样你就可以直接去使用 Yii::$app->user->id了
            return $this->redirect(Yii::$app->urlManager->createUrl(['index/index']));
        }
    }
}
觉得很赞
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册