This commit is contained in:
2023-06-12 20:01:07 +02:00
parent edc42e3750
commit 59b4eb582e
43 changed files with 1799 additions and 245 deletions

View File

@@ -9,7 +9,7 @@
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
@@ -21,15 +21,29 @@
},
"dependencies": {
"@nestjs/common": "9.4.1",
"@nestjs/config": "^2.3.3",
"@nestjs/core": "9.4.1",
"@nestjs/cqrs": "^9.0.4",
"@nestjs/mapped-types": "*",
"@nestjs/passport": "^9.0.3",
"@nestjs/platform-express": "^9.4.1",
"@nestjs/platform-fastify": "^9.4.1",
"@prisma/client": "^4.14.1",
"@nestjs/schedule": "^2.2.3",
"@nestjs/swagger": "^6.3.0",
"@prisma/client": "^4.15.0",
"bcrypt": "^5.1.0",
"class-transformer": "0.3.1",
"class-validator": "^0.14.0",
"cookie-parser": "^1.4.6",
"date-fns": "^2.30.0",
"dotenv": "^16.1.4",
"jsonwebtoken": "^9.0.0",
"nodemailer": "^6.9.3",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1"
"rxjs": "^7.8.1",
"uuid": "^9.0.0"
},
"devDependencies": {
"@nestjs/cli": "^9.5.0",
@@ -46,7 +60,7 @@
"eslint-plugin-prettier": "^4.2.1",
"jest": "29.5.0",
"prettier": "^2.8.8",
"prisma": "^4.14.1",
"prisma": "^4.15.0",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "29.1.0",

537
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,6 +6,19 @@ datasource db {
generator client {
provider = "prisma-client-js"
previewFeatures = ["fullTextSearch", "fullTextIndex"]
}
model Verification {
id String @id @default(cuid())
userId String @unique
isEmailVerified Boolean @default(false)
verificationToken String? @unique @default(uuid())
verificationTokenExpiry DateTime?
verificationEmailsSent Int @default(0)
user User @relation(fields: [userId], references: [id])
@@index([userId])
}
model User {
@@ -14,17 +27,41 @@ model User {
password String
isAdmin Boolean @default(false)
name String @db.VarChar(40)
isVerified Boolean @default(false)
avatar String?
deckCount Int @default(0)
isDeleted Boolean? @default(false)
deleteTime Int?
created DateTime @default(now())
updated DateTime @updatedAt
cards Card[] // One-to-many relation
decks Deck[] // One-to-many relation
grades Grade[] // One-to-many relation
generalChatMessages GeneralChatMessage[] // One-to-many relation
cards Card[]
decks Deck[]
grades Grade[]
generalChatMessages GeneralChatMessage[]
verification Verification?
AccessToken AccessToken[]
RefreshToken RefreshToken[]
}
model AccessToken {
id String @id @default(cuid())
userId String
token String @unique
expiresAt DateTime
isRevoked Boolean @default(false)
user User @relation(fields: [userId], references: [id])
@@index([userId])
}
model RefreshToken {
id String @id @default(cuid())
userId String
token String @unique
expiresAt DateTime
isRevoked Boolean @default(false)
user User @relation(fields: [userId], references: [id])
@@index([userId])
}
model Card {

View File

@@ -1,22 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@@ -1,12 +0,0 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@@ -1,12 +1,20 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
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 { AuthModule } from './modules/auth/auth.module';
import { UsersModule } from './modules/users/users.module';
import { PrismaModule } from './prisma.module';
@Module({
imports: [UsersModule, PrismaModule],
controllers: [AppController],
providers: [AppService],
imports: [ConfigModule, AuthModule, UsersModule, PrismaModule],
controllers: [],
providers: [
JwtStrategy,
JwtPayloadExtractorStrategy,
JwtPayloadExtractorGuard,
],
exports: [],
})
export class AppModule {}

37
src/exception.filter.ts Normal file
View File

@@ -0,0 +1,37 @@
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
if (status === 400) {
const errorsResponse = {
errorsMessages: [],
};
const responseBody: any = exception.getResponse();
if (typeof responseBody.message === 'object') {
responseBody.message.forEach((e) =>
errorsResponse.errorsMessages.push(e),
);
} else {
errorsResponse.errorsMessages.push(responseBody.message);
}
response.status(status).json(errorsResponse);
} else {
response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
}

View File

@@ -0,0 +1,24 @@
import {
BadRequestException,
CanActivate,
ExecutionContext,
} from '@nestjs/common';
import { UsersRepository } from '../../modules/users/infrastructure/users.repository';
export class LimitsControlGuard implements CanActivate {
constructor(private usersRepository: UsersRepository) {}
async canActivate(context: ExecutionContext): Promise<boolean> | null {
const request = context.switchToHttp().getRequest();
const email = request.body.email;
const userWithExistingEmail = await this.usersRepository.findUserByEmail(
email,
);
if (userWithExistingEmail)
throw new BadRequestException({
message: 'email already exist',
field: 'email',
});
return true;
}
}

View File

@@ -0,0 +1,23 @@
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.
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;
}
}

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';
@Injectable()
export class JwtPayloadExtractorStrategy extends PassportStrategy(
Strategy,
'payloadExtractor',
) {
constructor(
@Inject(AppSettings.name) private readonly appSettings: AppSettings,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: appSettings.auth.ACCESS_JWT_SECRET_KEY,
});
}
async validate(payload: any) {
const userId = payload.userId;
const login = payload.login;
if (payload) return { userId, login };
return null;
}
}

