TimoPHP做一个简单的后台登录、登出功能
登录控制器
登录控制器直接继承Timo\Core\Controller
其它需要登录后才能操作的控制器,继承自定义的公共控制器Admin,如Index控制器
通过AdminModel->checkAdmin($username, $password, $verify) 来验证登录
登录成功之后跳转到index/index
namespace app\admin\controller;
use app\admin\model\AdminModel;
use Timo\Captcha;
use Timo\Core\Controller;
use Timo\Core\Request;
use Timo\Core\Session;
class Login extends Controller
{
/**
* @var AdminModel
*/
protected $AdminModel;
public function __construct()
{
parent::__construct();
$this->AdminModel = new AdminModel();
}
/**
* 登录
*/
public function index()
{
if (Request::isPost()) {
$username = Request::post('username', '');
$password = Request::post('password', '');
$verify = Request::post('verify', '');
$check_ret = $this->AdminModel->checkAdmin($username, $password, $verify);
if ($check_ret['code'] == 1) {
Session::delete('v_login');
$this->redirect('index/index');
}
$this->assign('msg', $check_ret['msg']);
}
$this->view->set('layer_on', false);
$this->display();
}
/**
* 退出
*/
public function logout()
{
Session::destroy();
return $this->success('退出成功', 'login/index');
}
/**
* 生成验证码
*/
function verify()
{
$Captcha = new Captcha();
$code = $Captcha->getCode();
Session::set('v_login', $code);
$Captcha->getImage();
}
}
验证是否是管理员,并登录
验证成功之后,将管理员信息存入session
Session::set('u.uid', $admin_info['id']);
Session::set('u.name', $admin_info['username']);
namespace app\admin\model;
use Timo\Core\Model;
use Timo\Core\Session;
use Timo\Core\App;
class AdminModel extends Model
{
function __construct($dbType = '', $dbName = '')
{
parent::__construct($dbType, $dbName);
$this->setTablePrefix('back_');
}
/**
* 检测是否是管理员
*
* @param $username
* @param $password
* @param string $verify_code 验证码
* @param bool $is_verify 是否验证验证码
* @return array|string
*/
public function checkAdmin($username, $password, $verify_code = '', $is_verify = true)
{
$admin_info = $this->getRow(array('username' => $username), 'id, username, password');
if (!$admin_info) {
return App::result(4001, '没有该用户');
}
if ($is_verify && $verify_code != Session::get('v_login')) {
return App::result(4002, '验证码错误');
}
$password = sha1(md5($password));
if ($admin_info['password'] == $password) {
Session::set('u.uid', $admin_info['id']);
Session::set('u.name', $admin_info['username']);
return App::result(1, '登录成功');
}
return App::result(4003, '密码错误');
}
}
后台公共控制器Admin
检测是否登录
Admin控制器在初始化的时候会检测是否已登录,没登录,将跳转到登录页面login/index
namespace app\admin\controller;
use Timo\Core\Controller;
use Timo\Core\Session;
class Admin extends Controller
{
/**
* 管理员信息['uid' => 1, 'name' => 'admin']
*
* @var mixed
*/
protected $u;
public function __construct()
{
parent::__construct();
$this->u = Session::get('u');
if (!empty($this->u)) {
$this->assign('u', $this->u);
} else {
$this->redirect('login/index');
}
}
}
其它需要登录后才能操作的控制器
这些控制器需继承Admin控制器
这里只是以Index控制器来说明
<?php
namespace app\admin\controller;
class Index extends Admin
{
public function index()
{
$this->display();
}
}