<?php
namespace app\controllers;
use yii;
use yii\helpers\Json;
use yii\helpers\HtmlPurifier;
use yii\captcha\CaptchaAction;
use app\models\Auth;
class LoginController extends yii\web\Controller
{
public $enableCsrfValidation = false;
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'maxLength'=>4,
'minLength'=>4,
'padding'=>5,
'height'=>39,
'width'=>100,
'offset'=>3,
],
];
}
public function actionLogin()
{
$this->layout = false;
if (Yii::$app->request->isPost){
// 一些表单验证的逻辑代码,此处省略
$lifetime = 3600; // 1小时
ini_set('session.gc_maxlifetime', $lifetime); // 秒
ini_set("session.cookie_lifetime",$lifetime); // 秒
Yii::$app->session['expiretime'] = time() + $lifetime;
Yii::$app->session['username'] = $username;
return Json::encode(['status'=>2,'msg'=>'登陆成功','username' =>$username]);
}else{
if (isset(Yii::$app->session['username']) && isset(Yii::$app->session['expiretime'])) {
return $this->redirect(['index/index']);
Yii::$app->end();
}
}
return $this->render("login");
}
/**
* [actionLogout 登出]
* @return [type] [description]
*/
public function actionLogout()
{
Yii::$app->session->removeAll();
return $this->redirect(['login/login']);
Yii::$app->end();
}
}
- 父级控制器(除登陆控制器之外,都需要继续这个控制器)
class BaseController extends Controller
{
public function init()
{
if($this->checkLogin() === false) {
return $this->redirect(['/login/login']);
Yii::$app->end();
}
}
/**
* [checkLogin description]
* @return [type] [description]
*/
public function checkLogin()
{
$expiretime = isset($_SESSION['expiretime']) ? $_SESSION['expiretime'] : null;
$username = isset($_SESSION['username']) ? $_SESSION['username'] : null;
$lifetime = 3600; // 1小时
if( $expiretime !== null && $username !== null) {
if($expiretime < time() || !isset($username)) {
unset($_SESSION['expiretime']);
unset($_SESSION['username']);
return false;
} else {
$_SESSION['expiretime'] = time() + $lifetime; // 刷新时间戳
$_SESSION['username'] = $username;
return true;
}
}
return false;
}
}
- 处理session过期时ajax请求无反应,统一处理http状态。可以加载layouts的公共页面中。
<script type="text/javascript">
$(function(){
$.ajaxSetup({
type:"POST",
cache:false,
dataType:'JSON',
error:function(jqXHR,textStatus,errorThrown){
switch(jqXHR.status){
case(403):
$(location).attr('href', '/login/login');
break;
default:
//
}
},
});
});
</script>
网友评论