View File

@@ -0,0 +1,9 @@
export class Pagination {
static getPaginationData(query) {
const page = typeof query.PageNumber === 'string' ? +query.PageNumber : 1;
const pageSize = typeof query.PageSize === 'string' ? +query.PageSize : 10;
const searchNameTerm =
typeof query.SearchNameTerm === 'string' ? query.SearchNameTerm : '';
return { page, pageSize, searchNameTerm };
}
}

View File

@@ -1,18 +1,38 @@
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { HttpExceptionFilter } from './exception.filter';
import * as cookieParser from 'cookie-parser';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ logger: true }),
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Flashcards')
.setDescription('The config API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
app.useGlobalPipes(
new ValidationPipe({
stopAtFirstError: false,
exceptionFactory: (errors) => {
const customErrors = errors.map((e) => {
const firstError = JSON.stringify(e.constraints);
return { field: e.property, message: firstError };
});
throw new BadRequestException(customErrors);
},
}),
);
app.useGlobalPipes(new ValidationPipe({}));
await app.listen(3000, '0.0.0.0');
app.useGlobalFilters(new HttpExceptionFilter());
app.use(cookieParser());
await app.listen(process.env.PORT || 3000);
}
try {
bootstrap();
} catch (e) {
console.log('BOOTSTRAP CALL FAILED');
console.log('ERROR: ');
console.log(e);
}
void bootstrap();

View File

@@ -0,0 +1,103 @@
import {
Controller,
Get,
Post,
Body,
UseGuards,
Request,
Response,
NotFoundException,
UnauthorizedException,
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';
@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly usersService: UsersService,
) {}
@UseGuards(JwtAuthGuard)
@Get('me')
async getUserData(@Request() req) {
const userId = req.user.userId;
const user = await this.usersService.getUserById(userId);
if (!user) throw new UnauthorizedException();
return {
email: user.email,
name: user.name,
is: user.id,
};
}
@HttpCode(200)
@UseGuards(LocalAuthGuard)
@Post('login')
async login(@Request() req, @Res({ passthrough: true }) res) {
const userData = req.user.data;
res.cookie('refreshToken', userData.refreshToken, {
httpOnly: true,
secure: true,
});
return { accessToken: req.user.data.accessToken };
}
@HttpCode(201)
@Post('registration')
async registration(@Body() registrationData: RegistrationDto) {
return await this.usersService.createUser(
registrationData.name,
registrationData.password,
registrationData.email,
);
}
@Post('registration-confirmation')
async confirmRegistration(@Body('code') confirmationCode) {
const result = await this.authService.confirmEmail(confirmationCode);
if (!result) {
throw new NotFoundException();
}
return null;
}
@Post('registration-email-resending')
async resendRegistrationEmail(@Body('email') email: string) {
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;
}
@UseGuards(JwtAuthGuard)
@Post('logout')
async logout(@Request() req) {
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);
res.cookie('refreshToken', newTokens.refreshToken, {
httpOnly: true,
secure: true,
});
return { accessToken: newTokens.accessToken };
}
}

View File

