wangrong
9 小时以前 0d90e20ec20f0aeee642756a7ebf9e8514174124
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { ALL, Config, Middleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware, Init, Inject } from '@midwayjs/core';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import { CoolCommException, CoolUrlTagData, TagTypes } from '@cool-midway/core';
import { Utils } from '../../../comm/utils';
import { UserInfoService } from '../service/info';
 
/**
 * 用户
 */
@Middleware()
export class UserMiddleware implements IMiddleware<Context, NextFunction> {
  @Config(ALL)
  coolConfig;
 
  @Inject()
  coolUrlTagData: CoolUrlTagData;
 
  @Config('module.user.jwt')
  jwtConfig;
 
  ignoreUrls: string[] = [];
 
  @Config('koa.globalPrefix')
  prefix;
 
  @Inject()
  utils: Utils;
 
  @Init()
  async init() {
    this.ignoreUrls = this.coolUrlTagData.byKey(TagTypes.IGNORE_TOKEN, 'app');
  }
 
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      let { url } = ctx;
      url = url.replace(this.prefix, '').split('?')[0];
      if (_.startsWith(url, '/app/')) {
        let token = ctx.get('Authorization') || '';
        token = token.replace(/^Bearer\s+/i, '').trim();
        try {
          ctx.user = jwt.verify(token, this.jwtConfig.secret);
        } catch (error) {
          ctx.user = undefined;
          if (token) {
            console.error('[user] token无效:', (error as Error).message);
          }
        }
        if (ctx.user?.isRefresh) {
          ctx.user = undefined;
        } else if (ctx.user?.id) {
          try {
            // 令牌里的 id 是 unionid(手机号登录时就是手机号),整型 userId 列要用用户主键
            const userInfoService = await ctx.requestContext.getAsync(
              UserInfoService
            );
            const info = await userInfoService.person(ctx.user.id);
            if (info?.id) {
              ctx.user.userId = info.id;
            }
          } catch (error) {}
        }
        // 使用matchUrl方法来检查URL是否应该被忽略
        const isIgnored = this.ignoreUrls.some(pattern =>
          this.utils.matchUrl(pattern, url)
        );
        if (isIgnored) {
          await next();
          return;
        } else {
          if (!ctx.user) {
            ctx.status = 401;
            throw new CoolCommException('登录失效~');
          }
        }
      }
      await next();
    };
  }
}