AdminAuth.php 991 Bytes
<?php
declare(strict_types=1);

namespace app\middleware;

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

class AdminAuth
{
    public function handle($request, \Closure $next)
    {
        $auth = $request->header('Authorization', '');
        if (!is_string($auth) || !str_starts_with($auth, 'Bearer ')) {
            return json(['code' => 401, 'msg' => '请先登录管理端', 'data' => []]);
        }
        $token = trim(substr($auth, 7));
        if ($token === '') {
            return json(['code' => 401, 'msg' => 'Token 无效', 'data' => []]);
        }

        $now = date('Y-m-d H:i:s');
        $admin = Db::name('sys_admin')
            ->where('api_token', $token)
            ->where('token_expire', '>', $now)
            ->where('status', 1)
            ->find();

        if (!$admin) {
            return json(['code' => 401, 'msg' => '登录已过期', 'data' => []]);
        }

        AuthContext::setAdmin($admin);
        return $next($request);
    }
}