入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Yii2.0登录功能代码实现

创建时间:2015-10-05 投稿人: 浏览次数:4390

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

一、建立controller/action

这里用到SiteController的actionLogin方法:

namespace appcontrollers;

use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use yiifiltersVerbFilter;
use appmodelsLoginForm;
use appmodelsUserinfo;
use appmodelsContactForm;
use appmodelsEntryForm;

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 yiidbActiveRecord implements yiiwebIdentityInterface
{
    public $usernameL;
    public $passwordL;
    public $emailAddressL;
    public $authKey;
    public $accessToken;

三、yii登录基本原理

1、需要配置参数,加入user扩展

"components" => [
        "user" => [
            "identityClass" => "appmodelsUserinfo",
            "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 yiiwebIdentityInterface.
//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 yiidbActiveRecord implements yiiwebIdentityInterface
{
    public $usernameL;
    public $passwordL;
    public $emailAddressL;
    public $authKey;
    public $accessToken;

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

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。