init repo
This commit is contained in:
commit
51344d2018
|
@ -0,0 +1,13 @@
|
||||||
|
# app port
|
||||||
|
API_PORT=3001
|
||||||
|
|
||||||
|
# db config
|
||||||
|
DB_HOST=localhost
|
||||||
|
DB_PORT=25432
|
||||||
|
DB_USER=dating-admin
|
||||||
|
DB_PASSWORD=7TTLpNh4GtQcDAMY
|
||||||
|
DB_NAME=dating-db
|
||||||
|
|
||||||
|
# jwt
|
||||||
|
JWT_SECRET=3XUR3uRX6KHH5LI7nsWUh7RyhpJ8ST9t
|
||||||
|
JWT_EXPIRATION_TIME=3600
|
|
@ -0,0 +1,25 @@
|
||||||
|
module.exports = {
|
||||||
|
parser: '@typescript-eslint/parser',
|
||||||
|
parserOptions: {
|
||||||
|
project: 'tsconfig.json',
|
||||||
|
tsconfigRootDir: __dirname,
|
||||||
|
sourceType: 'module',
|
||||||
|
},
|
||||||
|
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||||
|
extends: [
|
||||||
|
'plugin:@typescript-eslint/recommended',
|
||||||
|
'plugin:prettier/recommended',
|
||||||
|
],
|
||||||
|
root: true,
|
||||||
|
env: {
|
||||||
|
node: true,
|
||||||
|
jest: true,
|
||||||
|
},
|
||||||
|
ignorePatterns: ['.eslintrc.js'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/interface-name-prefix': 'off',
|
||||||
|
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||||
|
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
},
|
||||||
|
};
|
|
@ -0,0 +1,37 @@
|
||||||
|
.env
|
||||||
|
|
||||||
|
# compiled output
|
||||||
|
/dist
|
||||||
|
/node_modules
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Tests
|
||||||
|
/coverage
|
||||||
|
/.nyc_output
|
||||||
|
|
||||||
|
# IDEs and editors
|
||||||
|
/.idea
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
|
.c9/
|
||||||
|
*.launch
|
||||||
|
.settings/
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# IDE - VSCode
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
|
@ -0,0 +1,73 @@
|
||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
|
||||||
|
</p>
|
||||||
|
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
|
||||||
|
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ yarn install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running the app
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ yarn run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ yarn run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ yarn run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ yarn run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ yarn run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ yarn run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](LICENSE).
|
|
@ -0,0 +1,17 @@
|
||||||
|
version: "3.9"
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:15.3
|
||||||
|
container_name: dating-postgres
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: "dating-db"
|
||||||
|
POSTGRES_USER: "dating-admin"
|
||||||
|
POSTGRES_PASSWORD: "7TTLpNh4GtQcDAMY"
|
||||||
|
volumes:
|
||||||
|
- dating-postgres-data:/var/lib/postgresql
|
||||||
|
ports:
|
||||||
|
- "25432:5432"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
dating-postgres-data:
|
||||||
|
driver: local
|
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,90 @@
|
||||||
|
{
|
||||||
|
"name": "dating",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "Dating app api",
|
||||||
|
"author": "Pravdin Egor Vadimov",
|
||||||
|
"private": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@nestjs/common": "^9.0.0",
|
||||||
|
"@nestjs/config": "^3.0.1",
|
||||||
|
"@nestjs/core": "^9.0.0",
|
||||||
|
"@nestjs/jwt": "^10.1.1",
|
||||||
|
"@nestjs/passport": "^10.0.1",
|
||||||
|
"@nestjs/platform-express": "^9.0.0",
|
||||||
|
"@nestjs/swagger": "^7.1.10",
|
||||||
|
"@nestjs/typeorm": "^10.0.0",
|
||||||
|
"bcrypt": "^5.1.1",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.0",
|
||||||
|
"cookie-parser": "^1.4.6",
|
||||||
|
"helmet": "^7.0.0",
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"passport": "^0.6.0",
|
||||||
|
"passport-jwt": "^4.0.1",
|
||||||
|
"passport-local": "^1.0.0",
|
||||||
|
"pg": "^8.11.3",
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rxjs": "^7.2.0",
|
||||||
|
"typeorm": "^0.3.17"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@nestjs/cli": "^9.0.0",
|
||||||
|
"@nestjs/schematics": "^9.0.0",
|
||||||
|
"@nestjs/testing": "^9.0.0",
|
||||||
|
"@types/bcrypt": "^5.0.0",
|
||||||
|
"@types/cookie-parser": "^1.4.4",
|
||||||
|
"@types/express": "^4.17.13",
|
||||||
|
"@types/jest": "29.5.1",
|
||||||
|
"@types/lodash": "^4.14.198",
|
||||||
|
"@types/node": "18.16.12",
|
||||||
|
"@types/passport-jwt": "^3.0.9",
|
||||||
|
"@types/passport-local": "^1.0.35",
|
||||||
|
"@types/supertest": "^2.0.11",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^5.0.0",
|
||||||
|
"@typescript-eslint/parser": "^5.0.0",
|
||||||
|
"eslint": "^8.0.1",
|
||||||
|
"eslint-config-prettier": "^8.3.0",
|
||||||
|
"eslint-plugin-prettier": "^4.0.0",
|
||||||
|
"jest": "29.5.0",
|
||||||
|
"prettier": "^2.3.2",
|
||||||
|
"source-map-support": "^0.5.20",
|
||||||
|
"supertest": "^6.1.3",
|
||||||
|
"ts-jest": "29.1.0",
|
||||||
|
"ts-loader": "^9.2.3",
|
||||||
|
"ts-node": "^10.0.0",
|
||||||
|
"tsconfig-paths": "4.2.0",
|
||||||
|
"typescript": "^5.0.0"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot(),
|
||||||
|
AuthModule,
|
||||||
|
TypeOrmModule.forRoot({
|
||||||
|
type: 'postgres',
|
||||||
|
host: process.env.DB_HOST,
|
||||||
|
port: +process.env.DB_PORT,
|
||||||
|
username: process.env.DB_USER,
|
||||||
|
password: process.env.DB_PASSWORD,
|
||||||
|
database: process.env.DB_NAME,
|
||||||
|
entities: ['dist/**/*.entity.js'],
|
||||||
|
// logging: ['query']
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
|
@ -0,0 +1,47 @@
|
||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
HttpCode,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
Res,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { RegisterDto } from './dto/register.dto';
|
||||||
|
import { Response } from 'express';
|
||||||
|
import { omit } from 'lodash';
|
||||||
|
import { LocalAuthGuard } from './guards/local-auth.guard';
|
||||||
|
|
||||||
|
import JwtAuthGuard from './guards/jwt-auth.guard';
|
||||||
|
import { RequestWithUser } from './interfaces/request-with-user.interface';
|
||||||
|
|
||||||
|
@Controller('auth')
|
||||||
|
export class AuthController {
|
||||||
|
constructor(private readonly authService: AuthService) {}
|
||||||
|
|
||||||
|
@Post('register')
|
||||||
|
async register(@Body() registerData: RegisterDto) {
|
||||||
|
return this.authService.register(registerData);
|
||||||
|
}
|
||||||
|
|
||||||
|
@HttpCode(200)
|
||||||
|
@UseGuards(LocalAuthGuard)
|
||||||
|
@Post('login')
|
||||||
|
async login(@Req() request: RequestWithUser, @Res() response: Response) {
|
||||||
|
const user = request.user;
|
||||||
|
const cookie = await this.authService.getCookieWithJwtToken(
|
||||||
|
user.id,
|
||||||
|
user.name,
|
||||||
|
);
|
||||||
|
response.setHeader('Set-Cookie', cookie);
|
||||||
|
response.json({ user: omit(user, 'password') });
|
||||||
|
}
|
||||||
|
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@Post('log-out')
|
||||||
|
async logOut(@Req() request: RequestWithUser, @Res() response: Response) {
|
||||||
|
response.setHeader('Set-Cookie', this.authService.getCookieForLogOut());
|
||||||
|
return response.sendStatus(200);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PassportModule } from '@nestjs/passport';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { UsersModule } from 'src/users/users.module';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { LocalStrategy } from './strategies/local.strategy';
|
||||||
|
import { AuthController } from './auth.controller';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
PassportModule,
|
||||||
|
UsersModule,
|
||||||
|
ConfigModule,
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: async (configService: ConfigService) => ({
|
||||||
|
secret: configService.get('JWT_SECRET'),
|
||||||
|
signOptions: {
|
||||||
|
expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}s`,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
providers: [AuthService, LocalStrategy, JwtStrategy],
|
||||||
|
controllers: [AuthController],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
|
@ -0,0 +1,71 @@
|
||||||
|
import { omit } from 'lodash';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PostgresErrorCode } from 'src/database/postgresErrorCodes.enum';
|
||||||
|
import { UsersService } from 'src/users/users.service';
|
||||||
|
import { RegisterDto } from './dto/register.dto';
|
||||||
|
import {
|
||||||
|
InternalErrorException,
|
||||||
|
UserEmailExistsException,
|
||||||
|
WrongCredentialsException,
|
||||||
|
} from 'src/utils/errors';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { TokenPayload } from './interfaces/token-payload.interface';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
constructor(
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async register(registrationData: RegisterDto) {
|
||||||
|
const hashedPassword = await bcrypt.hash(registrationData.password, 10);
|
||||||
|
try {
|
||||||
|
const createdUser = await this.usersService.create({
|
||||||
|
...registrationData,
|
||||||
|
password: hashedPassword,
|
||||||
|
});
|
||||||
|
return omit(createdUser, 'password');
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.code === PostgresErrorCode.UniqueViolation) {
|
||||||
|
throw new UserEmailExistsException();
|
||||||
|
}
|
||||||
|
throw new InternalErrorException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getAuthenticatedUser(email: string, password: string) {
|
||||||
|
try {
|
||||||
|
const user = await this.usersService.getByEmail(email);
|
||||||
|
await this.verifyPassword(password, user.password);
|
||||||
|
return omit(user, 'password');
|
||||||
|
} catch (error) {
|
||||||
|
throw new WrongCredentialsException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async verifyPassword(plainPassword: string, hashedPassword: string) {
|
||||||
|
const isPasswordMatching = await bcrypt.compare(
|
||||||
|
plainPassword,
|
||||||
|
hashedPassword,
|
||||||
|
);
|
||||||
|
if (!isPasswordMatching) {
|
||||||
|
throw new WrongCredentialsException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getCookieWithJwtToken(userId: number, username: string) {
|
||||||
|
const payload: TokenPayload = { id: userId, username };
|
||||||
|
const token = await this.jwtService.signAsync(payload);
|
||||||
|
return `Authentication=${token}; HttpOnly; Path=/; Max-Age=${this.configService.get(
|
||||||
|
'JWT_EXPIRATION_TIME',
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getCookieForLogOut() {
|
||||||
|
return `Authentication=; HttpOnly; Path=/; Max-Age=0`;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
import { CreateUserDto } from 'src/users/dto/create-user.dto';
|
||||||
|
|
||||||
|
export class RegisterDto extends CreateUserDto {}
|
|
@ -0,0 +1,5 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export default class JwtAuthGuard extends AuthGuard('jwt') {}
|
|
@ -0,0 +1,5 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class LocalAuthGuard extends AuthGuard('local') {}
|
|
@ -0,0 +1,6 @@
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { User } from 'src/users/entities/user.entity';
|
||||||
|
|
||||||
|
export interface RequestWithUser extends Request {
|
||||||
|
user: User;
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
export interface TokenPayload {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||||
|
import { UsersService } from 'src/users/users.service';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { TokenPayload } from '../interfaces/token-payload.interface';
|
||||||
|
import { omit } from 'lodash';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||||
|
constructor(
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
) {
|
||||||
|
super({
|
||||||
|
jwtFromRequest: ExtractJwt.fromExtractors([
|
||||||
|
(request: Request) => {
|
||||||
|
return request?.cookies?.Authentication;
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
secretOrKey: configService.get('JWT_SECRET'),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async validate(payload: TokenPayload) {
|
||||||
|
const user = await this.usersService.getById(payload.id);
|
||||||
|
return omit(user, 'password');
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
|
import { Strategy } from 'passport-local';
|
||||||
|
import { AuthService } from '../auth.service';
|
||||||
|
import { User } from 'src/users/entities/user.entity';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class LocalStrategy extends PassportStrategy(Strategy) {
|
||||||
|
constructor(private authenticationService: AuthService) {
|
||||||
|
super({
|
||||||
|
usernameField: 'email',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async validate(
|
||||||
|
email: string,
|
||||||
|
password: string,
|
||||||
|
): Promise<Omit<User, 'password'>> {
|
||||||
|
return this.authenticationService.getAuthenticatedUser(email, password);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
export enum PostgresErrorCode {
|
||||||
|
UniqueViolation = '23505',
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import cookieParser from 'cookie-parser';
|
||||||
|
import helmet from 'helmet';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
|
||||||
|
app.useGlobalPipes(new ValidationPipe());
|
||||||
|
app.use(cookieParser());
|
||||||
|
app.use(helmet());
|
||||||
|
app.enableCors();
|
||||||
|
|
||||||
|
const config = new DocumentBuilder()
|
||||||
|
.setTitle('Dating')
|
||||||
|
.setDescription('Dating app API description')
|
||||||
|
.setVersion('1.0')
|
||||||
|
.addTag('dating')
|
||||||
|
.build();
|
||||||
|
const document = SwaggerModule.createDocument(app, config);
|
||||||
|
SwaggerModule.setup('docs', app, document);
|
||||||
|
|
||||||
|
await app.listen(process.env.PORT);
|
||||||
|
}
|
||||||
|
bootstrap();
|
|
@ -0,0 +1,15 @@
|
||||||
|
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateUserDto {
|
||||||
|
@IsNotEmpty()
|
||||||
|
@IsString()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@IsNotEmpty()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(5)
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
||||||
|
|
||||||
|
export enum UserRole {
|
||||||
|
ADMIN = 'admin',
|
||||||
|
STANDARD = 'standard',
|
||||||
|
}
|
||||||
|
|
||||||
|
@Entity('Users')
|
||||||
|
export class User {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id!: number;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@Column({ unique: true })
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: UserRole,
|
||||||
|
default: UserRole.STANDARD,
|
||||||
|
})
|
||||||
|
role: UserRole;
|
||||||
|
}
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { User } from './entities/user.entity';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([User])],
|
||||||
|
providers: [UsersService],
|
||||||
|
exports: [UsersService],
|
||||||
|
})
|
||||||
|
export class UsersModule {}
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { CreateUserDto } from './dto/create-user.dto';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { User } from './entities/user.entity';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import {
|
||||||
|
UserEmailNotExistsException,
|
||||||
|
UserIdNotExistsException,
|
||||||
|
} from 'src/utils/errors';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UsersService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(User)
|
||||||
|
private usersRepository: Repository<User>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async getByEmail(email: string) {
|
||||||
|
const user = await this.usersRepository.findOneBy({ email });
|
||||||
|
if (!user) {
|
||||||
|
throw new UserEmailNotExistsException();
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getById(id: number) {
|
||||||
|
const user = await this.usersRepository.findOneBy({ id });
|
||||||
|
if (!user) {
|
||||||
|
throw new UserIdNotExistsException();
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(userData: CreateUserDto) {
|
||||||
|
const user = this.usersRepository.create(userData);
|
||||||
|
await this.usersRepository.save(user);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||||
|
|
||||||
|
export class UserEmailNotExistsException extends HttpException {
|
||||||
|
constructor() {
|
||||||
|
super('User with this email does not exist', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WrongCredentialsException extends HttpException {
|
||||||
|
constructor() {
|
||||||
|
super('Wrong credentials provided', HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UserEmailExistsException extends HttpException {
|
||||||
|
constructor() {
|
||||||
|
super('User with that email already exists', HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class InternalErrorException extends HttpException {
|
||||||
|
constructor() {
|
||||||
|
super('Something went wrong', HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UserIdNotExistsException extends HttpException {
|
||||||
|
constructor() {
|
||||||
|
super('User with this id does not exist', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "es2017",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": false,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictBindCallApply": false,
|
||||||
|
"forceConsistentCasingInFileNames": false,
|
||||||
|
"noFallthroughCasesInSwitch": false
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue