1. Creating Database and Model
Create a User database table with Id, username, password,email and your own requirements . Now go to the Model generator and create a user Model using Gii tool. Model is a PHP class that maps data from a database into PHP objects. Model allows you to fetch, update, select and delete rows from database. In this model you will have to implement the IdentityInterface class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface.IdentityInterface defines several methods and add two additional functions validatePassword() for valid password and findByUsername() for find current user name.
public static function findByUsername($username) { return self::findOne(['username' => $username]); } public function validatePassword($password) { return $this->password === $password; }
LoginForm class which is saved under app\models\LoginForm. In Login form you will have to define User model so it will return back the userclass
LoginForm extends Model { public $username; public $password; public $email; public $rememberMe = true; }
This is the class where we will connect application with User database table, and make it work with database.
public function getUser() { if ($this->_user === false) { $this->_user = User::findByUsername($this->username); } return $this->_user; }
findByUsername () search for a user in a database using username.
- If user with provided username doesn’t exist, then set ERROR_USERNAME_INVALID .
- If user exists, then check it password. If password doesn’t exist, then set ERROR_PASSWORD_INVALID.
- If user and user’s password is exists, then save user’s id, name, password and user’s type to the session.
user’s Id should always stored in session never in a cookie.
2. Creating Action
Create a login action in SiteController. Defined new LoginForm object and check if user submitted a login form, then get the values (username, password) and try to validate them.
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, ]); }
User is the class for the user application component that manages the user authentication status. You may use $isGuest to determine whether the current user is a guest or not. If the user is a guest, the $identity property would return null. Otherwise, it would be an instance of yii\web\IdentityInterface.
You may call various methods to change the user authentication status:
login(): sets the specified identity and remembers the authentication status in session and cookie;
logout(): marks the user as a guest and clears the relevant information from session and cookie;
setIdentity(): changes the user identity without touching session or cookie.