File size: 803 Bytes
d988ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class AdminAuthGuard implements CanActivate {
  private readonly expectedToken = process.env.ADMIN_TOKEN || 'admin-token';

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const headerToken = request.headers['x-admin-token'] || request.headers['authorization'];
    const token = typeof headerToken === 'string' && headerToken.startsWith('Bearer ')
      ? headerToken.slice(7)
      : headerToken;

    if (token === this.expectedToken) {
      return true;
    }

    throw new UnauthorizedException('Invalid admin token');
  }
}