yunzer/app/api/controller/AdminController.php

320 lines
9.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 app\api\controller;
use app\api\controller\BaseController;
use app\api\model\AdminUser;
use app\api\model\AdminSysMenu;
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));
}
/**
* 从token中获取管理员ID
*
* @param string $token
* @return int|null
*/
private function getUserIdFromToken($token)
{
try {
$data = json_decode(base64_decode($token), true);
if ($data && isset($data['user_id'])) {
return $data['user_id'];
}
} catch (\Exception $e) {
return null;
}
return null;
}
/**
* 管理员登录接口
*
* @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' => '密码错误']);
}
// 生成token
$token = $this->generateToken($user->uid);
// 将token存储到缓存中设置过期时间
Cache::set('admin_token_' . $user->uid, $token, 7 * 24 * 3600);
// 记录登录日志
Log::record('管理员登录成功:' . $user->account, 'info');
// 返回管理员信息和token
return json([
'code' => 0,
'msg' => '登录成功',
'data' => [
'token' => $token,
'user_info' => [
'id' => $user->uid,
'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()]);
}
}
/**
* 退出登录接口
*
* @return \think\Response
*/
public function logout()
{
try {
$token = $this->request->header('Authorization');
if ($token) {
// 去掉Bearer前缀
if (strpos($token, 'Bearer ') === 0) {
$token = substr($token, 7);
}
// 从token中获取管理员ID
$userId = $this->getUserIdFromToken($token);
if ($userId) {
// 清除token缓存
Cache::delete('admin_token_' . $userId);
}
}
Log::record('管理员退出登录', 'info');
// 增加前端刷新指示
return json([
'code' => 0,
'msg' => '退出成功',
'refresh' => true // 前端可根据此字段判断是否需要刷新
]);
} catch (\Exception $e) {
Log::record('退出登录失败:' . $e->getMessage(), 'error');
return json(['code' => 1, 'msg' => '退出失败:' . $e->getMessage()]);
}
}
/**
* 获取管理员信息接口
*
* @return \think\Response
*/
public function info()
{
try {
$token = $this->request->header('Authorization');
if (!$token) {
return json(['code' => 1, 'msg' => '请先登录']);
}
// 去掉Bearer前缀
if (strpos($token, 'Bearer ') === 0) {
$token = substr($token, 7);
}
$userId = $this->getUserIdFromToken($token);
if (!$userId) {
return json(['code' => 1, 'msg' => 'token无效']);
}
// 验证token是否在缓存中
$cachedToken = Cache::get('admin_token_' . $userId);
if (!$cachedToken || $cachedToken !== $token) {
return json(['code' => 1, 'msg' => 'token已过期']);
}
// 获取管理员信息
$user = AdminUser::where('uid', $userId)->find();
if (!$user) {
return json(['code' => 1, 'msg' => '管理员不存在']);
}
return json([
'code' => 0,
'msg' => '获取成功',
'data' => [
'id' => $user->uid,
'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()]);
}
}
/**
* 修改密码接口
*
* @return \think\Response
*/
public function changePassword()
{
if (!$this->request->isPost()) {
return json(['code' => 1, 'msg' => '请求方法错误']);
}
try {
$token = $this->request->header('Authorization');
if (!$token) {
return json(['code' => 1, 'msg' => '请先登录']);
}
// 去掉Bearer前缀
if (strpos($token, 'Bearer ') === 0) {
$token = substr($token, 7);
}
$userId = $this->getUserIdFromToken($token);
if (!$userId) {
return json(['code' => 1, 'msg' => 'token无效']);
}
// 验证token是否在缓存中
$cachedToken = Cache::get('admin_token_' . $userId);
if (!$cachedToken || $cachedToken !== $token) {
return json(['code' => 1, 'msg' => 'token已过期']);
}
$data = $this->request->post();
// 验证数据
$validate = validate([
'oldPassword' => 'require',
'newPassword' => 'require|min:6'
], [
'oldPassword.require' => '原密码不能为空',
'newPassword.require' => '新密码不能为空',
'newPassword.min' => '新密码长度不能少于6位'
]);
if (!$validate->check($data)) {
return json(['code' => 1, 'msg' => $validate->getError()]);
}
// 获取管理员信息
$user = AdminUser::where('uid', $userId)->find();
if (!$user) {
return json(['code' => 1, 'msg' => '管理员不存在']);
}
// 验证原密码
if ($user->password !== md5($data['oldPassword'])) {
return json(['code' => 1, 'msg' => '原密码错误']);
}
// 更新密码
$user->password = md5($data['newPassword']);
$user->save();
Log::record('管理员修改密码成功:' . $user->account, 'info');
return json(['code' => 0, 'msg' => '密码修改成功']);
} catch (\Exception $e) {
Log::record('修改密码失败:' . $e->getMessage(), 'error');
return json(['code' => 1, 'msg' => '修改密码失败:' . $e->getMessage()]);
}
}
/**
* 获取管理员菜单接口
*
* @return \think\Response
*/
public function menus()
{
try {
// 取消token验证直接获取菜单数据
$menus = AdminSysMenu::getMenuTree();
return json([
'code' => 0,
'msg' => '获取成功',
'data' => $menus
]);
} catch (\Exception $e) {
Log::record('获取菜单失败:' . $e->getMessage(), 'error');
return json(['code' => 1, 'msg' => '获取菜单失败:' . $e->getMessage()]);
}
}
}