Yii2.0登录功能代码实现

yii归档文件中的basic应用是带登录功能的,见user相关。同时basic中已经带了基本登录Login模板。

一、建立controller/action

这里用到SiteController的actionLogin方法:

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\Userinfo;
use app\models\ContactForm;
use app\models\EntryForm;

class SiteController extends Controller
{

用的basic中默认siteController

public function actionLogin()
{
    if (!\Yii::$app->user->isGuest) {
        return $this->goHome();
    }

    $model = new LoginForm();

    if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->goBack();
    }

    return $this->render('login', [
        'model' => $model,
    ]);
}

Action也是默认的。

二、Model和LoginForm

public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
    }
    return false;
}

public function getUser()
{
    if ($this->_user === false) {
        $this->_user = Userinfo::validateUsername($this->username, $this->password);
    }

    return $this->_user;
}

LoginForm中的默认login方法,在yii/app/web下需要返回一个user信息记录在session和cookie中,记录的信息是$this->getUser()中返回的static类,如下。

public static function validateUsername($username, $password)
{
    try {
        $records = Yii::$app->db->createCommand("select * from userinfo where username = '".$username."'")->queryAll();
    } catch (Exception $e) {
        var_dump($e);
    }

    if ($records && $records[0]["password"] == $password) {
        $currentUser = [
            'usernameL' => $records[0]["username"],
            'passwordL' => $records[0]["password"],
            'emailAddressL' => $records[0]["emailAddress"],
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ];
        return new static($currentUser);
    }

    return null;
}

static($currentUser)是创建了当前的一个类,属性要对应上:

class Userinfo extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public $usernameL;
    public $passwordL;
    public $emailAddressL;
    public $authKey;
    public $accessToken;

三、yii登录基本原理

1、需要配置参数,加入user扩展
'components' => [
        'user' => [
            'identityClass' => 'app\models\Userinfo',
            'enableAutoLogin' => true,
        ],
        ...
]

identityClass就是用于处理user的model,可以使用Yii2高级模板自带的user,也可以自己写,需要实现IdentityInterface接口(这里写的是userInfo,利用gii的crud生成)

2、关于user

配置好user后,可以在全局使用Yii::$app->user访问;
user的重要属性,isGuest:判断用户是否登录;id,保存登录用户的唯一识别标识,由我们自己设置,具体如何设置,且看后文分解;
user的重要方法,login():将用户信息保存在session、cookie中;logout():将用户信息从session、cookie中销毁;
Note that User only maintains the user authentication status. It does NOT handle how to authenticate a user. The logic of how to authenticate a user should be done in the class implementing yii\web\IdentityInterface.
//user组件的工作只是维护用户的认证状态(即简单的操作session和cookie)。它并不负责认证用户。认证过程的逻辑实现统统由一个实现了IdentityInterface接口的类实现;

3、IdentityInterface

这个接口定义了5个函数:
findIdentity();
getId();
findIdentityByAccessToken();
getAuthKey();
validateAuthKey;
这5个函数当中,最重要的可能就是getId()了。这个函数由你实现,由传递给user的对象在login的时候调用,用于设置user的id属性值!所以,在实现这个函数的时候,你返回的是什么,那么user组件记住的user id就是什么。其他几个函数的具体实现,请参照文档;

4、登录

假设我们定义了一个名为User的AR模型类(注意应用组件user的区别),User对应了一张我们保存有用户登录信息的数据表;如果我们要使用User来完成用户认证,User就必须实现上文提及的IdentityInterface;
1、服务器接受到用户提交的用户名和密码;
2、生成User实例$model;
3、赋值:$model->load(Yii::$app->request->post());
4、检查用户输入以及验证用户名和密码:$model->validate();
5、登录Yii::$app->user->login($model,$duration);

5、自动登录

要实现自动登录,需要设置参数$enableAutoLogin
$duration必须大于零;
使用$isGuest判断用户是否已经登录;

四、遇到的问题

class Userinfo extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public $usernameL;
    public $passwordL;
    public $emailAddressL;
    public $authKey;
    public $accessToken;

model中有数据库属性,这里是记录登录属性,二者名称需要不一样,否则会影响用户新增。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mitsuhide1992

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值