Skip to main content

8, Login / rollen

In onze tweede web app, de student database gaan we een login maken. Als je aanlogt als beheerder dan mag je de cijfers invoeren, veranderen of deleten.

models/Users.php
private static $users = [
  '100' => [
      'id' => '100',
      'username' => 'admin',
      'password' => 'admin',
       'authKey' => 'test100key',
       'accessToken' => '100-token',
       'role'=> 'admin',
  ],
   '101' => [
      'id' => '101',
      'username' => 'user',
      'password' => 'demo',
      'authKey' => 'test101key',
      'accessToken' => '101-token',
      'role'=> 'user',
  ],
];
In controller
public function behaviors()
{
  return [
    'access' => [
    'class' => AccessControl::className(),

    'rules' => [
          [ 'actions' => ['index','view'],
            'allow' => true,
            'roles' => ['@'] // any authenticated user, use ? for guests
          ],

          [ 'actions' => ['create','update','delete','overzicht'],
            'allow' => true,
            'roles' => ['@'],
            'matchCallback' => function ($rule, $action)
            {
              return (Yii::$app->user->identity->role == 'admin');
            }
          ],

       ],

     ],
  ];
}
via Init method in Controller (replaces the __construct)
// if user object does nit exists or it exists but is anything but admin, go to login screen
public function init() {
    if (! isset(Yii::$app->user->identity->role) || Yii::$app->user->identity->role != 'admin') {
        $this->redirect(['/site/login']);
    }
 }