mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-17 05:09:26 +00:00
resend email in progress
This commit is contained in:
@@ -46,6 +46,7 @@
|
|||||||
"passport-jwt": "^4.0.1",
|
"passport-jwt": "^4.0.1",
|
||||||
"passport-local": "^1.0.0",
|
"passport-local": "^1.0.0",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"remeda": "^1.19.0",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
"uuid": "^9.0.0"
|
"uuid": "^9.0.0"
|
||||||
},
|
},
|
||||||
|
|||||||
7
pnpm-lock.yaml
generated
7
pnpm-lock.yaml
generated
@@ -80,6 +80,9 @@ dependencies:
|
|||||||
reflect-metadata:
|
reflect-metadata:
|
||||||
specifier: ^0.1.13
|
specifier: ^0.1.13
|
||||||
version: 0.1.13
|
version: 0.1.13
|
||||||
|
remeda:
|
||||||
|
specifier: ^1.19.0
|
||||||
|
version: 1.19.0
|
||||||
rxjs:
|
rxjs:
|
||||||
specifier: ^7.8.1
|
specifier: ^7.8.1
|
||||||
version: 7.8.1
|
version: 7.8.1
|
||||||
@@ -6951,6 +6954,10 @@ packages:
|
|||||||
engines: {node: '>= 0.10'}
|
engines: {node: '>= 0.10'}
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
|
/remeda@1.19.0:
|
||||||
|
resolution: {integrity: sha512-iwZohiXDhC1K+adRI6OB+tYxOfXyX7DaPXQDZrR5s1k7umrkG3Yd2+QDfSrYFlC7oc0IqeUns6RqSjNkERXeLw==}
|
||||||
|
dev: false
|
||||||
|
|
||||||
/remote-content@3.0.1:
|
/remote-content@3.0.1:
|
||||||
resolution: {integrity: sha512-zEMsvb4GgxVKBBTHgy2tte67RYBZx2Kyg9mTYpg+JfATHDqYJqhuC3zG1VoiYhDVP5JaB5+mPKcAvdnT0n3jxA==}
|
resolution: {integrity: sha512-zEMsvb4GgxVKBBTHgy2tte67RYBZx2Kyg9mTYpg+JfATHDqYJqhuC3zG1VoiYhDVP5JaB5+mPKcAvdnT0n3jxA==}
|
||||||
dependencies:
|
dependencies:
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ model User {
|
|||||||
email String @unique
|
email String @unique
|
||||||
password String
|
password String
|
||||||
isAdmin Boolean @default(false)
|
isAdmin Boolean @default(false)
|
||||||
|
isEmailVerified Boolean @default(false)
|
||||||
name String @db.VarChar(40)
|
name String @db.VarChar(40)
|
||||||
avatar String?
|
avatar String?
|
||||||
deckCount Int @default(0)
|
deckCount Int @default(0)
|
||||||
@@ -49,7 +50,7 @@ model RevokedToken {
|
|||||||
userId String
|
userId String
|
||||||
token String @unique
|
token String @unique
|
||||||
revokedAt DateTime @default(now())
|
revokedAt DateTime @default(now())
|
||||||
user User @relation(fields: [userId], references: [id])
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
}
|
}
|
||||||
@@ -60,7 +61,7 @@ model RefreshToken {
|
|||||||
token String @unique @db.VarChar(255)
|
token String @unique @db.VarChar(255)
|
||||||
expiresAt DateTime
|
expiresAt DateTime
|
||||||
isRevoked Boolean @default(false)
|
isRevoked Boolean @default(false)
|
||||||
user User @relation(fields: [userId], references: [id])
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
}
|
}
|
||||||
@@ -83,8 +84,8 @@ model Card {
|
|||||||
moreId String?
|
moreId String?
|
||||||
created DateTime @default(now())
|
created DateTime @default(now())
|
||||||
updated DateTime @updatedAt
|
updated DateTime @updatedAt
|
||||||
user User @relation(fields: [userId], references: [id])
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
decks Deck @relation(fields: [deckId], references: [id])
|
decks Deck @relation(fields: [deckId], references: [id], onDelete: Cascade)
|
||||||
grades Grade[] // One-to-many relation
|
grades Grade[] // One-to-many relation
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
import { Module } from '@nestjs/common'
|
import { Module } from '@nestjs/common'
|
||||||
import { JwtStrategy } from './modules/auth/strategies/jwt.strategy'
|
import { JwtStrategy } from './modules/auth/strategies/jwt.strategy'
|
||||||
import { JwtPayloadExtractorStrategy } from './guards/common/jwt-payload-extractor.strategy'
|
|
||||||
import { JwtPayloadExtractorGuard } from './guards/common/jwt-payload-extractor.guard'
|
|
||||||
import { ConfigModule } from './settings/config.module'
|
import { ConfigModule } from './settings/config.module'
|
||||||
import { AuthModule } from './modules/auth/auth.module'
|
import { AuthModule } from './modules/auth/auth.module'
|
||||||
import { UsersModule } from './modules/users/users.module'
|
import { UsersModule } from './modules/users/users.module'
|
||||||
import { PrismaModule } from './prisma.module'
|
import { PrismaModule } from './prisma.module'
|
||||||
import { MailerModule } from '@nestjs-modules/mailer'
|
import { MailerModule } from '@nestjs-modules/mailer'
|
||||||
import * as process from 'process'
|
import * as process from 'process'
|
||||||
|
import { JwtRefreshStrategy } from './modules/auth/strategies/jwt-refresh.strategy'
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -29,7 +28,7 @@ import * as process from 'process'
|
|||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
controllers: [],
|
controllers: [],
|
||||||
providers: [JwtStrategy, JwtPayloadExtractorStrategy, JwtPayloadExtractorGuard],
|
providers: [JwtStrategy, JwtRefreshStrategy],
|
||||||
exports: [],
|
exports: [],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'
|
|
||||||
import { AuthGuard } from '@nestjs/passport'
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class JwtPayloadExtractorGuard extends AuthGuard('payloadExtractor') {
|
|
||||||
canActivate(context: ExecutionContext) {
|
|
||||||
// Add your custom authentication logic here
|
|
||||||
// for example, call super.logIn(request) to establish a session.
|
|
||||||
console.log('JwtPayloadExtractorGuard')
|
|
||||||
return super.canActivate(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
handleRequest(err, user, info) {
|
|
||||||
// You can throw an exception based on either "info" or "err" arguments
|
|
||||||
if (err) {
|
|
||||||
throw err || new UnauthorizedException()
|
|
||||||
}
|
|
||||||
return user
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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 { AuthService } from '../../modules/auth/auth.service'
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class JwtPayloadExtractorStrategy extends PassportStrategy(Strategy, 'payloadExtractor') {
|
|
||||||
constructor(
|
|
||||||
@Inject(AppSettings.name) private readonly appSettings: AppSettings,
|
|
||||||
private readonly authService: AuthService
|
|
||||||
) {
|
|
||||||
super({
|
|
||||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
||||||
ignoreExpiration: false,
|
|
||||||
secretOrKey: appSettings.auth.ACCESS_JWT_SECRET_KEY,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async validate(payload: any) {
|
|
||||||
console.log(payload)
|
|
||||||
const userId = payload.userId
|
|
||||||
const name = payload.name
|
|
||||||
if (payload) return { userId, name }
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
6
src/infrastructure/decorators/cookie.decorator.ts
Normal file
6
src/infrastructure/decorators/cookie.decorator.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common'
|
||||||
|
|
||||||
|
export const Cookies = createParamDecorator((data: string, ctx: ExecutionContext) => {
|
||||||
|
const request = ctx.switchToHttp().getRequest()
|
||||||
|
return data ? request.cookies?.[data] : request.cookies
|
||||||
|
})
|
||||||
@@ -11,13 +11,16 @@ import {
|
|||||||
BadRequestException,
|
BadRequestException,
|
||||||
Res,
|
Res,
|
||||||
HttpCode,
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
} from '@nestjs/common'
|
} from '@nestjs/common'
|
||||||
import { AuthService } from './auth.service'
|
import { AuthService } from './auth.service'
|
||||||
import { RegistrationDto } from './dto/registration.dto'
|
import { RegistrationDto } from './dto/registration.dto'
|
||||||
import { LocalAuthGuard } from './guards/local-auth.guard'
|
import { LocalAuthGuard } from './guards/local-auth.guard'
|
||||||
import { UsersService } from '../users/services/users.service'
|
import { UsersService } from '../users/services/users.service'
|
||||||
import { JwtAuthGuard } from './guards/jwt-auth.guard'
|
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')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -28,7 +31,7 @@ export class AuthController {
|
|||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Get('me')
|
@Get('me')
|
||||||
async getUserData(@Request() req) {
|
async getUserData(@Request() req) {
|
||||||
const userId = req.user.userId
|
const userId = req.user.id
|
||||||
const user = await this.usersService.getUserById(userId)
|
const user = await this.usersService.getUserById(userId)
|
||||||
|
|
||||||
if (!user) throw new UnauthorizedException()
|
if (!user) throw new UnauthorizedException()
|
||||||
@@ -42,12 +45,13 @@ export class AuthController {
|
|||||||
|
|
||||||
@HttpCode(200)
|
@HttpCode(200)
|
||||||
@UseGuards(LocalAuthGuard)
|
@UseGuards(LocalAuthGuard)
|
||||||
@Post('sign-in')
|
@Post('login')
|
||||||
async login(@Request() req, @Res({ passthrough: true }) res) {
|
async login(@Request() req, @Res({ passthrough: true }) res: ExpressResponse) {
|
||||||
const userData = req.user.data
|
const userData = req.user.data
|
||||||
res.cookie('refreshToken', userData.refreshToken, {
|
res.cookie('refreshToken', userData.refreshToken, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
// secure: true,
|
||||||
|
path: '/v1/auth/refresh-token',
|
||||||
})
|
})
|
||||||
return { accessToken: req.user.data.accessToken }
|
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) {
|
async confirmRegistration(@Body('code') confirmationCode) {
|
||||||
const result = await this.authService.confirmEmail(confirmationCode)
|
const result = await this.authService.confirmEmail(confirmationCode)
|
||||||
if (!result) {
|
if (!result) {
|
||||||
@@ -71,12 +76,12 @@ export class AuthController {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('registration-email-resending')
|
@Post('resend-verification-email')
|
||||||
async resendRegistrationEmail(@Body('email') email: string) {
|
async resendRegistrationEmail(@Body('userId') userId: string) {
|
||||||
const isResented = await this.authService.resendCode(email)
|
const isResent = await this.authService.resendCode(userId)
|
||||||
if (!isResented)
|
if (!isResent)
|
||||||
throw new BadRequestException({
|
throw new BadRequestException({
|
||||||
message: 'email already confirmed or such email not found',
|
message: 'Email already confirmed or such email was not found',
|
||||||
field: 'email',
|
field: 'email',
|
||||||
})
|
})
|
||||||
return null
|
return null
|
||||||
@@ -84,24 +89,31 @@ export class AuthController {
|
|||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Post('logout')
|
@Post('logout')
|
||||||
async logout(@Request() req) {
|
async logout(
|
||||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException()
|
@Cookies('refreshToken') refreshToken: string,
|
||||||
await this.usersService.addRevokedToken(req.cookie.refreshToken)
|
@Res({ passthrough: true }) res: ExpressResponse
|
||||||
|
) {
|
||||||
|
if (!refreshToken) throw new UnauthorizedException()
|
||||||
|
await this.usersService.addRevokedToken(refreshToken)
|
||||||
|
res.clearCookie('refreshToken')
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@HttpCode(HttpStatus.OK)
|
||||||
@Post('refresh-token')
|
@UseGuards(JwtRefreshGuard)
|
||||||
async refreshToken(@Request() req, @Response() res) {
|
@Get('refresh-token')
|
||||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException()
|
async refreshToken(@Request() req, @Response({ passthrough: true }) res: ExpressResponse) {
|
||||||
|
if (!req.cookies?.refreshToken) throw new UnauthorizedException()
|
||||||
const userId = req.user.id
|
const userId = req.user.id
|
||||||
const newTokens = await this.authService.createJwtTokensPair(userId)
|
const newTokens = await this.authService.createJwtTokensPair(userId)
|
||||||
res.cookie('refreshToken', newTokens.refreshToken, {
|
res.cookie('refreshToken', newTokens.refreshToken, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
// secure: true,
|
||||||
path: '/refresh',
|
path: '/v1/auth/refresh-token',
|
||||||
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
|
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 { Injectable, UnauthorizedException } from '@nestjs/common'
|
||||||
import { addDays, isAfter } from 'date-fns'
|
import { addDays, isBefore } from 'date-fns'
|
||||||
import * as jwt from 'jsonwebtoken'
|
import * as jwt from 'jsonwebtoken'
|
||||||
import * as bcrypt from 'bcrypt'
|
import * as bcrypt from 'bcrypt'
|
||||||
import { UsersRepository } from '../users/infrastructure/users.repository'
|
import { UsersRepository } from '../users/infrastructure/users.repository'
|
||||||
@@ -56,7 +56,6 @@ export class AuthService {
|
|||||||
isRevoked: false,
|
isRevoked: false,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
accessToken,
|
accessToken,
|
||||||
refreshToken,
|
refreshToken,
|
||||||
@@ -133,19 +132,21 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async confirmEmail(token: string): Promise<boolean> {
|
async confirmEmail(token: string): Promise<boolean> {
|
||||||
const user = await this.usersRepository.findUserByVerificationToken(token)
|
const verificationWithUser = await this.usersRepository.findUserByVerificationToken(token)
|
||||||
if (!user || user.isEmailVerified) return false
|
console.log(verificationWithUser)
|
||||||
const dbToken = user.verificationToken
|
if (!verificationWithUser || verificationWithUser.isEmailVerified) return false
|
||||||
const isTokenExpired = isAfter(user.verificationTokenExpiry, new Date())
|
const dbToken = verificationWithUser.verificationToken
|
||||||
|
const isTokenExpired = isBefore(verificationWithUser.verificationTokenExpiry, new Date())
|
||||||
|
console.log({ isTokenExpired })
|
||||||
if (dbToken !== token || isTokenExpired) {
|
if (dbToken !== token || isTokenExpired) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return await this.usersRepository.updateConfirmation(user.id)
|
return await this.usersRepository.updateConfirmation(verificationWithUser.userId)
|
||||||
}
|
}
|
||||||
|
|
||||||
async resendCode(email: string) {
|
async resendCode(userId: string) {
|
||||||
const user = await this.usersRepository.findUserByEmail(email)
|
const user = await this.usersRepository.findUserById(userId)
|
||||||
if (!user || user?.verification.isEmailVerified) return null
|
if (!user || user?.verification.isEmailVerified) return null
|
||||||
const updatedUser = await this.usersRepository.updateVerificationToken(user.id)
|
const updatedUser = await this.usersRepository.updateVerificationToken(user.id)
|
||||||
if (!updatedUser) return null
|
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 { Inject, Injectable, UnauthorizedException } from '@nestjs/common'
|
||||||
import { PassportStrategy } from '@nestjs/passport'
|
import { PassportStrategy } from '@nestjs/passport'
|
||||||
import { ExtractJwt, Strategy } from 'passport-jwt'
|
import { ExtractJwt, Strategy } from 'passport-jwt'
|
||||||
|
import { AuthService } from '../auth.service'
|
||||||
import { AppSettings } from '../../../settings/app-settings'
|
import { AppSettings } from '../../../settings/app-settings'
|
||||||
import { Request } from 'express'
|
import { UsersService } from '../../users/services/users.service'
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
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({
|
super({
|
||||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
ignoreExpiration: false,
|
ignoreExpiration: false,
|
||||||
@@ -14,29 +19,12 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async validate(request: Request, payload: any) {
|
async validate(payload: any) {
|
||||||
const accessToken = request.headers.authorization?.split(' ')[1]
|
console.log(payload)
|
||||||
const refreshToken = request.cookies.refreshToken // Extract refresh token from cookies
|
const user = await this.userService.getUserById(payload.userId)
|
||||||
|
if (!user) {
|
||||||
// If there's no refresh token, simply validate the user based on payload
|
throw new UnauthorizedException()
|
||||||
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')
|
|
||||||
}
|
}
|
||||||
|
return user
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,10 +12,10 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async validate(email: string, password: string): Promise<any> {
|
async validate(email: string, password: string): Promise<any> {
|
||||||
const credentials = await this.authService.checkCredentials(email, password)
|
const newCredentials = await this.authService.checkCredentials(email, password)
|
||||||
if (credentials.resultCode === 1) {
|
if (newCredentials.resultCode === 1) {
|
||||||
throw new UnauthorizedException()
|
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 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
8
src/modules/users/entities/user.entity.ts
Normal file
8
src/modules/users/entities/user.entity.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { Prisma } from '@prisma/client'
|
||||||
|
|
||||||
|
export class User implements Prisma.UserUncheckedCreateInput {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
password: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
@@ -10,7 +10,8 @@ import { addHours } from 'date-fns'
|
|||||||
import { IUsersRepository } from '../services/users.service'
|
import { IUsersRepository } from '../services/users.service'
|
||||||
import { v4 as uuidv4 } from 'uuid'
|
import { v4 as uuidv4 } from 'uuid'
|
||||||
import { PrismaService } from '../../../prisma.service'
|
import { PrismaService } from '../../../prisma.service'
|
||||||
|
import { pick } from 'remeda'
|
||||||
|
import { Prisma } from '@prisma/client'
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class UsersRepository implements IUsersRepository {
|
export class UsersRepository implements IUsersRepository {
|
||||||
constructor(private prisma: PrismaService) {}
|
constructor(private prisma: PrismaService) {}
|
||||||
@@ -38,14 +39,8 @@ export class UsersRepository implements IUsersRepository {
|
|||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
|
|
||||||
console.log(users, 'usersFromBase')
|
|
||||||
const totalPages = Math.ceil(totalItems / itemsPerPage)
|
const totalPages = Math.ceil(totalItems / itemsPerPage)
|
||||||
const usersView = users.map(u => ({
|
const usersView = users.map(u => pick(u, ['id', 'name', 'email', 'isEmailVerified']))
|
||||||
id: u.id,
|
|
||||||
name: u.name,
|
|
||||||
email: u.email,
|
|
||||||
}))
|
|
||||||
console.log(usersView, 'users---')
|
|
||||||
return {
|
return {
|
||||||
totalPages,
|
totalPages,
|
||||||
currentPage,
|
currentPage,
|
||||||
@@ -56,6 +51,7 @@ export class UsersRepository implements IUsersRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createUser(newUser: CreateUserInput): Promise<User | null> {
|
async createUser(newUser: CreateUserInput): Promise<User | null> {
|
||||||
|
console.log(newUser)
|
||||||
return await this.prisma.user.create({
|
return await this.prisma.user.create({
|
||||||
data: {
|
data: {
|
||||||
email: newUser.email,
|
email: newUser.email,
|
||||||
@@ -88,13 +84,16 @@ export class UsersRepository implements IUsersRepository {
|
|||||||
return result.count > 0
|
return result.count > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
async findUserById(id: string): Promise<User | null> {
|
async findUserById(id: string, include?: Prisma.UserInclude) {
|
||||||
const user = await this.prisma.user.findUnique({ where: { id } })
|
const user = await this.prisma.user.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include,
|
||||||
|
})
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
return user
|
return user as Prisma.UserGetPayload<{ include: typeof include }>
|
||||||
}
|
}
|
||||||
|
|
||||||
async findUserByEmail(email: string): Promise<User | null> {
|
async findUserByEmail(email: string): Promise<User | null> {
|
||||||
|
|||||||
@@ -21,11 +21,12 @@ export class UsersService {
|
|||||||
|
|
||||||
async createUser(name: string, password: string, email: string): Promise<UserViewType | null> {
|
async createUser(name: string, password: string, email: string): Promise<UserViewType | null> {
|
||||||
const passwordHash = await this._generateHash(password)
|
const passwordHash = await this._generateHash(password)
|
||||||
|
const verificationToken = uuidv4()
|
||||||
const newUser: CreateUserInput = {
|
const newUser: CreateUserInput = {
|
||||||
name: name || email.split('@')[0],
|
name: name || email.split('@')[0],
|
||||||
email: email,
|
email: email,
|
||||||
password: passwordHash,
|
password: passwordHash,
|
||||||
verificationToken: uuidv4(),
|
verificationToken,
|
||||||
verificationTokenExpiry: addHours(new Date(), 24),
|
verificationTokenExpiry: addHours(new Date(), 24),
|
||||||
isEmailVerified: false,
|
isEmailVerified: false,
|
||||||
}
|
}
|
||||||
@@ -33,23 +34,32 @@ export class UsersService {
|
|||||||
if (!createdUser) {
|
if (!createdUser) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
try {
|
await this.sendConfirmationEmail({
|
||||||
await this.emailService.sendMail({
|
email: createdUser.email,
|
||||||
from: 'andrii <andrii@andrii.es>',
|
name: createdUser.name,
|
||||||
to: createdUser.email,
|
verificationToken: verificationToken,
|
||||||
text: 'hello and welcome',
|
|
||||||
subject: 'E-mail confirmation ',
|
|
||||||
})
|
})
|
||||||
} catch (e) {
|
|
||||||
console.log(e)
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
id: createdUser.id,
|
id: createdUser.id,
|
||||||
name: createdUser.name,
|
name: createdUser.name,
|
||||||
email: createdUser.email,
|
email: createdUser.email,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async resendConfirmationEmail(userId: string) {
|
||||||
|
const user = await this.usersRepository.findUserById(userId, { verification: true })
|
||||||
|
if (!user) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (user.isEmailVerified) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
await this.sendConfirmationEmail({
|
||||||
|
email: user.email,
|
||||||
|
name: user.name,
|
||||||
|
verificationToken: user.verification.verificationToken,
|
||||||
|
})
|
||||||
|
return true
|
||||||
|
}
|
||||||
async deleteUserById(id: string): Promise<boolean> {
|
async deleteUserById(id: string): Promise<boolean> {
|
||||||
return await this.usersRepository.deleteUserById(id)
|
return await this.usersRepository.deleteUserById(id)
|
||||||
}
|
}
|
||||||
@@ -70,7 +80,27 @@ export class UsersService {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private async sendConfirmationEmail({
|
||||||
|
email,
|
||||||
|
name,
|
||||||
|
verificationToken,
|
||||||
|
}: {
|
||||||
|
email: string
|
||||||
|
name: string
|
||||||
|
verificationToken: string
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
await this.emailService.sendMail({
|
||||||
|
from: 'andrii <andrii@andrii.es>',
|
||||||
|
to: email,
|
||||||
|
text: 'hello and welcome, token is: ' + verificationToken,
|
||||||
|
html: `<b>Hello ${name}!</b><br/>Please confirm your email by clicking on the link below:<br/><a href="http://localhost:3000/confirm-email/${verificationToken}">Confirm email</a>`,
|
||||||
|
subject: 'E-mail confirmation ',
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
private async _generateHash(password: string) {
|
private async _generateHash(password: string) {
|
||||||
return await bcrypt.hash(password, 10)
|
return await bcrypt.hash(password, 10)
|
||||||
}
|
}
|
||||||
@@ -88,7 +118,7 @@ export interface IUsersRepository {
|
|||||||
|
|
||||||
deleteUserById(id: string): Promise<boolean>
|
deleteUserById(id: string): Promise<boolean>
|
||||||
|
|
||||||
findUserById(id: string): Promise<User | null>
|
// findUserById(id: string): Promise<User | null>
|
||||||
|
|
||||||
revokeToken(id: string, token: string): Promise<User | null>
|
revokeToken(id: string, token: string): Promise<User | null>
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user