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
import { Config, Inject, Middleware } from '@midwayjs/core';
import { NextFunction } from '@midwayjs/socketio';
import * as jwt from 'jsonwebtoken';
import { UserInfoService } from '../../../user/service/info';
 
@Middleware()
export class CsSocketTokenMiddleware {
  @Config('module.user.jwt')
  appJwtConfig;
 
  @Config('module.base.jwt')
  adminJwtConfig;
 
  @Inject()
  userInfoService: UserInfoService;
 
  resolve() {
    return async (ctx, next: NextFunction) => {
      try {
        // 获得连接参数
        const isAdmin = ctx.handshake.auth.isAdmin;
        const token = ctx.handshake.auth.token;
        const data = jwt.verify(
          token,
          isAdmin ? this.adminJwtConfig.secret : this.appJwtConfig.secret
        );
        let userId = isAdmin ? data.userId : data.id;
        if (!isAdmin) {
          const info = await this.userInfoService.person(data.id);
          userId = info?.id;
        }
        ctx.connData = {
          userId,
          isAdmin,
        };
      } catch (error) {
        ctx.emit('sys', '连接失败');
        return;
      }
      return await next();
    };
  }
}