yunzer/app/api/controller/AdminController.php

107 lines
3.3 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 app\api\controller;
use app\api\controller\BaseController;
use app\admin\model\AdminUser;
use app\index\model\AdminUserGroup;
use think\facade\Log;
use think\facade\Cache;
use think\Response;
class AdminController extends BaseController
{
/**
* 生成用户token
*
* @param int $userId 用户ID
* @return string
*/
private function generateToken($userId)
{
// 生成一个简单的token包含用户ID和时间戳
$data = [
'user_id' => $userId,
'timestamp' => time(),
'random' => mt_rand(100000, 999999)
];
// 使用base64编码实际项目中建议使用JWT
return base64_encode(json_encode($data));
}
/**
* 用户登录接口
*
* @return \think\Response
*/
public function login()
{
if (!$this->request->isPost()) {
return json(['code' => 1, 'msg' => '请求方法错误']);
}
$data = $this->request->post();
try {
// 验证数据
$validate = validate([
'account' => 'require|email',
'password' => 'require'
], [
'account.require' => '账户不能为空',
'account.email' => '邮箱格式不正确',
'password.require' => '密码不能为空'
]);
if (!$validate->check($data)) {
return json(['code' => 1, 'msg' => $validate->getError()]);
}
// 查询用户
$user = AdminUser::where('account', $data['account'])->find();
if (!$user) {
return json(['code' => 1, 'msg' => '用户不存在']);
}
// 验证密码
if ($user->password !== md5($data['password'])) {
return json(['code' => 1, 'msg' => '密码错误']);
}
// 生成JWT token这里使用简单的token实际项目中建议使用JWT
$token = $this->generateToken($user->id);
// 将token存储到缓存中设置过期时间
Cache::set('user_token_' . $user->id, $token, 7 * 24 * 3600);
// 记录登录日志
Log::record('用户登录成功:' . $user->account, 'info');
// 返回用户信息和token
return json([
'code' => 0,
'msg' => '登录成功',
'data' => [
'token' => $token,
'user_info' => [
'id' => $user->id,
'account' => $user->account,
'name' => $user->name,
'avatar' => $user->avatar ?? '/static/images/avatar.png',
'phone' => $user->phone ?? '',
'sex' => $user->sex ?? 0,
'qq' => $user->qq ?? '',
'wechat' => $user->wechat ?? '',
'create_time' => $user->create_time
]
]
]);
} catch (\Exception $e) {
Log::record('登录失败:' . $e->getMessage(), 'error');
return json(['code' => 1, 'msg' => '登录失败:' . $e->getMessage()]);
}
}
}