@@ -0,0 +1,12 @@
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],
controllers: [AuthController],
providers: [AuthService, LocalStrategy],
})
export class AuthModule {}

View File

@@ -0,0 +1,88 @@
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 payload: { userId: string; date: Date; email: string | null } = {
userId,
date: new Date(),
email,
};
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);
if (!user /*|| !user.emailConfirmation.isConfirmed*/)
return {
resultCode: 1,
data: {
accessToken: null,
refreshToken: null,
},
};
const isPasswordValid = await this.isPasswordCorrect(
password,
user.password,
);
if (!isPasswordValid) {
return {
resultCode: 1,
data: {
token: {
accessToken: null,
refreshToken: null,
},
},
};
}
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);
}
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());
if (dbToken !== token || isTokenExpired) {
return false;
}
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;
return true;
}
}

View File

@@ -0,0 +1,10 @@
import { IsEmail, Length } from 'class-validator';
export class RegistrationDto {
@Length(3, 30)
name: string;
@Length(3, 30)
password: string;
@IsEmail()
email: string;
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { RegistrationDto } from './registration.dto';
export class UpdateAuthDto extends PartialType(RegistrationDto) {}

View File

@@ -0,0 +1 @@
export class Auth {}

View File

@@ -0,0 +1,52 @@
import {
BadRequestException,
CanActivate,
ExecutionContext,
Injectable,
NotFoundException,
UnauthorizedException,
} 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();
if (!request.headers || !request.headers.authorization) {
throw new BadRequestException([{ message: 'No any auth headers' }]);
}
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);
if (!user) {
throw new NotFoundException([
{
field: 'token',
message: 'user not found',
},
]);
}
} catch (e) {
console.log(e);
throw new UnauthorizedException([
{
message: 'login or password invalid',
},
]);
}
return true;
}
}

View File

@@ -0,0 +1,29 @@
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';
if (!request.headers || !request.headers.authorization) {
throw new UnauthorizedException([{ message: 'No any auth headers' }]);
} else {
if (request.headers.authorization != exceptedAuthInput) {
throw new UnauthorizedException([
{
message: 'login or password invalid',
},
]);
}
}
return true;
}
}

View File

@@ -0,0 +1,25 @@
import {
ExecutionContext,
Injectable,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor() {
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;
// check DTO
return res;
}
}

View File

@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

View File

@@ -0,0 +1,21 @@
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,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: true,
secretOrKey: appSettings.auth.ACCESS_JWT_SECRET_KEY,
});
}
async validate(payload: any) {
return { userId: payload.userId };
}
}

View File

@@ -0,0 +1,21 @@
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',
});
}
async validate(login: string, password: string): Promise<any> {
const user = await this.authService.checkCredentials(login, password);
if (user.resultCode === 1) {
throw new UnauthorizedException();
}
return user;
}
}

View File

@@ -0,0 +1,69 @@
import { IEvent } from '@nestjs/cqrs';
export class ResultNotification<T = null> {
constructor(data: T | null = null) {
this.data = data;
}
extensions: NotificationExtension[] = [];
code = 0;
data: T | null = null;
hasError() {
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));
}
addData(data: T) {
this.data = data;
}
}
export class NotificationExtension {
constructor(public message: string, public key: string | null) {}
}
export class DomainResultNotification<
TData = null,
> extends ResultNotification<TData> {
public events: IEvent[] = [];
addEvents(...events: IEvent[]) {
this.events = [...this.events, ...events];
}
static create<T>(
mainNotification: DomainResultNotification<T>,
...otherNotifications: DomainResultNotification[]
) {
const domainResultNotification = new DomainResultNotification<T>();
if (!!mainNotification.data) {
domainResultNotification.addData(mainNotification.data);
}
domainResultNotification.events = mainNotification.events;
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);
});
});
return domainResultNotification;
}
}

View File

@@ -0,0 +1,58 @@
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);
}
}
export const validateEntityOrThrow = async (entity: any) => {
try {
await validateOrReject(entity);
} catch (errors) {
const resultNotification: ResultNotification = mapErrorsToNotification(
validationErrorsMapper.mapValidationErrorArrayToValidationPipeErrorTypeArray(
errors,
),
);
throw new DomainError('domain entity validation error', resultNotification);
}
};
export const validateEntity = async <T extends object>(
entity: T,
events: IEvent[],
): Promise<DomainResultNotification<T>> => {
try {
await validateOrReject(entity);
} catch (errors) {
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);
return domainResultNotification;
};
export function mapErrorsToNotification<T>(errors: ValidationPipeErrorType[]) {
const resultNotification = new DomainResultNotification<T>();
errors.forEach((item: ValidationPipeErrorType) =>
resultNotification.addError(item.message, item.field, 1),
);
return resultNotification;
}

