I use the component yii/web/User and define behaviors in controller to access controller.
When I access an action that only accessed by authenticated user, but I get the LoginForm.php rules’s messages.
You know, while access an authenticated controller-action, if I am a guest. It should show a message “Please Login first”, but now I got “login_name is required.” It is a little weired for the user.
So is there a way to sovle this problem in yii2 framework.
I try use Yii::$app->request->url
, but I got the value ‘/site/login’.
Here is my code.
LoginForm.php
<?php
namespace common\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $login_name;
public $password;
public $rememberMe = true;
private $_user;
/**
* {@inheritdoc}
*/
public function rules()
{
return [
// username and password are both required
[['login_name', 'password'], 'required', 'message' => '请先登录,再进行操作'],
// rememberMe must be a boolean value
//['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, '用户名或密码不正确');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->login_name);
}
return $this->_user;
}
}
SiteController.php
<?php
namespace backend\controllers;
use Yii;
use yii\rest\Controller;
use common\controllers\RestController;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use common\models\User;
/**
* Site controller
*/
class SiteController extends RestController
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return array_merge( parent::behaviors(), [
'access' => [
'class' => AccessControl::className(),
'rules' => [
['actions' => ['login', 'error'], 'allow' => true],
['actions' => ['logout', 'index'], 'allow' => true, 'roles' => ['@']],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['get'],
],
]
]
);
}
/**
* {@inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
echo '后台首页';
//return $this->render('index');
}
/**
* Login action.
*
* @return string
*/
public function actionLogin()
{
//var_dump(Yii::$app->request->post());
/*
if (!Yii::$app->user->isGuest) {
//return $this->goHome();
}
*/
$post = Yii::$app->request->post();
$model = new LoginForm();
$model->login_name = $post['login_name'];
$model->password = $post['password'];
if ($model->login()) {
$user = Yii::$app->user->getIdentity();
$msg = "登录成功";
$response = ['code' => 0, 'token' => $user->token, 'msg' => $msg];
} else {
$model->password = '';
$errors = $model->getFirstErrors();
$response = ['code' => 1, 'msg' => array_shift($errors)];
}
return $this->serializeData($response);
}
/**
* Logout action.
*
* @return string
*/
public function actionLogout()
{
Yii::$app->user->logout();
// 退出之后,需要更新用户 token
$response = ['code' => 0, 'msg' => '成功退出'];
return $this->serializeData($response);
}
}