move api to separate repository
This commit is contained in:
commit
02e9f874da
|
@ -0,0 +1,13 @@
|
||||||
|
# app port
|
||||||
|
PORT=3001
|
||||||
|
|
||||||
|
# db config
|
||||||
|
DB_HOST=localhost
|
||||||
|
DB_PORT=25432
|
||||||
|
DB_USER=mam-kupi-admin
|
||||||
|
DB_PASSWORD=7TTLpNh4GtQcDAMY
|
||||||
|
DB_NAME=mam-kupi-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: mam-kupi-postgres
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: "mam-kupi-db"
|
||||||
|
POSTGRES_USER: "mam-kupi-admin"
|
||||||
|
POSTGRES_PASSWORD: "7TTLpNh4GtQcDAMY"
|
||||||
|
volumes:
|
||||||
|
- mam-kupi-postgres-data:/var/lib/postgresql
|
||||||
|
ports:
|
||||||
|
- "25432:5432"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mam-kupi-postgres-data:
|
||||||
|
driver: local
|
|
@ -0,0 +1,47 @@
|
||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class InitSchema1693809572293 implements MigrationInterface {
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
CREATE TYPE public."Users_roles_enum" AS ENUM ('admin','standard');
|
||||||
|
|
||||||
|
CREATE TABLE public."Users" (
|
||||||
|
id serial4 primary key,
|
||||||
|
"name" varchar NOT NULL,
|
||||||
|
"password" varchar NOT NULL,
|
||||||
|
email varchar NOT NULL UNIQUE,
|
||||||
|
"role" public."Users_roles_enum" NOT NULL DEFAULT 'standard'::"Users_roles_enum"
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE public."Links" (
|
||||||
|
id serial4 PRIMARY KEY,
|
||||||
|
url varchar NOT NULL,
|
||||||
|
"lastCheckDate" timestamp NULL,
|
||||||
|
"userId" int4 NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE public."Links" ADD CONSTRAINT "links_user" FOREIGN KEY ("userId") REFERENCES public."Users"(id);
|
||||||
|
|
||||||
|
CREATE TABLE public."Prices" (
|
||||||
|
id serial4 PRIMARY KEY,
|
||||||
|
value int4 NOT NULL,
|
||||||
|
"createdDate" timestamp NOT NULL DEFAULT now(),
|
||||||
|
"linkId" int4 NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE public."Prices" ADD CONSTRAINT "prices_link" FOREIGN KEY ("linkId") REFERENCES public."Links"(id);
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`
|
||||||
|
DROP TYPE public."Users_roles_enum";
|
||||||
|
|
||||||
|
DROP TABLE public."Users";
|
||||||
|
|
||||||
|
DROP TABLE public."Links";
|
||||||
|
|
||||||
|
DROP TABLE public."Prices";
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,96 @@
|
||||||
|
{
|
||||||
|
"name": "api",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "Pravdin Egor Vadimovich",
|
||||||
|
"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",
|
||||||
|
"typeorm": "ts-node ./node_modules/typeorm/cli",
|
||||||
|
"migrate:run": "npm run typeorm migration:run -- -d ./typeorm.config.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@nestjs/axios": "^2.0.0",
|
||||||
|
"@nestjs/common": "^9.0.0",
|
||||||
|
"@nestjs/config": "^2.3.3",
|
||||||
|
"@nestjs/core": "^9.0.0",
|
||||||
|
"@nestjs/jwt": "^10.1.1",
|
||||||
|
"@nestjs/mapped-types": "*",
|
||||||
|
"@nestjs/microservices": "^9.4.3",
|
||||||
|
"@nestjs/passport": "^10.0.1",
|
||||||
|
"@nestjs/platform-express": "^9.0.0",
|
||||||
|
"@nestjs/schedule": "^2.2.3",
|
||||||
|
"@nestjs/typeorm": "^10.0.0",
|
||||||
|
"axios": "^1.4.0",
|
||||||
|
"bcrypt": "^5.1.1",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.0",
|
||||||
|
"cookie-parser": "^1.4.6",
|
||||||
|
"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.8.1",
|
||||||
|
"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/cron": "^2.0.1",
|
||||||
|
"@types/express": "^4.17.17",
|
||||||
|
"@types/jest": "29.5.1",
|
||||||
|
"@types/lodash": "^4.14.197",
|
||||||
|
"@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,12 @@
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AppController } from './app.controller';
|
||||||
|
import { AppService } from './app.service';
|
||||||
|
import { TasksModule } from './tasks/tasks.module';
|
||||||
|
import { ScheduleModule } from '@nestjs/schedule';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { LinksModule } from './links/links.module';
|
||||||
|
import { PricesModule } from './prices/prices.module';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { UsersModule } from './users/users.module';
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ScheduleModule.forRoot(),
|
||||||
|
ConfigModule.forRoot(),
|
||||||
|
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'],
|
||||||
|
}),
|
||||||
|
TasksModule,
|
||||||
|
LinksModule,
|
||||||
|
PricesModule,
|
||||||
|
UsersModule,
|
||||||
|
AuthModule,
|
||||||
|
],
|
||||||
|
controllers: [AppController],
|
||||||
|
providers: [AppService],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
|
@ -0,0 +1,8 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AppService {
|
||||||
|
getHello(): string {
|
||||||
|
return 'Hello World!';
|
||||||
|
}
|
||||||
|
}
|
|
@ -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 { 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 { JwtModule } from '@nestjs/jwt';
|
||||||
|
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,3 @@
|
||||||
|
export class CreateLinkDTO {
|
||||||
|
url: string;
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
import {
|
||||||
|
Column,
|
||||||
|
Entity,
|
||||||
|
ManyToOne,
|
||||||
|
OneToMany,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { Price } from 'src/prices/entities/prices.entity';
|
||||||
|
import { User } from 'src/users/entities/user.entity';
|
||||||
|
|
||||||
|
@Entity('Links')
|
||||||
|
export class Link {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id!: number;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
url: string;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
lastCheckDate: Date = new Date();
|
||||||
|
|
||||||
|
@OneToMany(() => Price, (price) => price.link)
|
||||||
|
prices: Price[];
|
||||||
|
|
||||||
|
@ManyToOne(() => User, (user) => user.links)
|
||||||
|
user: User;
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
|
||||||
|
import { LinksService } from './links.service';
|
||||||
|
import { CreateLinkDTO } from './dto/create-link.dto';
|
||||||
|
import JwtAuthGuard from 'src/auth/guards/jwt-auth.guard';
|
||||||
|
import { RequestWithUser } from 'src/auth/interfaces/request-with-user.interface';
|
||||||
|
|
||||||
|
@Controller('/links')
|
||||||
|
export class LinksController {
|
||||||
|
constructor(private readonly linksService: LinksService) {}
|
||||||
|
|
||||||
|
@Post('/')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
async createLink(
|
||||||
|
@Body() body: CreateLinkDTO,
|
||||||
|
@Req() request: RequestWithUser,
|
||||||
|
) {
|
||||||
|
const link = await this.linksService.createLink({
|
||||||
|
...body,
|
||||||
|
userId: request.user.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { link };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
async getLinks(@Req() request: RequestWithUser) {
|
||||||
|
const links = await this.linksService.getLinks(request.user.id);
|
||||||
|
|
||||||
|
return { links };
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { LinksService } from './links.service';
|
||||||
|
import { Link } from './entities/links.entity';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { LinksController } from './links.cotroller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Link])],
|
||||||
|
controllers: [LinksController],
|
||||||
|
providers: [LinksService],
|
||||||
|
})
|
||||||
|
export class LinksModule {}
|
|
@ -0,0 +1,21 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Link } from './entities/links.entity';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class LinksService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Link)
|
||||||
|
private linksRepository: Repository<Link>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async createLink({ url, userId }: { url: string; userId: number }) {
|
||||||
|
const link = this.linksRepository.create({ url, user: { id: userId } });
|
||||||
|
return this.linksRepository.save(link);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLinks(userId: number) {
|
||||||
|
return this.linksRepository.findBy({ user: { id: userId } });
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import * as cookieParser from 'cookie-parser';
|
||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
// import { MicroserviceOptions, Transport } from '@nestjs/microservices';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
app.useGlobalPipes(new ValidationPipe());
|
||||||
|
app.use(cookieParser());
|
||||||
|
await app.listen(process.env.PORT);
|
||||||
|
|
||||||
|
// MICROSERVICE
|
||||||
|
// app.connectMicroservice<MicroserviceOptions>({
|
||||||
|
// transport: Transport.NATS,
|
||||||
|
// options: { retryAttempts: 5, retryDelay: 3000 },
|
||||||
|
// });
|
||||||
|
|
||||||
|
// await app.startAllMicroservices();
|
||||||
|
// await app.listen(3001);
|
||||||
|
}
|
||||||
|
bootstrap();
|
|
@ -0,0 +1,23 @@
|
||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { Link } from 'src/links/entities/links.entity';
|
||||||
|
|
||||||
|
@Entity('Prices')
|
||||||
|
export class Price {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id!: number;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
value: number;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdDate: Date;
|
||||||
|
|
||||||
|
@ManyToOne(() => Link, (link) => link.prices)
|
||||||
|
link!: Link;
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { PricesService } from './prices.service';
|
||||||
|
import { Price } from './entities/prices.entity';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([Price])],
|
||||||
|
providers: [PricesService],
|
||||||
|
})
|
||||||
|
export class PricesModule {}
|
|
@ -0,0 +1,4 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PricesService {}
|
|
@ -0,0 +1,9 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TasksService } from './tasks.service';
|
||||||
|
import { HttpModule } from '@nestjs/axios';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [HttpModule],
|
||||||
|
providers: [TasksService],
|
||||||
|
})
|
||||||
|
export class TasksModule {}
|
|
@ -0,0 +1,44 @@
|
||||||
|
import { HttpService } from '@nestjs/axios';
|
||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||||
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
|
||||||
|
// * * * * * *
|
||||||
|
// | | | | | |
|
||||||
|
// | | | | | day of week
|
||||||
|
// | | | | months
|
||||||
|
// | | | day of month
|
||||||
|
// | | hours
|
||||||
|
// | minutes
|
||||||
|
// seconds (optional)
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TasksService {
|
||||||
|
private readonly logger = new Logger(TasksService.name);
|
||||||
|
|
||||||
|
constructor(private readonly httpService: HttpService) {}
|
||||||
|
|
||||||
|
private async request(link: string) {
|
||||||
|
try {
|
||||||
|
const response = await firstValueFrom(
|
||||||
|
this.httpService.get(`http://localhost:3000/parse?link=${link}`),
|
||||||
|
);
|
||||||
|
return response.data;
|
||||||
|
} catch (e) {
|
||||||
|
return 'Error!';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cron('0 */20 * * * *', {
|
||||||
|
name: 'sendParse',
|
||||||
|
timeZone: 'Europe/Moscow',
|
||||||
|
disabled: true,
|
||||||
|
})
|
||||||
|
async sendParse() {
|
||||||
|
const link =
|
||||||
|
'https://novex.ru/catalog/product/nabor-polot-c-smart-35-75-70-140-brusn/';
|
||||||
|
const res = await this.request(link);
|
||||||
|
this.logger.debug(res);
|
||||||
|
this.logger.debug('Called when the current second is 10');
|
||||||
|
}
|
||||||
|
}
|
|
@ -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,4 @@
|
||||||
|
import { PartialType } from '@nestjs/mapped-types';
|
||||||
|
import { CreateUserDto } from './create-user.dto';
|
||||||
|
|
||||||
|
export class UpdateUserDto extends PartialType(CreateUserDto) {}
|
|
@ -0,0 +1,32 @@
|
||||||
|
import { Link } from 'src/links/entities/links.entity';
|
||||||
|
import { Column, Entity, OneToMany, 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;
|
||||||
|
|
||||||
|
@OneToMany(() => Link, (link) => link.user)
|
||||||
|
links: Link[];
|
||||||
|
}
|
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { DataSource } from 'typeorm';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { config } from 'dotenv';
|
||||||
|
|
||||||
|
config();
|
||||||
|
|
||||||
|
const configService = new ConfigService();
|
||||||
|
|
||||||
|
export default new DataSource({
|
||||||
|
type: 'postgres',
|
||||||
|
host: configService.get('DB_HOST'),
|
||||||
|
port: +configService.get('DB_PORT'),
|
||||||
|
username: configService.get('DB_USER'),
|
||||||
|
password: configService.get('DB_PASSWORD'),
|
||||||
|
database: configService.get('DB_NAME'),
|
||||||
|
entities: ['dist/**/*.entity.js'],
|
||||||
|
migrations: ['migrations/**/*'],
|
||||||
|
});
|
Loading…
Reference in New Issue