View File

@@ -0,0 +1,47 @@
import {
Body,
Controller,
Delete,
Get,
NotFoundException,
Param,
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';
@Controller('users')
export class UsersController {
constructor(private usersService: UsersService) {}
@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;
}
//@UseGuards(BaseAuthGuard)
@Post()
async create(@Body() createUserDto: CreateUserDto) {
return await this.usersService.createUser(
createUserDto.login,
createUserDto.password,
createUserDto.email,
);
}
@UseGuards(BaseAuthGuard)
@Delete(':id')
async remove(@Param('id') id: string) {
return await this.usersService.deleteUserById(id);
}
}

View File

@@ -0,0 +1,10 @@
import { Length, Matches } from 'class-validator';
export class CreateUserDto {
@Length(3, 10)
login: string;
@Length(6, 20)
password: string;
@Matches(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/)
email: string;
}

View File

@@ -0,0 +1,164 @@
import {
CreateUserInput,
EntityWithPaginationType,
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';
@Injectable()
export class UsersRepository implements IUsersRepository {
constructor(private prisma: PrismaService) {}
async getUsers(
currentPage: number,
itemsPerPage: number,
searchNameTerm: string,
): Promise<EntityWithPaginationType<UserViewType>> {
const where = {
name: {
search: searchNameTerm,
},
};
const [totalItems, users] = await this.prisma.$transaction([
this.prisma.user.count({ where }),
this.prisma.user.findMany({
where,
skip: (currentPage - 1) * itemsPerPage,
take: itemsPerPage,
}),
]);
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---');
return {
totalPages,
currentPage,
itemsPerPage,
totalItems,
items: usersView,
};
}
async createUser(newUser: CreateUserInput): Promise<User | null> {
return await this.prisma.user.create({
data: {
email: newUser.email,
password: newUser.password,
name: newUser.name,
verification: {
create: {
verificationToken: newUser.verificationToken,
verificationTokenExpiry: newUser.verificationTokenExpiry,
},
},
},
include: {
verification: true,
},
});
}
async deleteUserById(id: string): Promise<boolean> {
const result = await this.prisma.user.delete({
where: {
id,
},
});
return result.isDeleted;
}
async findUserById(id: string): Promise<User | null> {
const user = await this.prisma.user.findUnique({ where: { id } });
if (!user) {
return null;
}
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 user;
}
async findUserByVerificationToken(
token: string,
): Promise<VerificationWithUser | null> {
const verification = await this.prisma.verification.findUnique({
where: {
verificationToken: token,
},
include: {
user: true,
},
});
if (!verification) {
return null;
}
return verification;
}
async updateConfirmation(id: string) {
const result = await this.prisma.verification.update({
where: {
userId: id,
},
data: {
isEmailVerified: true,
},
});
return result.isEmailVerified;
}
async updateVerificationToken(id: string) {
return await this.prisma.verification.update({
where: {
userId: id,
},
data: {
verificationToken: uuidv4(),
verificationTokenExpiry: addHours(new Date(), 24),
},
include: {
user: true,
},
});
}
async revokeToken(id: string, token: string): Promise<User | null> {
const revokedToken = await this.prisma.accessToken.update({
where: {
token: token,
},
data: {
isRevoked: true,
},
include: {
user: true,
},
});
if (!revokedToken.user) {
return null;
}
return revokedToken.user;
}
}

View File

@@ -0,0 +1,87 @@
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';
@Injectable()
export class UsersService {
constructor(private usersRepository: UsersRepository) {}
async getUsers(page: number, pageSize: number, searchNameTerm: string) {
return await this.usersRepository.getUsers(page, pageSize, searchNameTerm);
}
async getUserById(id: string) {
return await this.usersRepository.findUserById(id);
}
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,
password: passwordHash,
verificationToken: uuidv4(),
verificationTokenExpiry: addHours(new Date(), 24),
isEmailVerified: false,
};
const createdUser = await this.usersRepository.createUser(newUser);
if (!createdUser) {
return null;
}
return {
id: createdUser.id,
name: createdUser.name,
email: createdUser.email,
};
}
async deleteUserById(id: string): Promise<boolean> {
return await this.usersRepository.deleteUserById(id);
}
async addRevokedToken(token: string) {
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);
} catch (e) {
console.log('Decoding error: e');
return null;
}
}
private async _generateHash(password: string) {
return await bcrypt.hash(password, 10);
}
}
export interface IUsersRepository {
getUsers(
page: number,
pageSize: number,
searchNameTerm: string,
): Promise<EntityWithPaginationType<UserViewType>>;
createUser(newUser: CreateUserInput): Promise<User | null>;
deleteUserById(id: string): Promise<boolean>;
findUserById(id: string): Promise<User | null>;
revokeToken(id: string, token: string): Promise<User | null>;
}

