auth in progress

This commit is contained in:
andres
2023-06-13 14:31:05 +02:00
parent 779b235363
commit 6f2fab076d
13 changed files with 181 additions and 29 deletions

View File

@@ -0,0 +1,24 @@
import { Inject, Injectable } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { AppSettings } from '../../../settings/app-settings'
type JwtPayload = {
userId: string
username: string
}
@Injectable()
export class AccessTokenStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(@Inject(AppSettings.name) private readonly appSettings: AppSettings) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: appSettings.auth.ACCESS_JWT_SECRET_KEY,
})
}
async validate(payload: JwtPayload) {
return { userId: payload.userId }
}
}

View File

@@ -1,19 +1,42 @@
import { Inject, Injectable } from '@nestjs/common'
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { AppSettings } from '../../../settings/app-settings'
import { Request } from 'express'
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(@Inject(AppSettings.name) private readonly appSettings: AppSettings) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: true,
ignoreExpiration: false,
secretOrKey: appSettings.auth.ACCESS_JWT_SECRET_KEY,
})
}
async validate(payload: any) {
return { userId: payload.userId }
async validate(request: Request, payload: any) {
const accessToken = request.headers.authorization?.split(' ')[1]
const refreshToken = request.cookies.refreshToken // Extract refresh token from cookies
// If there's no refresh token, simply validate the user based on payload
if (!refreshToken) {
return { userId: payload.userId }
}
try {
const newAccessToken = await this.authService.checkToken(accessToken, refreshToken)
// If new access token were issued, attach it to the response headers
if (newAccessToken) {
request.res.setHeader('Authorization', `Bearer ${newAccessToken.accessToken}`)
}
request.res.cookie('refreshToken', newAccessToken.refreshToken, {
httpOnly: true,
path: '/auth/refresh-token',
})
return { userId: payload.userId }
} catch (error) {
throw new UnauthorizedException('Invalid tokens')
}
}
}

View File

@@ -12,10 +12,10 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.checkCredentials(email, password)
if (user.resultCode === 1) {
const credentials = await this.authService.checkCredentials(email, password)
if (credentials.resultCode === 1) {
throw new UnauthorizedException()
}
return user
return credentials
}
}

View File

@@ -0,0 +1,27 @@
import { Inject, Injectable } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { AppSettings } from '../../../settings/app-settings'
import { Request } from 'express'
type JwtPayload = {
userId: string
username: string
}
@Injectable()
export class RefreshTokenStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
constructor(@Inject(AppSettings.name) private readonly appSettings: AppSettings) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: appSettings.auth.ACCESS_JWT_SECRET_KEY,
passReqToCallback: true,
})
}
validate(req: Request, payload: any) {
const refreshToken = req.get('Authorization').replace('Bearer', '').trim()
return { ...payload, refreshToken }
}
}