Blame view

稻城亚丁小程序/backend/app/middleware/AdminAuth.php 991 Bytes
bc518174   王天杨   提交两个项目文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  <?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);
      }
  }