Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

如何在nestjs的权限拦截器里面调用service层的方法

我的拦截期是验证token的,

import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Inject,
  Injectable,
} from '@nestjs/common';
import { Observable } from 'rxjs';
const whiteList = ['/admin/login'];
import { UserService } from '../service/user/user.service';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(@Inject('UserService') private readonly User: UserService) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.token;
    const url = request.route.path;
    //白名单的直接返回
 if (whiteList.includes(url)) {
      return true;
    }
    if (!token) {
      throw new HttpException('用户未登录', HttpStatus.BAD_REQUEST);
    }
    //const user= this.userService.getUserInfo();
 // user.then(res=>{ //   console.log(res) // })
 if (token != '1') {
      throw new HttpException('登陆失效,请重新登陆', HttpStatus.BAD_REQUEST);
    }
    return true;
  }
}

需要拿用户请求的token和数据库的token对比,然后判断token是否正确,我发现我不能再这个拦截器里用userservice这个服务层的数据。有大佬遇到过吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...