6-16 登录优化
login.php
<?php
namespace appadmincontroller;
use Exception;
use thinkacadeView;
class Login extends AdminBase
{
public function initialize()
{
if ($this->isLogin()) {
return $this->redirect(url('index/index'));
}
}
public function index(): string
{
try {
return View::fetch();
} catch (Exception $e) {
return show(config('status.error'), '模板不存在');
}
}
public function test(): void
{
halt(session(config('admin.session_admin')));
}
public function check()
{
if (!$this->request->isPost()) {
return show(config('status.error'), '请求方式错误');
}
//参数校验 1.原生方式 2.TP6验证机制
$username = $this->request->param('username', '', 'trim');
$password = $this->request->param('password', '', 'trim');
$captcha = $this->request->param('captcha', '', 'trim');
if (empty($username) || empty($password) || empty($captcha)) {
return show(config('status.error'), '参数不能为空');
}
if (!captcha_check($captcha)) {
//验证码校验失败
//验证码存放于session中使用验证码需要开启session在app下的全局文件middleware.php中
return show(config('status.error'), '验证码不正确');
}
$adminUserObj = new appadminlogicAdminUser();
$reuslt = $adminUserObj ->login($data);
//登录提醒未定义变量: data
return $reuslt;
}
}
business层AdminUser.php 我放在logic文件里了
<?php
namespace appadminlogic;
use Exception;
class AdminUser
{
public function login($data)
{
try {
$adminUserObj = new appmodelAdminUser();
$adminUser = $adminUserObj->getAdminUserByUsername($data['username']);
//判断用户名是否存在
if (empty($adminUser) || $adminUser->status !== config('status.mysql.table_normal')) {
return show(config('status.error'), '不存在该用户');
}
$adminUser = $adminUser->toArray();
//判断密码是否和数据库中一致
if ($adminUser['password'] !== md5($data['password'] . config('my.salt'))) {
return show(config('status.error'), '密码错误');
}
//需要记录信息到mysql表中
$updateData = [
'last_login_time' => time(),
'last_login_ip' => request()->ip(),
'update_time' => time(),
];
$res = $adminUserObj->updateById($adminUser['id'], $updateData);
if (empty($res)) {
return show(config('status.error'), '登录失败');
}
} catch (Exception $e) {
return show(config('status.error'), '内部异常,登录失败');
}
//记录session
session(config('admin.session_admin'), $adminUser);
return show(config('status.success'), '登录成功');
}
}