V
V
Vadim2017-05-29 11:58:16
Yii
Vadim, 2017-05-29 11:58:16

Yii2 backend access for admin only?

slightly passed actionLogin() to the backend (Yii2 advanced template)
essence: organize access only for admins
clarification: after the user has logged in, we check his status and access level for the admin panel. if everything is good, we skip it, if not, then logout
the question: is this enough for security? or are there other options?
the action itself

public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            $user_id = Yii::$app->user->identity->getId();
            if (User::findIdentityAdmin($user_id)) {
                return $this->goBack();
            } else {
                Yii::$app->user->logout();
                throw new ForbiddenHttpException('Доступ запрещен.');
            }
        } else {
            return $this->render('index', [
                'model' => $model,
            ]);
        }
    }

user model
const STATUS_ACTIVE = 10;
const ROLE_ADMIN = 10;

    public static function findIdentityAdmin($id)
    {
        return static::findOne(['id' => $id, 'role' => self::ROLE_ADMIN, 'status' => self::STATUS_ACTIVE]);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-05-29
@qonand

Question: Is this enough for security? or are there other options?

It is not enough, for example, if cookie authentication works, your logic simply will not work. It is better to use the appropriate filters to restrict access

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question