最新消息: 新版网站上线了!!!

Yii2 Login and SignUp

Yii2 的模板分两种, advanced 和 basic , 后文分别将实施了这两种模板的项目叫做:
  • yii2app
  • yii2adv

这两种模板自带的 Login 机制是不一样的,区别主要在 common\models\User

  • yii2app: User extends \yii\base\Object
    private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'admin',
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ],
        '101' => [
            'id' => '101',
            'username' => 'demo',
            'password' => 'demo',
            'authKey' => 'test101key',
            'accessToken' => '101-token',
        ],
    ];
  • yii2adv: User extends ActiveRecord
    public static function tableName()
    {
        return '{{%user}}';
    }

另外就是 yii2adv 还实现了下面的操作

  • SignUp
  • ResetPassword

原创文章: http://www.cnblogs.com/ganiks/

关于 AuthKey

    /**
     * @inheritdoc
	 * yii\web\user::loginByCookie()
	 * Logs in a user by cookie.
	 * This method attempts to log in a user using the ID and authKey information provided by the given cookie.
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

在 yii2app 上实现 注册

为了不覆盖 原始的 User, 这里 复制一份,命名 User2

使用 User2 模型登录, 还需要配置3个地方

  1. User2 中的 类名 class User2
  2. LoginForm 模型中的 getUser() 方法中用到了 User::findByUsername 需要改为 User2::findByUsername
  3. config/web.php 中
    'components' => [
        'user' => [
            'identityClass' => 'app\models\User2',
            'enableAutoLogin' => true,
            'enableSession' => true,
        ]
    ]

先实现在 yii2app 上链接 user 表, 将 yii2acv 的 common\models\User.php 拷贝过来覆盖即可。

user表结构如下:

mysql> select * from user\G;
*************************** 1. row ***************************
                  id: 1
            username: ganiks
            auth_key: iuMVI8xFbvrcdpZrDQDVhdmcLmIt5DgI
       password_hash: $2y$13$06XKlhs9ZObd5cOXdpcqAu3swIdPPDlRyJQp8z19CIl6xeQvgD3wu
password_reset_token: NULL
               email: ganiks@qq.com
                role: 10
              status: 10
          created_at: 1406096791
          updated_at: 1406096791
        access_token: ganiks-token
1 row in set (0.00 sec)

注意,yii2app and yii2adv 两者在框架上代码也有区别,比如 Yii::$app->security 中, yii2adv就要复杂些,有这个generateRandomString 方法, 记得加到yii2app 中,用于生成 authKey 和 access_token


    /**
     * Generates a random string of specified length.
     * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
     *
     * @param integer $length the length of the key in characters
     * @throws Exception Exception on failure.
     * @return string the generated random key
     */
    public function generateRandomString($length = 32)
    {
        $bytes = $this->generateRandomKey($length);
        // '=' character(s) returned by base64_encode() are always discarded because
        // they are guaranteed to be after position $length in the base64_encode() output.
        return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
    }

yii2app实现注册

相关代码:

  • app\models\SignupForm.php(new file)
  • app\models\User2.php
  • app\views\site\signup.php(new file)
  • app\controllers\SiteControllers.php
  • vendor\yiisoft\yii2\base\Security.php

app\models\SignupForm.php(new file)

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use app\models\User2;

/**
 * SignupForm is the model behind the contact form.
 */
class SignupForm extends Model
{
	public $username;
	public $email;
	public $password;

	public function rules()
	{
		return [
			['username', 'filter', 'filter' => 'trim'],
			['username', 'required'],
			['username', 'unique', 'targetClass' => '\app\models\User2', 'message' => '用户名已经被占用'],
			['username', 'string', 'min' => 2, 'max' => 225],
			['email', 'filter', 'filter' => 'trim'],
			['email', 'required'],
			['email', 'email'],
			['email', 'unique', 'targetClass' => '\app\models\User2', 'message' => 'Email 已经被占用'],
			['password', 'required'],
			['password', 'string', 'min' => 6],
		];
	}

	public function signup()
	{
		if($this->validate()) {
			$user = new User2();
			$user->username = $this->username;
			$user->email = $this->email;
			$user->setPassword($this->password);
			$user->generateAuthKey();
			$user->generateAccessToken();
			$user->save();
			return $user;
		}
	}
}

app\controllers\SiteControllers.php

	public function actionSignup()
	{
		$model = new SignupForm();
		if($model->load(Yii::$app->request->post())) {
			if ($user = $model->signup()) {
				if(Yii::$app->getUser()->login($user)) {
					return $this->goHome();
				}
			}
		}

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

转载请注明:谷谷点程序 » Yii2 Login and SignUp