You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.2 KiB

7 years ago
<?php
7 years ago
namespace frontend\controllers\auth;
use common\auth\Identity;
use core\services\auth\AuthService;
3 years ago
use DomainException;
7 years ago
use Yii;
use core\forms\auth\LoginForm;
use yii\filters\AccessControl;
use yii\web\Controller;
3 years ago
use yii\web\Response;
7 years ago
class AuthController extends Controller
7 years ago
{
public $layout = 'auth';
3 years ago
private AuthService $service;
7 years ago
public function __construct($id, $module, AuthService $service, $config = [])
{
parent::__construct($id, $module, $config);
3 years ago
$this->service = $service;
7 years ago
}
public function behaviors(): array
{
return [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'actions' => ['login'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
[ // all the action are accessible to admin
'allow' => true,
'roles' => ['admin'],
],
],
],
];
}
7 years ago
/**
3 years ago
* @return string|Response
7 years ago
*/
3 years ago
public function actionLogin(): string|Response
7 years ago
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$form = new LoginForm();
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
try {
3 years ago
$user = $this->service->auth($form);
7 years ago
Yii::$app->user->login(new Identity($user), $form->rememberMe ? Yii::$app->params['user.rememberMeDuration'] : 0);
7 years ago
return $this->goBack();
3 years ago
} catch (DomainException $e) {
7 years ago
Yii::$app->errorHandler->logException($e);
Yii::$app->session->setFlash('error', $e->getMessage());
}
}
return $this->render('login', [
'model' => $form,
]);
}
/**
3 years ago
* @return Response
7 years ago
*/
3 years ago
public function actionLogout(): Response
7 years ago
{
Yii::$app->user->logout();
return $this->goHome();
}
}