View File

@@ -0,0 +1,11 @@
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],
providers: [UsersService, UsersRepository],
exports: [UsersRepository, UsersService],
})
export class UsersModule {}

View File

@@ -0,0 +1,54 @@
//базовые настройки env переменных
//по умолчанию переменные беруться сначала из ENV илм смотрят всегда на staging
//для подстановки локальных значений переменных использовать исключительно локальные env файлы env.development.local
//при необзодимости добавляем сюда нужные приложению переменные
import * as dotenv from 'dotenv';
dotenv.config();
export type EnvironmentVariable = { [key: string]: string | undefined };
export type EnvironmentsTypes =
| 'DEVELOPMENT'
| 'STAGING'
| 'PRODUCTION'
| 'TEST';
export class EnvironmentSettings {
constructor(private env: EnvironmentsTypes) {}
getEnv() {
return this.env;
}
isProduction() {
return this.env === 'PRODUCTION';
}
isStaging() {
return this.env === 'STAGING';
}
isDevelopment() {
return this.env === 'DEVELOPMENT';
}
isTesting() {
return this.env === 'TEST';
}
}
class AuthSettings {
public readonly BASE_AUTH_HEADER: string;
public readonly ACCESS_JWT_SECRET_KEY: string;
public readonly REFRESH_JWT_SECRET_KEY: string;
constructor(private envVariables: EnvironmentVariable) {
this.BASE_AUTH_HEADER =
envVariables.BASE_AUTH_HEADER || 'Basic YWRtaW46cXdlcnR5';
this.ACCESS_JWT_SECRET_KEY =
envVariables.ACCESS_JWT_SECRET_KEY || 'accessJwtSecret';
this.REFRESH_JWT_SECRET_KEY =
envVariables.REFRESH_JWT_SECRET_KEY || 'refreshJwtSecret';
}
}
export class AppSettings {
constructor(public env: EnvironmentSettings, public auth: AuthSettings) {}
}
const env = new EnvironmentSettings(
(process.env.NODE_ENV || 'DEVELOPMENT') as EnvironmentsTypes,
);
const auth = new AuthSettings(process.env);
export const appSettings = new AppSettings(env, auth);

View File

@@ -0,0 +1,16 @@
import { Global, Module } from '@nestjs/common';
import { appSettings, AppSettings } from './app-settings';
//главный config модуль для управления env переменными импортируется в app.module.ts глобально
//поскольку он глобальный то импортировать в каждый модуль его не надо
@Global()
@Module({
providers: [
{
provide: AppSettings.name,
useFactory: () => appSettings,
},
],
exports: [AppSettings.name],
})
export class ConfigModule {}

View File

@@ -0,0 +1,43 @@
import {
BadRequestException,
INestApplication,
ValidationPipe,
} from '@nestjs/common';
import { ValidationError } from 'class-validator';
export const validationErrorsMapper = {
mapValidationErrorArrayToValidationPipeErrorTypeArray(
errors: ValidationError[],
): ValidationPipeErrorType[] {
return errors.flatMap((error) => {
const constraints = error.constraints ?? [];
return Object.entries(constraints).map(([_, value]) => ({
field: error.property,
message: value,
}));
});
},
};
export function pipesSetup(app: INestApplication) {
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
stopAtFirstError: true,
exceptionFactory: (errors: ValidationError[]) => {
const err =
validationErrorsMapper.mapValidationErrorArrayToValidationPipeErrorTypeArray(
errors,
);
throw new BadRequestException(err);
},
}),
);
}
export type ValidationPipeErrorType = {
field: string;
message: string;
};

