Yii2 framework user-defined authentication model, complete the login and registration operation example

Time:2021-4-13

This paper describes the user authentication model in yii2 framework, and completes the login and registration operations. The details are as follows:

Sometimes we need to define our own user classes and operate our own user tables to complete the login and registration functions.

The user table structure is as follows. Of course, you can add or delete it according to your own needs:

CREATE TABLE `tb_user` (
 `id` int(11) unsigned NOT NULL AUTO_ Create comment 'user ID',
 `Name ` varchar (32) default '' comment 'user name',
 `PWD ` varchar (64) default '' comment 'password',
 `head_ IMG ` varchar (256) default '' comment 'image',
 `Sex ` tinyint (1) default '0' comment 'gender (0: male, 1: female)',
 `Age ` tinyint (3) default '0' comment 'age',
 `auth_ Key ` varchar (32) default '' comment 'authentication key',
 PRIMARY KEY (`id`)
)Engine = InnoDB default charset = utf8mb4 comment ='user table ';

Then we create it in models MyUser.php The code is as follows:

<?php

namespace app\models;

use YII;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

//To customize our own user operation model, we need to implement all the methods in the identityinterface interface
//Our customized model mainly implements authentication logic, while Yii / Web / user is responsible for managing user authentication status. There is a difference between the two.
class MyUser extends ActiveRecord implements IdentityInterface
{
  //Specifies the table name of the operation
  public static function tableName()
  {
    return '{{%user}}';
  }

  //Return the user instance by ID
  public static function findIdentity($id)
  {
    return static::findOne($id);
  }

  //Through the token, the user instance is returned, which is generally used for stateless restful applications
  //If your application doesn't need to be used, just leave it blank
  public static function findIdentityByAccessToken($token, $type = null)
  {
    return static::findOne(['access_token' => $token]);
  }

  //Return the user instance through the user name
  public static function findByUsername($name)
  {
    return static::findOne(['name' => $name]);
  }

  //Get user ID
  public function getId()
  {
    return $this->id;
  }

  //Get user authentication key
  public function getAuthKey()
  {
    return $this->auth_key;
  }

  //Generating authkey in cookie
  public function generateAuthKey()
  {
    $this->auth_key = Yii::$app->security->generateRandomString(32);
    $this->save(false);
  }

  //Verify user authentication key
  public function validateAuthKey($authKey)
  {
    return $this->getAuthKey() === $authKey;
  }

  //Verify whether the password is correct, of course, we can also define our own encryption and decryption methods
  public function validatePassword($password)
  {
    return Yii::$app->security->validatePassword($password, $this->pwd);
  }
}

After creating our own user model class, we need to modify it to our own in the configuration file, in the config\ web.php


'components' => [
	// ...
	'user' => [
		'identityClass' => 'app\models\MyUser',
		'enableAutoLogin' => true,
	],
];

Then we create a landing page

<?php
use yii\helpers\Url;
?>
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  < title > form submission
</head>
<body>
<form action="<?php echo Url::toRoute('index/login'); ?>" method="post">
  Name:
  Password: < input type = "password" name = "PWD" > < br > password
  < input type = "submit" value = "login" >
  <input name="_csrf" type="hidden" value="<?php echo \Yii::$app->request->csrfToken; ?>">
</form>
</body>
</html>

Then the user login form model is created under models MyUserLogin.php

<?php

namespace app\models;

use Yii;
use yii\base\Model;

class MyUserLogin extends Model
{
  //Note that the variables submitted in the form should be declared here
  public $name;
  public $pwd;

  //Set up validation
  public function rules()
  {
    return [
      [['name', 'pwd'], 'required'],
      ['pwd', 'validatePassword'],
    ];
  }

  //Verify password
  public function validatePassword($attribute, $params)
  {
    if (!$this->hasErrors()) {
      $user = $this->getUser();

      if (!$user || !$user->validatePassword($this->pwd)) {
        $this - > adderror ($attribute, 'password error');
      }
    }
  }

  //Login processing
  public function login()
  {
    if ($this->validate()) {
      $user = $this->getUser();
      //Listen to events and regenerate authkey before logging in
      YII::$app->user->on(\yii\web\User::EVENT_BEFORE_LOGIN, [$user, 'generateAuthKey']);

      return Yii::$app->user->login($user, 3600 * 24);
    }
    return false;
  }

  //Get users
  public function getUser()
  {
    return MyUser::findByUsername($this->name);
  }
}

Finally, our controller code

<?php

namespace app\controllers;

use YII;
use yii\web\Controller;
use app\models\MyUserLogin;

class IndexController extends Controller
{
  public function actionIndex()
  {
    //The ID of the current user
    var_dump(YII::$app->user->id);
    //Is the current user a tourist
    var_dump(YII::$app->user->isGuest);
  }

  public function actionLogin()
  {
    if (YII::$app->request->isPost) {

      $model = new MyUserLogin();
      $model->load(YII::$app->request->post(), '');

      if ($model->login()) {
        Echo 'login successful';
      } else {
        Echo 'login failed';
      }

    } else {
      return $this->renderPartial('login');
    }
  }
}

The demonstration is as follows:

For more information about Yii, readers who are interested in it can see the following topics: Yii framework introduction and common skills summary, PHP excellent development framework summary, smart template introduction basic course, PHP object-oriented programming introduction course, PHP string usage summary, PHP + MySQL database operation introduction course and PHP common database operation introduction course Summary of writing skills

I hope this article will be helpful to the PHP Programming Based on Yii framework.

Recommended Today

Seven solutions for distributed transactions

1、 What is distributed transaction Distributed transaction means that transaction participants, transaction supporting servers, resource servers and transaction managers are located on different nodes of different distributed systems. A large operation is completed by more than n small operations. These small operations are distributed on different services. For these operations, either all of them are […]