80 lines
1.8 KiB
PHP
80 lines
1.8 KiB
PHP
<?php
|
|
declare (strict_types = 1);
|
|
|
|
namespace app\controller;
|
|
|
|
use app\BaseController;
|
|
use app\service\UserService;
|
|
use think\facade\Session;
|
|
use think\facade\View;
|
|
|
|
/**
|
|
* 认证控制器
|
|
*/
|
|
class Auth extends BaseController
|
|
{
|
|
/**
|
|
* 显示登录页面
|
|
*/
|
|
public function login()
|
|
{
|
|
// 如果已登录,根据账号类型跳转到不同页面
|
|
if (Session::has('username')) {
|
|
$isAdmin = Session::get('is_admin', false);
|
|
if ($isAdmin) {
|
|
return redirect('/admin');
|
|
} else {
|
|
return redirect('/crawler');
|
|
}
|
|
}
|
|
return View::fetch();
|
|
}
|
|
|
|
/**
|
|
* 处理登录
|
|
*/
|
|
public function doLogin()
|
|
{
|
|
$username = $this->request->param('username', '');
|
|
$password = $this->request->param('password', '');
|
|
|
|
if (empty($username) || empty($password)) {
|
|
return json([
|
|
'code' => 0,
|
|
'msg' => '请输入用户名和密码',
|
|
]);
|
|
}
|
|
|
|
$service = new UserService();
|
|
$user = $service->verifyLogin($username, $password);
|
|
|
|
if ($user === false) {
|
|
return json([
|
|
'code' => 0,
|
|
'msg' => '用户名或密码错误',
|
|
]);
|
|
}
|
|
|
|
// 保存登录信息到Session
|
|
Session::set('username', $user['username']);
|
|
Session::set('is_admin', $user['is_admin']);
|
|
|
|
return json([
|
|
'code' => 1,
|
|
'msg' => '登录成功',
|
|
'data' => [
|
|
'is_admin' => $user['is_admin'],
|
|
],
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 退出登录
|
|
*/
|
|
public function logout()
|
|
{
|
|
Session::clear();
|
|
return redirect('/login');
|
|
}
|
|
}
|