Blame view

稻城亚丁小程序/backend/app/middleware/MiniAuth.php 940 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
  <?php
  declare(strict_types=1);
  
  namespace app\middleware;
  
  use app\service\AuthContext;
  use think\facade\Db;
  
  /**
   * 小程序端:Authorization: Bearer <mp_token>
   */
  class MiniAuth
  {
      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));
          $user  = Db::name('mp_user')->where('api_token', $token)->find();
  
          if (!$user) {
              return json(['code' => 401, 'msg' => '请先登录或重新进入', 'data' => []]);
          }
  
          if ((int) ($user['status'] ?? 1) !== 1) {
              return json(['code' => 403, 'msg' => '账号已被禁用', 'data' => []]);
          }
  
          AuthContext::setMpUser($user);
          return $next($request);
      }
  }