mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-25 20:59:28 +00:00
resend email in progress
This commit is contained in:
@@ -11,13 +11,16 @@ import {
|
||||
BadRequestException,
|
||||
Res,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common'
|
||||
import { AuthService } from './auth.service'
|
||||
import { RegistrationDto } from './dto/registration.dto'
|
||||
import { LocalAuthGuard } from './guards/local-auth.guard'
|
||||
import { UsersService } from '../users/services/users.service'
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard'
|
||||
|
||||
import { Response as ExpressResponse } from 'express'
|
||||
import { JwtRefreshGuard } from './guards/jwt-refresh.guard'
|
||||
import { Cookies } from '../../infrastructure/decorators/cookie.decorator'
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
@@ -28,7 +31,7 @@ export class AuthController {
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('me')
|
||||
async getUserData(@Request() req) {
|
||||
const userId = req.user.userId
|
||||
const userId = req.user.id
|
||||
const user = await this.usersService.getUserById(userId)
|
||||
|
||||
if (!user) throw new UnauthorizedException()
|
||||
@@ -42,12 +45,13 @@ export class AuthController {
|
||||
|
||||
@HttpCode(200)
|
||||
@UseGuards(LocalAuthGuard)
|
||||
@Post('sign-in')
|
||||
async login(@Request() req, @Res({ passthrough: true }) res) {
|
||||
@Post('login')
|
||||
async login(@Request() req, @Res({ passthrough: true }) res: ExpressResponse) {
|
||||
const userData = req.user.data
|
||||
res.cookie('refreshToken', userData.refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
// secure: true,
|
||||
path: '/v1/auth/refresh-token',
|
||||
})
|
||||
return { accessToken: req.user.data.accessToken }
|
||||
}
|
||||
@@ -62,7 +66,8 @@ export class AuthController {
|
||||
)
|
||||
}
|
||||
|
||||
@Post('registration-confirmation')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('verify-email')
|
||||
async confirmRegistration(@Body('code') confirmationCode) {
|
||||
const result = await this.authService.confirmEmail(confirmationCode)
|
||||
if (!result) {
|
||||
@@ -71,12 +76,12 @@ export class AuthController {
|
||||
return null
|
||||
}
|
||||
|
||||
@Post('registration-email-resending')
|
||||
async resendRegistrationEmail(@Body('email') email: string) {
|
||||
const isResented = await this.authService.resendCode(email)
|
||||
if (!isResented)
|
||||
@Post('resend-verification-email')
|
||||
async resendRegistrationEmail(@Body('userId') userId: string) {
|
||||
const isResent = await this.authService.resendCode(userId)
|
||||
if (!isResent)
|
||||
throw new BadRequestException({
|
||||
message: 'email already confirmed or such email not found',
|
||||
message: 'Email already confirmed or such email was not found',
|
||||
field: 'email',
|
||||
})
|
||||
return null
|
||||
@@ -84,24 +89,31 @@ export class AuthController {
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('logout')
|
||||
async logout(@Request() req) {
|
||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException()
|
||||
await this.usersService.addRevokedToken(req.cookie.refreshToken)
|
||||
async logout(
|
||||
@Cookies('refreshToken') refreshToken: string,
|
||||
@Res({ passthrough: true }) res: ExpressResponse
|
||||
) {
|
||||
if (!refreshToken) throw new UnauthorizedException()
|
||||
await this.usersService.addRevokedToken(refreshToken)
|
||||
res.clearCookie('refreshToken')
|
||||
return null
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('refresh-token')
|
||||
async refreshToken(@Request() req, @Response() res) {
|
||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@UseGuards(JwtRefreshGuard)
|
||||
@Get('refresh-token')
|
||||
async refreshToken(@Request() req, @Response({ passthrough: true }) res: ExpressResponse) {
|
||||
if (!req.cookies?.refreshToken) throw new UnauthorizedException()
|
||||
const userId = req.user.id
|
||||
const newTokens = await this.authService.createJwtTokensPair(userId)
|
||||
res.cookie('refreshToken', newTokens.refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
path: '/refresh',
|
||||
// secure: true,
|
||||
path: '/v1/auth/refresh-token',
|
||||
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
|
||||
})
|
||||
return { accessToken: newTokens.accessToken }
|
||||
return {
|
||||
accessToken: newTokens.accessToken,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common'
|
||||
import { addDays, isAfter } from 'date-fns'
|
||||
import { addDays, isBefore } from 'date-fns'
|
||||
import * as jwt from 'jsonwebtoken'
|
||||
import * as bcrypt from 'bcrypt'
|
||||
import { UsersRepository } from '../users/infrastructure/users.repository'
|
||||
@@ -56,7 +56,6 @@ export class AuthService {
|
||||
isRevoked: false,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
@@ -133,19 +132,21 @@ export class AuthService {
|
||||
}
|
||||
|
||||
async confirmEmail(token: string): Promise<boolean> {
|
||||
const user = await this.usersRepository.findUserByVerificationToken(token)
|
||||
if (!user || user.isEmailVerified) return false
|
||||
const dbToken = user.verificationToken
|
||||
const isTokenExpired = isAfter(user.verificationTokenExpiry, new Date())
|
||||
const verificationWithUser = await this.usersRepository.findUserByVerificationToken(token)
|
||||
console.log(verificationWithUser)
|
||||
if (!verificationWithUser || verificationWithUser.isEmailVerified) return false
|
||||
const dbToken = verificationWithUser.verificationToken
|
||||
const isTokenExpired = isBefore(verificationWithUser.verificationTokenExpiry, new Date())
|
||||
console.log({ isTokenExpired })
|
||||
if (dbToken !== token || isTokenExpired) {
|
||||
return false
|
||||
}
|
||||
|
||||
return await this.usersRepository.updateConfirmation(user.id)
|
||||
return await this.usersRepository.updateConfirmation(verificationWithUser.userId)
|
||||
}
|
||||
|
||||
async resendCode(email: string) {
|
||||
const user = await this.usersRepository.findUserByEmail(email)
|
||||
async resendCode(userId: string) {
|
||||
const user = await this.usersRepository.findUserById(userId)
|
||||
if (!user || user?.verification.isEmailVerified) return null
|
||||
const updatedUser = await this.usersRepository.updateVerificationToken(user.id)
|
||||
if (!updatedUser) return null
|
||||
|
||||
5
src/modules/auth/guards/jwt-refresh.guard.ts
Normal file
5
src/modules/auth/guards/jwt-refresh.guard.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import { AuthGuard } from '@nestjs/passport'
|
||||
|
||||
@Injectable()
|
||||
export class JwtRefreshGuard extends AuthGuard('jwt-refresh') {}
|
||||
34
src/modules/auth/strategies/jwt-refresh.strategy.ts
Normal file
34
src/modules/auth/strategies/jwt-refresh.strategy.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Inject, Injectable } from '@nestjs/common'
|
||||
import { PassportStrategy } from '@nestjs/passport'
|
||||
import { Strategy } from 'passport-jwt'
|
||||
import { UsersService } from '../../users/services/users.service'
|
||||
import { AppSettings } from '../../../settings/app-settings'
|
||||
import { Request } from 'express'
|
||||
|
||||
const cookieExtractor = function (req: Request) {
|
||||
console.log(req.cookies)
|
||||
let token = null
|
||||
if (req && req.cookies) {
|
||||
token = req.cookies['refreshToken']
|
||||
}
|
||||
console.log(token)
|
||||
return token
|
||||
}
|
||||
// ...
|
||||
@Injectable()
|
||||
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
|
||||
constructor(
|
||||
@Inject(AppSettings.name) private readonly appSettings: AppSettings,
|
||||
private userService: UsersService
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: cookieExtractor,
|
||||
ignoreExpiration: true,
|
||||
secretOrKey: appSettings.auth.REFRESH_JWT_SECRET_KEY,
|
||||
})
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
return this.userService.getUserById(payload.userId)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'
|
||||
import { PassportStrategy } from '@nestjs/passport'
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt'
|
||||
import { AuthService } from '../auth.service'
|
||||
import { AppSettings } from '../../../settings/app-settings'
|
||||
import { Request } from 'express'
|
||||
import { UsersService } from '../../users/services/users.service'
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(@Inject(AppSettings.name) private readonly appSettings: AppSettings) {
|
||||
constructor(
|
||||
@Inject(AppSettings.name) private readonly appSettings: AppSettings,
|
||||
private authService: AuthService,
|
||||
private userService: UsersService
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
@@ -14,29 +19,12 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
})
|
||||
}
|
||||
|
||||
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')
|
||||
async validate(payload: any) {
|
||||
console.log(payload)
|
||||
const user = await this.userService.getUserById(payload.userId)
|
||||
if (!user) {
|
||||
throw new UnauthorizedException()
|
||||
}
|
||||
return user
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,10 +12,10 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
|
||||
}
|
||||
|
||||
async validate(email: string, password: string): Promise<any> {
|
||||
const credentials = await this.authService.checkCredentials(email, password)
|
||||
if (credentials.resultCode === 1) {
|
||||
const newCredentials = await this.authService.checkCredentials(email, password)
|
||||
if (newCredentials.resultCode === 1) {
|
||||
throw new UnauthorizedException()
|
||||
}
|
||||
return credentials
|
||||
return newCredentials
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
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 }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user