Auth.php 4.17 KB
<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\service\AuthContext;
use think\facade\Db;

class Auth extends BaseController
{
    public function login()
    {
        $username = trim((string) $this->request->post('username', ''));
        $password = (string) $this->request->post('password', '');
        if ($username === '' || $password === '') {
            return json(['code' => 400, 'msg' => '请输入账号密码', 'data' => []]);
        }

        $admin = Db::name('sys_admin')->where('username', $username)->where('status', 1)->find();
        if (!$admin || !password_verify($password, (string) $admin['password'])) {
            return json(['code' => 400, 'msg' => '账号或密码错误', 'data' => []]);
        }

        $token  = bin2hex(random_bytes(32));
        $expire = date('Y-m-d H:i:s', time() + 86400 * 7);
        Db::name('sys_admin')->where('id', $admin['id'])->update([
            'api_token'     => $token,
            'token_expire'  => $expire,
            'update_time'   => date('Y-m-d H:i:s'),
        ]);

        $roleName = '';
        if ((int) $admin['role_id'] > 0) {
            $roleName = (string) (Db::name('sys_role')->where('id', $admin['role_id'])->value('name') ?: '');
        }

        return json([
            'code' => 0,
            'msg'  => 'ok',
            'data' => [
                'token' => $token,
                'admin' => [
                    'id'        => (int) $admin['id'],
                    'username'  => $admin['username'],
                    'nickname'  => $admin['nickname'],
                    'role_id'   => (int) $admin['role_id'],
                    'role_name' => $roleName,
                ],
            ],
        ]);
    }

    public function profile()
    {
        $admin = AuthContext::admin();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '未登录', 'data' => []]);
        }

        $roleName = '';
        if ((int) $admin['role_id'] > 0) {
            $roleName = (string) (Db::name('sys_role')->where('id', $admin['role_id'])->value('name') ?: '');
        }

        return json([
            'code' => 0,
            'msg'  => 'ok',
            'data' => [
                'id'        => (int) $admin['id'],
                'username'  => $admin['username'],
                'nickname'  => $admin['nickname'],
                'role_id'   => (int) $admin['role_id'],
                'role_name' => $roleName,
            ],
        ]);
    }

    public function menus()
    {
        $admin = AuthContext::admin();
        if (!$admin) {
            return json(['code' => 401, 'msg' => '未登录', 'data' => []]);
        }

        $roleId = (int) $admin['role_id'];
        $menuIds = Db::name('sys_role_menu')->where('role_id', $roleId)->column('menu_id');
        if ($menuIds === []) {
            return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => []]]);
        }

        $rows = Db::name('sys_menu')
            ->whereIn('id', $menuIds)
            ->where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();

        $tree = $this->buildMenuTree($rows, 0);

        return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => $tree]]);
    }

    /**
     * @param list<array<string,mixed>> $rows
     * @return list<array<string,mixed>>
     */
    protected function buildMenuTree(array $rows, int $parentId): array
    {
        $out = [];
        foreach ($rows as $r) {
            if ((int) $r['parent_id'] !== $parentId) {
                continue;
            }
            $node = [
                'id'        => (int) $r['id'],
                'parent_id' => (int) $r['parent_id'],
                'name'      => $r['name'],
                'type'      => (int) $r['type'],
                'path'      => $r['path'],
                'component' => $r['component'],
                'perms'     => $r['perms'],
                'icon'      => $r['icon'],
                'sort'      => (int) $r['sort'],
                'children'  => $this->buildMenuTree($rows, (int) $r['id']),
            ];
            $out[] = $node;
        }

        return $out;
    }
}