145
src/types/types.ts Normal file
View File

@@ -0,0 +1,145 @@
import { Prisma } from '@prisma/client';
export type NewestLikesType = {
id: string;
login: string;
addedAt: Date;
};
export type ExtendedLikesInfoType = {
dislikesCount: number;
likesCount: number;
myStatus: string;
newestLikes: Array<NewestLikesType>;
};
export type PostType = {
addedAt: Date;
id?: string;
title: string | null;
shortDescription: string | null;
content: string | null;
blogId: string;
blogName?: string | null;
extendedLikesInfo: ExtendedLikesInfoType;
};
export type BlogType = {
id: string;
name: string | null;
youtubeUrl: string | null;
};
export type LikeType = {
userId: string;
login: string;
action: string;
addedAt: Date;
};
export type CommentType = {
id: string;
content: string; //20<len<300
postId: string;
userId: string;
userLogin: string;
addedAt: Date;
likesInfo?: {
likesCount: number;
dislikesCount: number;
myStatus: string;
};
};
export type EntityWithPaginationType<T> = {
totalPages: number;
currentPage: number;
itemsPerPage: number;
totalItems: number;
items: T[];
};
export type QueryDataType = {
page: number;
pageSize: number;
searchNameTerm: string;
};
export type ErrorMessageType = {
message: string;
field: string;
};
const userInclude: Prisma.UserInclude = {
verification: true,
};
export type VerificationWithUser = Prisma.VerificationGetPayload<{
include: { user: true };
}>;
export type User = Prisma.UserGetPayload<{
include: typeof userInclude;
}>;
export type CreateUserInput = Omit<
Prisma.UserCreateInput & Prisma.VerificationCreateInput,
'user'
>;
export type UserType = {
accountData: Prisma.UserCreateInput;
emailConfirmation: EmailConfirmationType;
};
export type UserViewType = {
id: string;
name: string;
email: string;
};
export type UserAccountType = {
id: string;
email: string;
login: string;
passwordHash: string;
createdAt: Date;
revokedTokens?: string[] | null;
};
export type SentConfirmationEmailType = {
sentDate: Date;
};
export type LoginAttemptType = {
attemptDate: Date;
ip: string;
};
export type EmailConfirmationType = {
isConfirmed: boolean;
confirmationCode: string;
expirationDate: Date;
sentEmails?: SentConfirmationEmailType[];
};
export type LimitsControlType = {
userIp: string;
url: string;
time: Date;
};
export type CheckLimitsType = {
login: string | null;
userIp: string;
url: string;
time: Date;
};
export type EmailConfirmationMessageType = {
email: string;
message: string;
subject: string;
isSent: boolean;
createdAt: Date;
};
export enum LikeAction {
Like = 'Like',
Dislike = 'Dislike',
None = 'None',
}
export type LikeActionType = 'Like' | 'Dislike' | 'None';

View File

@@ -1,13 +0,0 @@
import { IsEmail, IsString, Length } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
password: string;
@IsString()
@Length(2, 40)
name: string;
}

View File

@@ -1 +0,0 @@
export class User {}

View File

@@ -1,20 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
describe('UsersController', () => {
let controller: UsersController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [UsersService],
}).compile();
controller = module.get<UsersController>(UsersController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@@ -1,42 +0,0 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get()
findAll() {
return this.usersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(id, updateUserDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.usersService.remove(id);
}
}

View File

@@ -1,9 +0,0 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
@Module({
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {}

View File

@@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@@ -1,38 +0,0 @@
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaService } from '../prisma.service';
@Injectable()
export class UsersService {
constructor(private prisma: PrismaService) {}
create(createUserDto: CreateUserDto) {
return this.prisma.user.create({
data: createUserDto,
});
}
findAll() {
return this.prisma.user.findMany();
}
findOne(id: string) {
return this.prisma.user.findUnique({
where: { id },
});
}
update(id: string, updateUserDto: UpdateUserDto) {
return this.prisma.user.update({
where: { id },
data: updateUserDto,
});
}
remove(id: string) {
return this.prisma.user.delete({
where: { id },
});
}
}