<?php
namespace app\controller\admin;
use app\BaseController;
use think\facade\Session;
use think\Request;
use \app\model\User;
class Login extends BaseController
{
protected $request;
public function index(){
return view('admin/login');
}
public function toAdminIndex(){
return view('admin/index');
}
public function logout(){
Session::delete('user');
return view('admin/login');
}
public function __construct(Request $request){
$this->request = $request;
$this->request->header('Content-Type:text/html; charset=utf-8');
}
public function login(){
$user = new User();
$username = $this->request->param('username');
$password = $this->request->param('password');
$data = [
'username' => $username,
'password' => $password,
'dto' => ['username'=>$username,'password'=>$password], // dto 为一个数组类型
];
$flag = $user->login($data); // $flag != 1 则返回错误消息
if($flag != 1){
//show 方法在common.php 中,封装统一返回前端数据格式{"code":-1,"msg":$flag,"data":null}
return show(-1,$flag,null);
}
//能到这一步说明验证通过,将用户信息存入 Session 中存储起来
Session::set('user',$user->getUserByUserName($username));
// url: '/admin.login/toAdminIndex'
return show(1,'登陆成功!','/admin.login/toAdminIndex');
}
}
7.UserModel.php
<?php
namespace app\model;
use think\exception\ValidateException;
use think\facade\Db;
use think\Model;
class User extends Model
{
protected $table = 'user';
public function getUserByUserName($username){
return Db::table('user')->where('username','=',$username)->find();
}
public function login($data){
try{
//Login 是登陆验证器
validate(\app\validate\Login::class)->check($data);
} catch (ValidateException $e) {
// 验证不通过则返回错误消息
// 错误消息比如: "用户名不能为空!","用户名或密码错误!"等
return $e->getError();
}
//验证通过返回1,也可以是其他数字,任意,只要和 controller层对接好就行
return 1;
}
}