Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

1.2 KB
Raw Blame
import { ExecutionContext, Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { AuthGuard } from '@nestjs/passport'
import { IS_OPTIONAL_AUTH_KEY } from '../decorators'

@Injectable()
export class MultiAuthGuard extends AuthGuard(['jwt-access-token', 'api-key']) {
  constructor(private readonly reflector: Reflector) {
    super()
  }

  canActivate(context: ExecutionContext) {
    if (context.switchToHttp().getRequest().headers?.['x-api-key']) {
      const KeyGuard = AuthGuard('api-key')
      return new KeyGuard().canActivate(context)
    }
    return super.canActivate(context)
  }

  handleRequest(
    err: any,
    user: any,
    info: any,
    context: ExecutionContext,
    status?: any,
  ) {
    const isOptionalAuth = this.reflector.getAllAndOverride<boolean>(
      IS_OPTIONAL_AUTH_KEY,
      [context.getHandler(), context.getClass()],
    )

    if (isOptionalAuth) {
      const request = context.switchToHttp().getRequest()
      const hasCredentials = Boolean(
        request.headers?.authorization ||
        request.headers?.['x-api-key'] ||
        request.cookies?.token,
      )

      if (!hasCredentials) return user
    }

    return super.handleRequest(err, user, info, context, status)
  }
}