Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Модуль 2 «Введение в Nest» #2

Merged
merged 27 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
04d1b5d
2.1. Добавит общую библиотеку `libs/shared/core.
AntonovIgor Mar 27, 2024
7a5b532
2.2. Удалит стартовые файлы из библиотеки core.
AntonovIgor Mar 27, 2024
b2178b1
2.3. Добавит интерфейс `User`, `AuthUser` и перечисление `UserRole`, …
AntonovIgor Mar 27, 2024
753a0bf
2.4. Установит пакет `class-transformer`.
AntonovIgor Mar 27, 2024
17680fc
2.5. Добавит библиотеку `shared/helpers`
AntonovIgor Mar 27, 2024
9cd4d83
2.6. Добавит модуль common.ts в общую библиотеку shared/helpers.
AntonovIgor Mar 27, 2024
9654e39
2.7. Удалит заготовки из проекта `account`
AntonovIgor Mar 27, 2024
c681a19
2.8. Добавит модули AuthenticationModule и BlogUserModule.
AntonovIgor Mar 27, 2024
d6071b5
2.9. Добавит `AuthenticationController` и `AuthenticationService`.
AntonovIgor Mar 27, 2024
eab3327
2.10. Добавит интерфейс `StorableEntity`.
AntonovIgor Mar 27, 2024
05c08ee
2.11. Добавит имплементацию `BlogUserEntity` и `BlogUserFactory`.
AntonovIgor Mar 27, 2024
e7fa07f
2.12. Добавит библиотеку `data-access` и `BaseMemoryRepository`.
AntonovIgor Mar 27, 2024
1d4f0fa
2.13. Имплементируем `BlogUserRepository`
AntonovIgor Mar 27, 2024
c24ecc0
2.14. Зарегистрирует `BlogUserRepository` и `BlogUserFactory` в качес…
AntonovIgor Mar 27, 2024
7237d01
2.15. Внедрит репозиторий в качестве зависимости.
AntonovIgor Mar 27, 2024
6dfc3c2
2.16. Установит пакет `dayjs`.
AntonovIgor Mar 27, 2024
b8bf334
2.17. Добавит DTO: `CreateUserDto` и `LoginUserDto`.
AntonovIgor Mar 27, 2024
9ff6c31
2.18. Установит пакет `bcrypt` и типы для него.
AntonovIgor Mar 27, 2024
d1c6e72
2.19. Добавит метод `setPassword` в `BlogUserEntity`.
AntonovIgor Mar 27, 2024
b432f78
2.20. Добавит метод `comparePassword`.
AntonovIgor Mar 27, 2024
df11db2
2.21. Добавит метод регистрации в `AuthenticationService`.
AntonovIgor Mar 27, 2024
cf4b970
2.22. Добавит метод `verifyUser` в `AuthenticationService`.
AntonovIgor Mar 27, 2024
b5a536a
2.23. Добавит Response Data Object.
AntonovIgor Mar 27, 2024
4c8ed19
2.24. Добавит контроллер `AuthenticationController`.
AntonovIgor Mar 27, 2024
2be916e
2.25. Добавит обработчик маршрута `/register`.
AntonovIgor Mar 27, 2024
fb82dbf
2.26. Добавит обработчики маршрутов `/login`, `/:id`.
AntonovIgor Mar 27, 2024
70ea983
2.27. Добавит примеры запросов для тестирования.
AntonovIgor Mar 27, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 0 additions & 22 deletions project/apps/account/src/app/app.controller.spec.ts

This file was deleted.

13 changes: 0 additions & 13 deletions project/apps/account/src/app/app.controller.ts

This file was deleted.

14 changes: 9 additions & 5 deletions project/apps/account/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { Module } from '@nestjs/common';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { BlogUserModule } from '@project/blog-user';
import { AuthenticationModule } from '@project/authentication'


@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
imports: [
BlogUserModule,
AuthenticationModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
21 changes: 0 additions & 21 deletions project/apps/account/src/app/app.service.spec.ts

This file was deleted.

8 changes: 0 additions & 8 deletions project/apps/account/src/app/app.service.ts

This file was deleted.

18 changes: 18 additions & 0 deletions project/libs/account/authentication/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions project/libs/account/authentication/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# authentication

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test authentication` to execute the unit tests via [Jest](https://jestjs.io).
11 changes: 11 additions & 0 deletions project/libs/account/authentication/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-disable */
export default {
displayName: 'authentication',
preset: '../../../jest.preset.js',
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../../coverage/libs/account/authentication',
};
9 changes: 9 additions & 0 deletions project/libs/account/authentication/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "authentication",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/account/authentication/src",
"projectType": "library",
"tags": [],
"// targets": "to see all targets run: nx show project authentication --web",
"targets": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const AUTH_USER_EXISTS = 'User with this email exists';
export const AUTH_USER_NOT_FOUND = 'User not found';
export const AUTH_USER_PASSWORD_WRONG = 'User password is wrong';
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';

import { AuthenticationService } from './authentication.service';
import { CreateUserDto } from '../dto/create-user.dto';
import { LoginUserDto } from '../dto/login-user.dto';

@Controller('auth')
export class AuthenticationController {
constructor(
private readonly authService: AuthenticationService
) {}

@Post('register')
public async create(@Body() dto: CreateUserDto) {
const newUser = await this.authService.register(dto);
return newUser.toPOJO();
}

@Post('login')
public async login(@Body() dto: LoginUserDto) {
const verifiedUser = await this.authService.verifyUser(dto);
return verifiedUser.toPOJO();
}

@Get(':id')
public async show(@Param('id') id: string) {
const existUser = await this.authService.getUser(id);
return existUser.toPOJO();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Create a new user
POST http://localhost:3000/api/auth/register HTTP/1.1
Content-Type: application/json

{
"email": "[email protected]",
"dateBirth": "2012-02-22",
"firstname": "Keks",
"lastname": "Smith",
"password": "123456"
}

###

# Get user by ID
GET http://localhost:3000/api/auth/7aef6925-4fe5-4057-b5cc-cc7cf214df05 HTTP/1.1

###

# Login user by email and password
POST http://localhost:3000/api/auth/login HTTP/1.1
Content-Type: application/json

{
"email": "[email protected]",
"password": "123456"
}

###
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';

import { BlogUserModule } from '@project/blog-user';

import { AuthenticationController } from './authentication.controller';
import { AuthenticationService } from './authentication.service';

@Module({
imports: [BlogUserModule],
controllers: [AuthenticationController],
providers: [AuthenticationService]
})
export class AuthenticationModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import dayjs from 'dayjs';
import { ConflictException, Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';

import { BlogUserRepository, BlogUserEntity } from '@project/blog-user';
import { UserRole } from '@project/shared/core';

import { CreateUserDto } from '../dto/create-user.dto';
import { AUTH_USER_EXISTS, AUTH_USER_NOT_FOUND, AUTH_USER_PASSWORD_WRONG } from './authentication.constant';
import { LoginUserDto } from '../dto/login-user.dto';

@Injectable()
export class AuthenticationService {
constructor(
private readonly blogUserRepository: BlogUserRepository
) {}

public async register(dto: CreateUserDto): Promise<BlogUserEntity> {
const {email, firstname, lastname, password, dateBirth} = dto;

const blogUser = {
email, firstname, lastname, role: UserRole.User,
avatar: '', dateOfBirth: dayjs(dateBirth).toDate(),
passwordHash: ''
};

const existUser = await this.blogUserRepository
.findByEmail(email);

if (existUser) {
throw new ConflictException(AUTH_USER_EXISTS);
}

const userEntity = await new BlogUserEntity(blogUser)
.setPassword(password)

this.blogUserRepository
.save(userEntity);

return userEntity;
}

public async verifyUser(dto: LoginUserDto) {
const {email, password} = dto;
const existUser = await this.blogUserRepository.findByEmail(email);

if (!existUser) {
throw new NotFoundException(AUTH_USER_NOT_FOUND);
}

if (!await existUser.comparePassword(password)) {
throw new UnauthorizedException(AUTH_USER_PASSWORD_WRONG);
}

return existUser;
}

public async getUser(id: string) {
const user = await this.blogUserRepository.findById(id);

if (! user) {
throw new NotFoundException(AUTH_USER_NOT_FOUND);
}

return user;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export class CreateUserDto {
public email: string;
public dateBirth: string;
public firstname: string;
public lastname: string;
public password: string;
}
4 changes: 4 additions & 0 deletions project/libs/account/authentication/src/dto/login-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class LoginUserDto {
public email: string;
public password: string;
}
1 change: 1 addition & 0 deletions project/libs/account/authentication/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { AuthenticationModule } from './authentication-module/authentication.module';
12 changes: 12 additions & 0 deletions project/libs/account/authentication/src/rdo/logged-user.rdo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Expose } from 'class-transformer';

export class LoggedUserRdo {
@Expose()
public id: string;

@Expose()
public email: string;

@Expose()
public accessToken: string;
}
21 changes: 21 additions & 0 deletions project/libs/account/authentication/src/rdo/user.rdo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Expose } from 'class-transformer';

export class UserRdo {
@Expose()
public id: string;

@Expose()
public avatar: string;

@Expose()
public dateOfBirth: string;

@Expose()
public email: string;

@Expose()
public firstname: string;

@Expose()
public lastname: string;
}
16 changes: 16 additions & 0 deletions project/libs/account/authentication/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"module": "commonjs"
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
11 changes: 11 additions & 0 deletions project/libs/account/authentication/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "../../../dist/out-tsc",
"declaration": true,
"types": ["node"]
},
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
"include": ["src/**/*.ts"]
}
14 changes: 14 additions & 0 deletions project/libs/account/authentication/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
18 changes: 18 additions & 0 deletions project/libs/account/blog-user/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
Loading
Loading