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();
|
};
|
}
|
}
|