File size: 1,367 Bytes
f3abb0d
4acc19f
 
f3abb0d
4acc19f
d201b18
 
4acc19f
 
f3abb0d
 
4acc19f
 
 
f3abb0d
 
 
d201b18
 
 
 
 
 
 
 
 
 
 
 
4acc19f
 
 
 
 
 
 
 
 
 
 
 
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
import { Injectable, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { Observable } from 'rxjs';
import { IS_PUBLIC_KEY } from 'src/shared/decorators/public.decorator';
import { LOG_TO_DISCORD } from 'src/shared/decorators/log-to-discord.decorator';
import { SHOULD_LOG_TO_DISCORD } from 'src/shared/modules/discord-logger/discord-logger.filter';

@Injectable()
export class UserAuthGuard extends AuthGuard('user-jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    // Check if route should be logged to Discord
    const shouldLogToDiscord =
      this.reflector.get<boolean>(LOG_TO_DISCORD, context.getHandler()) ||
      this.reflector.get<boolean>(LOG_TO_DISCORD, context.getClass());

    // Mark the request if it should be logged
    if (shouldLogToDiscord) {
      const request = context.switchToHttp().getRequest();
      (request as any)[SHOULD_LOG_TO_DISCORD] = true;
    }

    // Check if route is public
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      return true;
    }

    return super.canActivate(context);
  }
}