Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

1.8 KB
Raw Blame
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { AbstractStrategy, PassportStrategy } from '@nestjs/passport'
import { FastifyRequest } from 'fastify'
import { PinoLogger } from 'nestjs-pino'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { UserModel } from '../../applications/users/models/user.model.js'
import { configuration } from '../../configuration/config.environment.js'
import { AuthManager } from '../auth.service.js'
import type { JwtPayload } from '../interfaces/jwt-payload.interface.js'
import { TOKEN_TYPE } from '../interfaces/token.interface.js'

@Injectable()
export class AuthTokenAccessStrategy extends PassportStrategy(Strategy, 'tokenAccess') implements AbstractStrategy {
  private static accessCookieName: string

  constructor(
    private readonly authManager: AuthManager,
    private readonly logger: PinoLogger
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([AuthTokenAccessStrategy.extractJWTFromCookie, ExtractJwt.fromAuthHeaderAsBearerToken()]),
      secretOrKey: configuration.auth.token.access.secret,
      ignoreExpiration: false,
      passReqToCallback: true
    })
    AuthTokenAccessStrategy.accessCookieName = configuration.auth.token.access.name
  }

  validate(req: FastifyRequest, jwtPayload: JwtPayload): UserModel {
    if (jwtPayload.tokenType !== TOKEN_TYPE.ACCESS) {
      throw new UnauthorizedException()
    }
    this.logger.assign({ user: jwtPayload.identity.login })
    this.authManager.csrfValidation(req, jwtPayload, TOKEN_TYPE.ACCESS)
    return new UserModel(jwtPayload.identity)
  }

  static extractJWTFromCookie(req: FastifyRequest): string | null {
    if (typeof req.cookies === 'object' && req.cookies[AuthTokenAccessStrategy.accessCookieName] !== undefined) {
      return req.cookies[AuthTokenAccessStrategy.accessCookieName] as string
    }
    return null
  }
}