mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-17 20:59:27 +00:00
add email account validation
This commit is contained in:
@@ -11,93 +11,96 @@ import {
|
||||
BadRequestException,
|
||||
Res,
|
||||
HttpCode,
|
||||
} 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';
|
||||
} 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'
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
private readonly usersService: UsersService,
|
||||
private readonly usersService: UsersService
|
||||
) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('me')
|
||||
async getUserData(@Request() req) {
|
||||
const userId = req.user.userId;
|
||||
const user = await this.usersService.getUserById(userId);
|
||||
const userId = req.user.userId
|
||||
const user = await this.usersService.getUserById(userId)
|
||||
|
||||
if (!user) throw new UnauthorizedException();
|
||||
if (!user) throw new UnauthorizedException()
|
||||
|
||||
return {
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
is: user.id,
|
||||
};
|
||||
id: user.id,
|
||||
}
|
||||
}
|
||||
|
||||
@HttpCode(200)
|
||||
@UseGuards(LocalAuthGuard)
|
||||
@Post('login')
|
||||
@Post('sign-in')
|
||||
async login(@Request() req, @Res({ passthrough: true }) res) {
|
||||
const userData = req.user.data;
|
||||
console.log(req)
|
||||
const userData = req.user.data
|
||||
res.cookie('refreshToken', userData.refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
});
|
||||
return { accessToken: req.user.data.accessToken };
|
||||
})
|
||||
return { accessToken: req.user.data.accessToken }
|
||||
}
|
||||
|
||||
@HttpCode(201)
|
||||
@Post('registration')
|
||||
@Post('sign-up')
|
||||
async registration(@Body() registrationData: RegistrationDto) {
|
||||
return await this.usersService.createUser(
|
||||
registrationData.name,
|
||||
registrationData.password,
|
||||
registrationData.email,
|
||||
);
|
||||
registrationData.email
|
||||
)
|
||||
}
|
||||
|
||||
@Post('registration-confirmation')
|
||||
async confirmRegistration(@Body('code') confirmationCode) {
|
||||
const result = await this.authService.confirmEmail(confirmationCode);
|
||||
const result = await this.authService.confirmEmail(confirmationCode)
|
||||
if (!result) {
|
||||
throw new NotFoundException();
|
||||
throw new NotFoundException()
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
@Post('registration-email-resending')
|
||||
async resendRegistrationEmail(@Body('email') email: string) {
|
||||
const isResented = await this.authService.resendCode(email);
|
||||
const isResented = await this.authService.resendCode(email)
|
||||
if (!isResented)
|
||||
throw new BadRequestException({
|
||||
message: 'email already confirmed or such email not found',
|
||||
field: 'email',
|
||||
});
|
||||
return null;
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('logout')
|
||||
async logout(@Request() req) {
|
||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException();
|
||||
await this.usersService.addRevokedToken(req.cookie.refreshToken);
|
||||
return null;
|
||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException()
|
||||
await this.usersService.addRevokedToken(req.cookie.refreshToken)
|
||||
return null
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('refresh-token')
|
||||
async refreshToken(@Request() req, @Response() res) {
|
||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException();
|
||||
const userId = req.user.id;
|
||||
const newTokens = this.authService.createJwtTokensPair(userId, null);
|
||||
if (!req.cookie?.refreshToken) throw new UnauthorizedException()
|
||||
const userId = req.user.id
|
||||
const newTokens = this.authService.createJwtTokensPair(userId, null)
|
||||
res.cookie('refreshToken', newTokens.refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
});
|
||||
return { accessToken: newTokens.accessToken };
|
||||
})
|
||||
return { accessToken: newTokens.accessToken }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { LocalStrategy } from './strategies/local.strategy';
|
||||
import { Module } from '@nestjs/common'
|
||||
import { AuthService } from './auth.service'
|
||||
import { AuthController } from './auth.controller'
|
||||
import { UsersModule } from '../users/users.module'
|
||||
import { LocalStrategy } from './strategies/local.strategy'
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule],
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { isAfter } from 'date-fns';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { UsersRepository } from '../users/infrastructure/users.repository';
|
||||
import * as process from 'process';
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import { isAfter } from 'date-fns'
|
||||
import * as jwt from 'jsonwebtoken'
|
||||
import * as bcrypt from 'bcrypt'
|
||||
import { UsersRepository } from '../users/infrastructure/users.repository'
|
||||
import * as process from 'process'
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(private usersRepository: UsersRepository) {}
|
||||
|
||||
createJwtTokensPair(userId: string, email: string | null) {
|
||||
const accessSecretKey = process.env.ACCESS_JWT_SECRET_KEY;
|
||||
const refreshSecretKey = process.env.REFRESH_JWT_SECRET_KEY;
|
||||
const accessSecretKey = process.env.ACCESS_JWT_SECRET_KEY
|
||||
const refreshSecretKey = process.env.REFRESH_JWT_SECRET_KEY
|
||||
const payload: { userId: string; date: Date; email: string | null } = {
|
||||
userId,
|
||||
date: new Date(),
|
||||
email,
|
||||
};
|
||||
const accessToken = jwt.sign(payload, accessSecretKey, { expiresIn: '1d' });
|
||||
}
|
||||
const accessToken = jwt.sign(payload, accessSecretKey, { expiresIn: '1d' })
|
||||
const refreshToken = jwt.sign(payload, refreshSecretKey, {
|
||||
expiresIn: '30d',
|
||||
});
|
||||
})
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async checkCredentials(email: string, password: string) {
|
||||
const user = await this.usersRepository.findUserByEmail(email);
|
||||
const user = await this.usersRepository.findUserByEmail(email)
|
||||
if (!user /*|| !user.emailConfirmation.isConfirmed*/)
|
||||
return {
|
||||
resultCode: 1,
|
||||
@@ -36,11 +36,8 @@ export class AuthService {
|
||||
accessToken: null,
|
||||
refreshToken: null,
|
||||
},
|
||||
};
|
||||
const isPasswordValid = await this.isPasswordCorrect(
|
||||
password,
|
||||
user.password,
|
||||
);
|
||||
}
|
||||
const isPasswordValid = await this.isPasswordCorrect(password, user.password)
|
||||
if (!isPasswordValid) {
|
||||
return {
|
||||
resultCode: 1,
|
||||
@@ -50,39 +47,37 @@ export class AuthService {
|
||||
refreshToken: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const tokensPair = this.createJwtTokensPair(user.id, user.email);
|
||||
const tokensPair = this.createJwtTokensPair(user.id, user.email)
|
||||
return {
|
||||
resultCode: 0,
|
||||
data: tokensPair,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async isPasswordCorrect(password: string, hash: string) {
|
||||
return bcrypt.compare(password, hash);
|
||||
return bcrypt.compare(password, hash)
|
||||
}
|
||||
|
||||
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 user = await this.usersRepository.findUserByVerificationToken(token)
|
||||
if (!user || user.isEmailVerified) return false
|
||||
const dbToken = user.verificationToken
|
||||
const isTokenExpired = isAfter(user.verificationTokenExpiry, new Date())
|
||||
if (dbToken !== token || isTokenExpired) {
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
|
||||
return await this.usersRepository.updateConfirmation(user.id);
|
||||
return await this.usersRepository.updateConfirmation(user.id)
|
||||
}
|
||||
|
||||
async resendCode(email: string) {
|
||||
const user = await this.usersRepository.findUserByEmail(email);
|
||||
if (!user || user?.verification.isEmailVerified) return null;
|
||||
const updatedUser = await this.usersRepository.updateVerificationToken(
|
||||
user.id,
|
||||
);
|
||||
if (!updatedUser) return null;
|
||||
const user = await this.usersRepository.findUserByEmail(email)
|
||||
if (!user || user?.verification.isEmailVerified) return null
|
||||
const updatedUser = await this.usersRepository.updateVerificationToken(user.id)
|
||||
if (!updatedUser) return null
|
||||
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { IsEmail, Length } from 'class-validator';
|
||||
import { IsEmail, Length } from 'class-validator'
|
||||
|
||||
export class RegistrationDto {
|
||||
@Length(3, 30)
|
||||
name: string;
|
||||
name: string
|
||||
@Length(3, 30)
|
||||
password: string;
|
||||
password: string
|
||||
@IsEmail()
|
||||
email: string;
|
||||
email: string
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { RegistrationDto } from './registration.dto';
|
||||
import { PartialType } from '@nestjs/mapped-types'
|
||||
import { RegistrationDto } from './registration.dto'
|
||||
|
||||
export class UpdateAuthDto extends PartialType(RegistrationDto) {}
|
||||
|
||||
@@ -5,48 +5,48 @@ import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import { UsersRepository } from '../../users/infrastructure/users.repository';
|
||||
} from '@nestjs/common'
|
||||
import * as jwt from 'jsonwebtoken'
|
||||
import { UsersRepository } from '../../users/infrastructure/users.repository'
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly usersRepository: UsersRepository) {}
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const request = context.switchToHttp().getRequest()
|
||||
if (!request.headers || !request.headers.authorization) {
|
||||
throw new BadRequestException([{ message: 'No any auth headers' }]);
|
||||
throw new BadRequestException([{ message: 'No any auth headers' }])
|
||||
}
|
||||
const authorizationData = request.headers.authorization.split(' ');
|
||||
const token = authorizationData[1];
|
||||
const tokenName = authorizationData[0];
|
||||
const authorizationData = request.headers.authorization.split(' ')
|
||||
const token = authorizationData[1]
|
||||
const tokenName = authorizationData[0]
|
||||
if (tokenName != 'Bearer') {
|
||||
throw new UnauthorizedException([
|
||||
{
|
||||
message: 'login or password invalid',
|
||||
},
|
||||
]);
|
||||
])
|
||||
}
|
||||
try {
|
||||
const secretKey = process.env.JWT_SECRET_KEY;
|
||||
const decoded: any = jwt.verify(token, secretKey!);
|
||||
const user = await this.usersRepository.findUserById(decoded.userId);
|
||||
const secretKey = process.env.JWT_SECRET_KEY
|
||||
const decoded: any = jwt.verify(token, secretKey!)
|
||||
const user = await this.usersRepository.findUserById(decoded.userId)
|
||||
if (!user) {
|
||||
throw new NotFoundException([
|
||||
{
|
||||
field: 'token',
|
||||
message: 'user not found',
|
||||
},
|
||||
]);
|
||||
])
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
console.log(e)
|
||||
throw new UnauthorizedException([
|
||||
{
|
||||
message: 'login or password invalid',
|
||||
},
|
||||
]);
|
||||
])
|
||||
}
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,22 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'
|
||||
import { Observable } from 'rxjs'
|
||||
|
||||
@Injectable()
|
||||
export class BaseAuthGuard implements CanActivate {
|
||||
canActivate(
|
||||
context: ExecutionContext,
|
||||
): boolean | Promise<boolean> | Observable<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const exceptedAuthInput = 'Basic YWRtaW46cXdlcnR5';
|
||||
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
|
||||
const request = context.switchToHttp().getRequest()
|
||||
const exceptedAuthInput = 'Basic YWRtaW46cXdlcnR5'
|
||||
if (!request.headers || !request.headers.authorization) {
|
||||
throw new UnauthorizedException([{ message: 'No any auth headers' }]);
|
||||
throw new UnauthorizedException([{ message: 'No any auth headers' }])
|
||||
} else {
|
||||
if (request.headers.authorization != exceptedAuthInput) {
|
||||
throw new UnauthorizedException([
|
||||
{
|
||||
message: 'login or password invalid',
|
||||
},
|
||||
]);
|
||||
])
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
import {
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UsePipes,
|
||||
ValidationPipe,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { ExecutionContext, Injectable, UsePipes, ValidationPipe } from '@nestjs/common'
|
||||
import { AuthGuard } from '@nestjs/passport'
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
constructor() {
|
||||
super();
|
||||
super()
|
||||
}
|
||||
|
||||
@UsePipes(new ValidationPipe())
|
||||
validateLoginDto(): void {}
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
|
||||
const res: boolean = await (super.canActivate(context) as Promise<boolean>);
|
||||
if (!res) return false;
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest()
|
||||
|
||||
const res: boolean = await (super.canActivate(context) as Promise<boolean>)
|
||||
if (!res) return false
|
||||
|
||||
// check DTO
|
||||
return res;
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import { AuthGuard } from '@nestjs/passport'
|
||||
|
||||
@Injectable()
|
||||
export class LocalAuthGuard extends AuthGuard('local') {}
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { AppSettings } from '../../../settings/app-settings';
|
||||
import { Inject, Injectable } from '@nestjs/common'
|
||||
import { PassportStrategy } from '@nestjs/passport'
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt'
|
||||
import { AppSettings } from '../../../settings/app-settings'
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(
|
||||
@Inject(AppSettings.name) private readonly appSettings: AppSettings,
|
||||
) {
|
||||
constructor(@Inject(AppSettings.name) private readonly appSettings: AppSettings) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: true,
|
||||
secretOrKey: appSettings.auth.ACCESS_JWT_SECRET_KEY,
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
return { userId: payload.userId };
|
||||
return { userId: payload.userId }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { Strategy } from 'passport-local';
|
||||
import { AuthService } from '../auth.service';
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common'
|
||||
import { PassportStrategy } from '@nestjs/passport'
|
||||
import { Strategy } from 'passport-local'
|
||||
import { AuthService } from '../auth.service'
|
||||
|
||||
@Injectable()
|
||||
export class LocalStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(private readonly authService: AuthService) {
|
||||
super({
|
||||
usernameField: 'login',
|
||||
});
|
||||
usernameField: 'email',
|
||||
})
|
||||
}
|
||||
|
||||
async validate(login: string, password: string): Promise<any> {
|
||||
const user = await this.authService.checkCredentials(login, password);
|
||||
async validate(email: string, password: string): Promise<any> {
|
||||
const user = await this.authService.checkCredentials(email, password)
|
||||
if (user.resultCode === 1) {
|
||||
throw new UnauthorizedException();
|
||||
throw new UnauthorizedException()
|
||||
}
|
||||
return user;
|
||||
return user
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,25 @@
|
||||
import { IEvent } from '@nestjs/cqrs';
|
||||
import { IEvent } from '@nestjs/cqrs'
|
||||
|
||||
export class ResultNotification<T = null> {
|
||||
constructor(data: T | null = null) {
|
||||
this.data = data;
|
||||
this.data = data
|
||||
}
|
||||
|
||||
extensions: NotificationExtension[] = [];
|
||||
code = 0;
|
||||
data: T | null = null;
|
||||
extensions: NotificationExtension[] = []
|
||||
code = 0
|
||||
data: T | null = null
|
||||
|
||||
hasError() {
|
||||
return this.code !== 0;
|
||||
return this.code !== 0
|
||||
}
|
||||
|
||||
addError(
|
||||
message: string,
|
||||
key: string | null = null,
|
||||
code: number | null = null,
|
||||
) {
|
||||
this.code = code ?? 1;
|
||||
this.extensions.push(new NotificationExtension(message, key));
|
||||
addError(message: string, key: string | null = null, code: number | null = null) {
|
||||
this.code = code ?? 1
|
||||
this.extensions.push(new NotificationExtension(message, key))
|
||||
}
|
||||
|
||||
addData(data: T) {
|
||||
this.data = data;
|
||||
this.data = data
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,39 +27,34 @@ export class NotificationExtension {
|
||||
constructor(public message: string, public key: string | null) {}
|
||||
}
|
||||
|
||||
export class DomainResultNotification<
|
||||
TData = null,
|
||||
> extends ResultNotification<TData> {
|
||||
public events: IEvent[] = [];
|
||||
export class DomainResultNotification<TData = null> extends ResultNotification<TData> {
|
||||
public events: IEvent[] = []
|
||||
addEvents(...events: IEvent[]) {
|
||||
this.events = [...this.events, ...events];
|
||||
this.events = [...this.events, ...events]
|
||||
}
|
||||
|
||||
static create<T>(
|
||||
mainNotification: DomainResultNotification<T>,
|
||||
...otherNotifications: DomainResultNotification[]
|
||||
) {
|
||||
const domainResultNotification = new DomainResultNotification<T>();
|
||||
const domainResultNotification = new DomainResultNotification<T>()
|
||||
|
||||
if (!!mainNotification.data) {
|
||||
domainResultNotification.addData(mainNotification.data);
|
||||
domainResultNotification.addData(mainNotification.data)
|
||||
}
|
||||
domainResultNotification.events = mainNotification.events;
|
||||
domainResultNotification.events = mainNotification.events
|
||||
|
||||
mainNotification.extensions.forEach((e) => {
|
||||
domainResultNotification.addError(e.message, e.key);
|
||||
});
|
||||
mainNotification.extensions.forEach(e => {
|
||||
domainResultNotification.addError(e.message, e.key)
|
||||
})
|
||||
|
||||
otherNotifications.forEach((n) => {
|
||||
domainResultNotification.events = [
|
||||
...domainResultNotification.events,
|
||||
...n.events,
|
||||
];
|
||||
n.extensions.forEach((e) => {
|
||||
domainResultNotification.addError(e.message, e.key);
|
||||
});
|
||||
});
|
||||
otherNotifications.forEach(n => {
|
||||
domainResultNotification.events = [...domainResultNotification.events, ...n.events]
|
||||
n.extensions.forEach(e => {
|
||||
domainResultNotification.addError(e.message, e.key)
|
||||
})
|
||||
})
|
||||
|
||||
return domainResultNotification;
|
||||
return domainResultNotification
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,58 +1,50 @@
|
||||
import { DomainResultNotification, ResultNotification } from './notification';
|
||||
import { validateOrReject } from 'class-validator';
|
||||
import { IEvent } from '@nestjs/cqrs';
|
||||
import {
|
||||
validationErrorsMapper,
|
||||
ValidationPipeErrorType,
|
||||
} from '../../../settings/pipes-setup';
|
||||
import { DomainResultNotification, ResultNotification } from './notification'
|
||||
import { validateOrReject } from 'class-validator'
|
||||
import { IEvent } from '@nestjs/cqrs'
|
||||
import { validationErrorsMapper, ValidationPipeErrorType } from '../../../settings/pipes-setup'
|
||||
|
||||
export class DomainError extends Error {
|
||||
constructor(message: string, public resultNotification: ResultNotification) {
|
||||
super(message);
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export const validateEntityOrThrow = async (entity: any) => {
|
||||
try {
|
||||
await validateOrReject(entity);
|
||||
await validateOrReject(entity)
|
||||
} catch (errors) {
|
||||
const resultNotification: ResultNotification = mapErrorsToNotification(
|
||||
validationErrorsMapper.mapValidationErrorArrayToValidationPipeErrorTypeArray(
|
||||
errors,
|
||||
),
|
||||
);
|
||||
validationErrorsMapper.mapValidationErrorArrayToValidationPipeErrorTypeArray(errors)
|
||||
)
|
||||
|
||||
throw new DomainError('domain entity validation error', resultNotification);
|
||||
throw new DomainError('domain entity validation error', resultNotification)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const validateEntity = async <T extends object>(
|
||||
entity: T,
|
||||
events: IEvent[],
|
||||
events: IEvent[]
|
||||
): Promise<DomainResultNotification<T>> => {
|
||||
try {
|
||||
await validateOrReject(entity);
|
||||
await validateOrReject(entity)
|
||||
} catch (errors) {
|
||||
const resultNotification: DomainResultNotification<T> =
|
||||
mapErrorsToNotification<T>(
|
||||
validationErrorsMapper.mapValidationErrorArrayToValidationPipeErrorTypeArray(
|
||||
errors,
|
||||
),
|
||||
);
|
||||
resultNotification.addData(entity);
|
||||
resultNotification.addEvents(...events);
|
||||
return resultNotification;
|
||||
const resultNotification: DomainResultNotification<T> = mapErrorsToNotification<T>(
|
||||
validationErrorsMapper.mapValidationErrorArrayToValidationPipeErrorTypeArray(errors)
|
||||
)
|
||||
resultNotification.addData(entity)
|
||||
resultNotification.addEvents(...events)
|
||||
return resultNotification
|
||||
}
|
||||
const domainResultNotification = new DomainResultNotification<T>(entity);
|
||||
domainResultNotification.addEvents(...events);
|
||||
const domainResultNotification = new DomainResultNotification<T>(entity)
|
||||
domainResultNotification.addEvents(...events)
|
||||
|
||||
return domainResultNotification;
|
||||
};
|
||||
return domainResultNotification
|
||||
}
|
||||
|
||||
export function mapErrorsToNotification<T>(errors: ValidationPipeErrorType[]) {
|
||||
const resultNotification = new DomainResultNotification<T>();
|
||||
const resultNotification = new DomainResultNotification<T>()
|
||||
errors.forEach((item: ValidationPipeErrorType) =>
|
||||
resultNotification.addError(item.message, item.field, 1),
|
||||
);
|
||||
return resultNotification;
|
||||
resultNotification.addError(item.message, item.field, 1)
|
||||
)
|
||||
return resultNotification
|
||||
}
|
||||
|
||||
@@ -8,11 +8,11 @@ import {
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { UsersService } from '../services/users.service';
|
||||
import { CreateUserDto } from '../dto/create-user.dto';
|
||||
import { Pagination } from '../../../infrastructure/common/pagination.service';
|
||||
import { BaseAuthGuard } from '../../auth/guards/base-auth.guard';
|
||||
} from '@nestjs/common'
|
||||
import { UsersService } from '../services/users.service'
|
||||
import { CreateUserDto } from '../dto/create-user.dto'
|
||||
import { Pagination } from '../../../infrastructure/common/pagination.service'
|
||||
import { BaseAuthGuard } from '../../auth/guards/base-auth.guard'
|
||||
|
||||
@Controller('users')
|
||||
export class UsersController {
|
||||
@@ -20,28 +20,31 @@ export class UsersController {
|
||||
|
||||
@Get()
|
||||
async findAll(@Query() query) {
|
||||
const { page, pageSize, searchNameTerm } =
|
||||
Pagination.getPaginationData(query);
|
||||
const users = await this.usersService.getUsers(
|
||||
page,
|
||||
pageSize,
|
||||
searchNameTerm,
|
||||
);
|
||||
if (!users) throw new NotFoundException('Users not found');
|
||||
return users;
|
||||
const { page, pageSize, searchNameTerm, searchEmailTerm } = Pagination.getPaginationData(query)
|
||||
const users = await this.usersService.getUsers(page, pageSize, searchNameTerm, searchEmailTerm)
|
||||
if (!users) throw new NotFoundException('Users not found')
|
||||
return users
|
||||
}
|
||||
|
||||
//@UseGuards(BaseAuthGuard)
|
||||
@Post()
|
||||
async create(@Body() createUserDto: CreateUserDto) {
|
||||
return await this.usersService.createUser(
|
||||
createUserDto.login,
|
||||
createUserDto.password,
|
||||
createUserDto.email,
|
||||
);
|
||||
createUserDto.email
|
||||
)
|
||||
}
|
||||
|
||||
@UseGuards(BaseAuthGuard)
|
||||
@Delete(':id')
|
||||
async remove(@Param('id') id: string) {
|
||||
return await this.usersService.deleteUserById(id);
|
||||
return await this.usersService.deleteUserById(id)
|
||||
}
|
||||
|
||||
@UseGuards(BaseAuthGuard)
|
||||
@Delete()
|
||||
async removeAll() {
|
||||
return await this.usersService.deleteAllUsers()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Length, Matches } from 'class-validator';
|
||||
import { Length, Matches } from 'class-validator'
|
||||
|
||||
export class CreateUserDto {
|
||||
@Length(3, 10)
|
||||
login: string;
|
||||
login: string
|
||||
@Length(6, 20)
|
||||
password: string;
|
||||
password: string
|
||||
@Matches(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/)
|
||||
email: string;
|
||||
email: string
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateUserDto } from './create-user.dto';
|
||||
import { PartialType } from '@nestjs/mapped-types'
|
||||
import { CreateUserDto } from './create-user.dto'
|
||||
|
||||
export class UpdateUserDto extends PartialType(CreateUserDto) {}
|
||||
|
||||
@@ -4,12 +4,12 @@ import {
|
||||
User,
|
||||
UserViewType,
|
||||
VerificationWithUser,
|
||||
} from '../../../types/types';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { addHours } from 'date-fns';
|
||||
import { IUsersRepository } from '../services/users.service';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../../../prisma.service';
|
||||
} from '../../../types/types'
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import { addHours } from 'date-fns'
|
||||
import { IUsersRepository } from '../services/users.service'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { PrismaService } from '../../../prisma.service'
|
||||
|
||||
@Injectable()
|
||||
export class UsersRepository implements IUsersRepository {
|
||||
@@ -19,12 +19,16 @@ export class UsersRepository implements IUsersRepository {
|
||||
currentPage: number,
|
||||
itemsPerPage: number,
|
||||
searchNameTerm: string,
|
||||
searchEmailTerm: string
|
||||
): Promise<EntityWithPaginationType<UserViewType>> {
|
||||
const where = {
|
||||
name: {
|
||||
search: searchNameTerm,
|
||||
search: searchNameTerm || undefined,
|
||||
},
|
||||
};
|
||||
email: {
|
||||
search: searchEmailTerm || undefined,
|
||||
},
|
||||
}
|
||||
const [totalItems, users] = await this.prisma.$transaction([
|
||||
this.prisma.user.count({ where }),
|
||||
this.prisma.user.findMany({
|
||||
@@ -32,23 +36,23 @@ export class UsersRepository implements IUsersRepository {
|
||||
skip: (currentPage - 1) * itemsPerPage,
|
||||
take: itemsPerPage,
|
||||
}),
|
||||
]);
|
||||
])
|
||||
|
||||
console.log(users, 'usersFromBase');
|
||||
const totalPages = Math.ceil(totalItems / itemsPerPage);
|
||||
const usersView = users.map((u) => ({
|
||||
console.log(users, 'usersFromBase')
|
||||
const totalPages = Math.ceil(totalItems / itemsPerPage)
|
||||
const usersView = users.map(u => ({
|
||||
id: u.id,
|
||||
name: u.name,
|
||||
email: u.email,
|
||||
}));
|
||||
console.log(usersView, 'users---');
|
||||
}))
|
||||
console.log(usersView, 'users---')
|
||||
return {
|
||||
totalPages,
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
totalItems,
|
||||
items: usersView,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createUser(newUser: CreateUserInput): Promise<User | null> {
|
||||
@@ -67,7 +71,7 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
verification: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async deleteUserById(id: string): Promise<boolean> {
|
||||
@@ -75,34 +79,37 @@ export class UsersRepository implements IUsersRepository {
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
return result.isDeleted;
|
||||
})
|
||||
return result.isDeleted
|
||||
}
|
||||
|
||||
async deleteAllUsers(): Promise<boolean> {
|
||||
const result = await this.prisma.user.deleteMany()
|
||||
return result.count > 0
|
||||
}
|
||||
|
||||
async findUserById(id: string): Promise<User | null> {
|
||||
const user = await this.prisma.user.findUnique({ where: { id } });
|
||||
const user = await this.prisma.user.findUnique({ where: { id } })
|
||||
if (!user) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
return user;
|
||||
return user
|
||||
}
|
||||
|
||||
async findUserByEmail(email: string): Promise<User | null> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { email },
|
||||
include: { verification: true },
|
||||
});
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
return user;
|
||||
return user
|
||||
}
|
||||
|
||||
async findUserByVerificationToken(
|
||||
token: string,
|
||||
): Promise<VerificationWithUser | null> {
|
||||
async findUserByVerificationToken(token: string): Promise<VerificationWithUser | null> {
|
||||
const verification = await this.prisma.verification.findUnique({
|
||||
where: {
|
||||
verificationToken: token,
|
||||
@@ -110,11 +117,11 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
if (!verification) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
return verification;
|
||||
return verification
|
||||
}
|
||||
|
||||
async updateConfirmation(id: string) {
|
||||
@@ -125,8 +132,8 @@ export class UsersRepository implements IUsersRepository {
|
||||
data: {
|
||||
isEmailVerified: true,
|
||||
},
|
||||
});
|
||||
return result.isEmailVerified;
|
||||
})
|
||||
return result.isEmailVerified
|
||||
}
|
||||
|
||||
async updateVerificationToken(id: string) {
|
||||
@@ -141,7 +148,7 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async revokeToken(id: string, token: string): Promise<User | null> {
|
||||
@@ -155,10 +162,10 @@ export class UsersRepository implements IUsersRepository {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
})
|
||||
if (!revokedToken.user) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
return revokedToken.user;
|
||||
return revokedToken.user
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,26 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import {
|
||||
CreateUserInput,
|
||||
EntityWithPaginationType,
|
||||
User,
|
||||
UserViewType,
|
||||
} from '../../../types/types';
|
||||
import { addHours } from 'date-fns';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { UsersRepository } from '../infrastructure/users.repository';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { CreateUserInput, EntityWithPaginationType, User, UserViewType } from '../../../types/types'
|
||||
import { addHours } from 'date-fns'
|
||||
import { Injectable } from '@nestjs/common'
|
||||
import jwt from 'jsonwebtoken'
|
||||
import { UsersRepository } from '../infrastructure/users.repository'
|
||||
import * as bcrypt from 'bcrypt'
|
||||
import { MailerService } from '@nestjs-modules/mailer'
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private usersRepository: UsersRepository) {}
|
||||
constructor(private usersRepository: UsersRepository, private emailService: MailerService) {}
|
||||
|
||||
async getUsers(page: number, pageSize: number, searchNameTerm: string) {
|
||||
return await this.usersRepository.getUsers(page, pageSize, searchNameTerm);
|
||||
async getUsers(page: number, pageSize: number, searchNameTerm: string, searchEmailTerm: string) {
|
||||
return await this.usersRepository.getUsers(page, pageSize, searchNameTerm, searchEmailTerm)
|
||||
}
|
||||
|
||||
async getUserById(id: string) {
|
||||
return await this.usersRepository.findUserById(id);
|
||||
return await this.usersRepository.findUserById(id)
|
||||
}
|
||||
|
||||
async createUser(
|
||||
name: string,
|
||||
password: string,
|
||||
email: string,
|
||||
): Promise<UserViewType | null> {
|
||||
const passwordHash = await this._generateHash(password);
|
||||
async createUser(name: string, password: string, email: string): Promise<UserViewType | null> {
|
||||
const passwordHash = await this._generateHash(password)
|
||||
const newUser: CreateUserInput = {
|
||||
name: name || email.split('@')[0],
|
||||
email: email,
|
||||
@@ -36,37 +28,51 @@ export class UsersService {
|
||||
verificationToken: uuidv4(),
|
||||
verificationTokenExpiry: addHours(new Date(), 24),
|
||||
isEmailVerified: false,
|
||||
};
|
||||
const createdUser = await this.usersRepository.createUser(newUser);
|
||||
if (!createdUser) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const createdUser = await this.usersRepository.createUser(newUser)
|
||||
if (!createdUser) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
await this.emailService.sendMail({
|
||||
from: 'andrii <andrii@andrii.es>',
|
||||
to: createdUser.email,
|
||||
text: 'hello and welcome',
|
||||
subject: 'E-mail confirmation ',
|
||||
})
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
return {
|
||||
id: createdUser.id,
|
||||
name: createdUser.name,
|
||||
email: createdUser.email,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async deleteUserById(id: string): Promise<boolean> {
|
||||
return await this.usersRepository.deleteUserById(id);
|
||||
return await this.usersRepository.deleteUserById(id)
|
||||
}
|
||||
|
||||
async deleteAllUsers(): Promise<boolean> {
|
||||
return await this.usersRepository.deleteAllUsers()
|
||||
}
|
||||
|
||||
async addRevokedToken(token: string) {
|
||||
const secretKey = process.env.JWT_SECRET_KEY;
|
||||
if (!secretKey) throw new Error('JWT_SECRET_KEY is not defined');
|
||||
const secretKey = process.env.JWT_SECRET_KEY
|
||||
if (!secretKey) throw new Error('JWT_SECRET_KEY is not defined')
|
||||
|
||||
try {
|
||||
const decoded: any = jwt.verify(token, secretKey);
|
||||
return this.usersRepository.revokeToken(decoded.userId, token);
|
||||
const decoded: any = jwt.verify(token, secretKey)
|
||||
return this.usersRepository.revokeToken(decoded.userId, token)
|
||||
} catch (e) {
|
||||
console.log('Decoding error: e');
|
||||
return null;
|
||||
console.log(`Decoding error: ${e}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private async _generateHash(password: string) {
|
||||
return await bcrypt.hash(password, 10);
|
||||
return await bcrypt.hash(password, 10)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +81,14 @@ export interface IUsersRepository {
|
||||
page: number,
|
||||
pageSize: number,
|
||||
searchNameTerm: string,
|
||||
): Promise<EntityWithPaginationType<UserViewType>>;
|
||||
searchEmailTerm: string
|
||||
): Promise<EntityWithPaginationType<UserViewType>>
|
||||
|
||||
createUser(newUser: CreateUserInput): Promise<User | null>;
|
||||
createUser(newUser: CreateUserInput): Promise<User | null>
|
||||
|
||||
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>
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersService } from './services/users.service';
|
||||
import { UsersController } from './api/users.controller';
|
||||
import { UsersRepository } from './infrastructure/users.repository';
|
||||
import { Module } from '@nestjs/common'
|
||||
import { UsersService } from './services/users.service'
|
||||
import { UsersController } from './api/users.controller'
|
||||
import { UsersRepository } from './infrastructure/users.repository'
|
||||
|
||||
@Module({
|
||||
controllers: [UsersController],
|
||||
|
||||
Reference in New Issue
Block a user