121 lines
3.5 KiB
PHP
Raw Normal View History

<?php
namespace app\api\controller\backend;
use app\common\controller\Api;
use app\api\model\Admin as AdminModel;
use think\Db;
/**
* 登录接口
*/
class Login extends Api
{
protected $noNeedLogin = ['*'];
protected $noNeedRight = ['*'];
/**
* 首页
*
*/
public function login()
{
$username = $this->request->param('username');
$password = $this->request->param('password');
// 检查用户名和密码是否为空
if (!$username || !$password) {
$this->error('格式错误1');
}
// 查询用户信息
$where = [];
$where['username'] = $username;
$where['password'] = md5($password);
// var_dump($where);
$user = Db::name('user')->field('id,nickname,auth_group_id,group_id')->where($where)->find();
// 验证用户是否存在
if ($user) {
// 生成新的token
$timestamp = time();
$newToken = md5($password . md5($timestamp));
// 更新数据库中的token
Db::name('user')->where('id', $user['id'])->update(['token' => $newToken]);
$level = Db::name('auth_group')->where('id', $user['auth_group_id'])->value('level');
$user['level'] = $level;
// 返回成功信息和用户数据包括新token
$this->success('登录成功', ['user' => $user, 'token' => $newToken]);
} else {
// 用户不存在或密码错误
$this->error('账户密码错误');
}
}
public function getAuth()
{
$token = $this->request->header('Token');
if (!$token) {
$this->error('参数错误');
}
$user = Db::name('user')->field('auth_group_id')->where('token',$token)->find();
if (!$user) {
2025-04-03 15:25:40 +08:00
$this->error('请求失败');
}
$auth = Db::name('auth_group')->field('id,name,rules')->where('id',$user['auth_group_id'])->find();
if(!$auth){
$this->success('该用户无权限');
}
$reles = $auth['rules'];
if($reles == '*'){
$date = Db::name('auth_rule')->field('id,pid,title,url,icon')->select();
$tree = $this->buildTree($date);
$this->success('请求成功',$tree);
}
$ids = explode(',',$reles);
$data = Db::name('auth_rule')
->field('id, pid, title, url,icon')
->whereIn('id', $ids)
->select();
// var_dump($data);die();
$tree = $this->buildTree($data);
$this->success('请求成功',$tree);
}
/**
* 构建树结构
*
* @param array $data 数据库查询结果数组
* @param int $parentId 父ID
* @return array
*/
private function buildTree(array $data, $parentId = 0)
{
$tree = [];
foreach ($data as $item) {
if ($item['pid'] == $parentId) {
// 创建一个新的节点数组
$node = [
'id' => $item['url'], // 将 URL 替换为 ID
'pid' => $item['pid'],
'title' => $item['title'],
'url' => $item['url'],
'icon'=>$item['icon'],
];
// 递归构建子树
$children = $this->buildTree($data, $item['id']); // 使用原始的 ID 作为父 ID
if ($children) {
$node['children'] = $children;
}
$tree[] = $node;
}
}
return $tree;
}
}