import { IMiddleware, Inject, Middleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import get = require('lodash/get');
import { JwtService } from '@midwayjs/jwt';

@Middleware()
export class CheckTokenMiddleware implements IMiddleware<Context, NextFunction> {
  @Inject()
  jwtService: JwtService;
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const token: any = get(ctx.request, 'header.token');
      if (token) {
        const data = this.jwtService.decodeSync(token);
        if (data) ctx.user = data;
      }
      // 添加管理员身份
      const adminToken: any = get(ctx.request, 'header.admin-token');
      if (adminToken) {
        const data = this.jwtService.decodeSync(adminToken);
        if (data) ctx.admin = data;
      }
      await next();
    };
  }

  static getName(): string {
    return 'checkToken';
  }
}
