Skip to main content

Login via DB

Maak een  database tabel

CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `username` varchar(128) NOT NULL,
  `password` varchar(128) NOT NULL,
  `authKey` varchar(200) DEFAULT NULL,
  `role` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`);
  
ALTER TABLE `tbl_user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;

Create CRUD voor tbl_user

image-1617048375766.png     

image-1617048411848.png

app\models\TblUser
app\models\TblUserSearch
app\controllers\TblUserController

Pas actionCreate voor TblUserController aan

public function actionCreate()
{
    $model = new tblUser();

    if ($model->load(Yii::$app->request->post()) ) {
        $model->password=sha1($model->password);
        $model->authKey=md5(openssl_random_pseudo_bytes(40));
        if ($model->save() ) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
    }

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

Dit zorgt ervoor dat er

  • een hash wordt gegenereerd als er een nieuwe user wordt aangemaakt
  • het password wordt gehashed

Pas model User.php aan

<?php

namespace app\models;

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public static function tableName()
    {
        return 'tbl_user';
    }

    public function rules()
    {
        return [
            [['username', 'password', 'email'], 'required'],
            [['username', 'password', 'email'], 'string', 'max' => 128],
            [['role'], 'string', 'max' => 20],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'role' => 'Role',
            'email' => 'Email',
        ];
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }


    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        return $this->authKey;
    }


    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

 
    public function validatePassword($password)
    {
        return $this->password === sha1($password);
    }
}

Users aanmaken met CRUD tbl_user

Let op:

Get role

Yii::$app->user->identity->role

ToDo

User can change  his password

-> new form and access based on Yii:$app->user->identity->username