food_server/FlyCube/MpApi/Controller/LoginController.class.php
air 15131ccc2b 【类 型】:fix
【原  因】:1.login登录的bom头指定为json  2.debug改为不输出
【过  程】:
【影  响】:
2025-05-09 14:34:06 +08:00

93 lines
2.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace MpApi\Controller;
use Think\Controller;
use Firebase\JWT\JWT;
class LoginController extends Controller
{
private $shop_id;
/**
* @Description: 登陆接口
* @Return:
*/
public function login()
{
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: " . C('LimitApi')); //请求域名限制
header('Access-Control-Allow-Headers:Token'); //token请求头
if (!$_POST['username']) {
echo json_encode(array('status' => 0, 'msg' => '用户名不能为空'), JSON_UNESCAPED_UNICODE);
exit;
}
if (!$_POST['password']) {
echo json_encode(array('status' => 0, 'msg' => '密码不能为空'), JSON_UNESCAPED_UNICODE);
exit;
}
$adminuserDb = D('adminuser');
$where['name'] = $_POST['username'];
$where['del'] = '0';
$adminInfo = $adminuserDb->where($where)->field('name,uname,pwd,qx,shop_id,photo,lasttime')->find();
if ($adminInfo) {
if (MD5(MD5($_POST['password'])) == $adminInfo['pwd']) {
//登陆成功
$this->shop_id = $adminInfo['shop_id'];
$data['lasttime'] = time();
$adminuserDb->where($where)->save($data); //最后登录时间写入数据库
//从program表拿用户头像
$adminInfo['photo'] = json_decode($adminInfo['photo'])[0]; //反序列化 取到头像名称
switch ($adminInfo['qx']) {
case 4:
$adminInfo['power'] = 'admin';
break;
case 5:
$adminInfo['power'] = 'editor';
break;
}
//删除多余信息
unset($adminInfo['pwd']);
//创建token
$token = $this->makeToken(array('shop_id' => $this->shop_id));
//登陆成功 返回token
echo json_encode(array('status' => 1, 'msg' => '登陆成功', 'adminInfo' => $adminInfo, 'token' => $token), JSON_UNESCAPED_UNICODE);
} else {
//密码错误
echo json_encode(array('status' => 0, 'msg' => '登陆失败'), JSON_UNESCAPED_UNICODE);
exit;
}
} else {
//账号不存在或已注销
echo json_encode(array('status' => 0, 'msg' => "登陆失败"), JSON_UNESCAPED_UNICODE);
exit;
}
}
/**
* @description: 构建token
* @param {array} data 要存储在 JWT 中的数据,键值对形式 ps:这里可以传exp 来覆盖默认的过期时间
* @return {*} token
*/
private function makeToken($data = [])
{
$jwtKey = C('jwtKey'); // jwt密钥
$currtime = time();
// 默认的数据
$defaultData = [
'iat' => $currtime, // 签发时间(时间戳)
'iss' => 'jwt_admin', // 签发者
'nbf' => $currtime, // 在此时间之前不可用 (这里是2秒以内)
'exp' => strtotime('tomorrow'), //过期时间 到第二天凌晨
'jti' => md5(uniqid('JWT') . $currtime), // JWT ID令牌的唯一标识符
];
// 合并默认数据和传递的数据
$tokenData = array_merge($defaultData, $data);
// 使用密钥和 HS256 算法对数据进行编码生成 JWT
return JWT::encode($tokenData, $jwtKey, 'HS256');
}
}