📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Initial commit
Blaumaus73f789bd087a
diff --git a/.env.example b/.env.examplenew file mode 100644index 000000000..3af971f76--- /dev/null+++ b/.env.example@@ -0,0 +1,3 @@+# Auth+JWT_SECRET=SOME_SECRET_TOKEN+JWT_EXPIRES=120\ No newline at end of filediff --git a/.eslintrc.js b/.eslintrc.jsnew file mode 100644index 000000000..f6c62bee2--- /dev/null+++ b/.eslintrc.js@@ -0,0 +1,24 @@+module.exports = {+ parser: '@typescript-eslint/parser',+ parserOptions: {+ project: 'tsconfig.json',+ 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',+ },+};diff --git a/.gitignore b/.gitignoreindex 67045665d..53e6a82e4 100644--- a/.gitignore+++ b/.gitignore@@ -1,3 +1,7 @@+# compiled output+/dist+/node_modules+# Logslogs*.log@@ -6,99 +10,28 @@ yarn-debug.log*yarn-error.log*lerna-debug.log*-# Diagnostic reports (https://nodejs.org/api/report.html)-report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json--# Runtime data-pids-*.pid-*.seed-*.pid.lock--# Directory for instrumented libs generated by jscoverage/JSCover-lib-cov--# Coverage directory used by tools like istanbul-coverage-*.lcov--# nyc test coverage-.nyc_output--# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)-.grunt--# Bower dependency directory (https://bower.io/)-bower_components--# node-waf configuration-.lock-wscript--# Compiled binary addons (https://nodejs.org/api/addons.html)-build/Release--# Dependency directories-node_modules/-jspm_packages/--# TypeScript v1 declaration files-typings/--# TypeScript cache-*.tsbuildinfo--# Optional npm cache directory-.npm--# Optional eslint cache-.eslintcache--# Microbundle cache-.rpt2_cache/-.rts2_cache_cjs/-.rts2_cache_es/-.rts2_cache_umd/--# Optional REPL history-.node_repl_history--# Output of 'npm pack'-*.tgz--# Yarn Integrity file-.yarn-integrity--# dotenv environment variables file-.env-.env.test--# parcel-bundler cache (https://parceljs.org/)-.cache--# Next.js build output-.next--# Nuxt.js build / generate output-.nuxt-dist--# Gatsby files-.cache/-# Comment in the public line in if your project uses Gatsby and *not* Next.js-# https://nextjs.org/blog/next-9-1#public-directory-support-# public--# vuepress build output-.vuepress/dist--# Serverless directories-.serverless/--# FuseBox cache-.fusebox/--# DynamoDB Local files-.dynamodb/--# TernJS port file-.tern-port+# 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++package-lock.json+.env\ No newline at end of filediff --git a/.prettierrc b/.prettierrcnew file mode 100644index 000000000..dcb72794f--- /dev/null+++ b/.prettierrc@@ -0,0 +1,4 @@+{+ "singleQuote": true,+ "trailingComma": "all"+}\ No newline at end of filediff --git a/README.md b/README.mdindex 300d57217..9fe8812ff 100644--- a/README.md+++ b/README.md@@ -1 +1,73 @@-# analytics_api\ No newline at end of file+<p align="center">+ <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" 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>+ <!--[](https://opencollective.com/nest#backer)+ [](https://opencollective.com/nest#sponsor)-->++## Description++[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.++## Installation++```bash+$ npm install+```++## Running the app++```bash+# development+$ npm run start++# watch mode+$ npm run start:dev++# production mode+$ npm run start:prod+```++## Test++```bash+# unit tests+$ npm run test++# e2e tests+$ npm run test:e2e++# test coverage+$ npm 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).diff --git a/nest-cli.json b/nest-cli.jsonnew file mode 100644index 000000000..56167b36a--- /dev/null+++ b/nest-cli.json@@ -0,0 +1,4 @@+{+ "collection": "@nestjs/schematics",+ "sourceRoot": "src"+}diff --git a/package.json b/package.jsonnew file mode 100644index 000000000..3a2a2a909--- /dev/null+++ b/package.json@@ -0,0 +1,94 @@+{+ "name": "analytics_api",+ "version": "0.0.1",+ "description": "",+ "author": "",+ "private": true,+ "license": "UNLICENSED",+ "scripts": {+ "prebuild": "rimraf dist",+ "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": "^7.6.13",+ "@nestjs/config": "^0.6.3",+ "@nestjs/core": "^7.6.13",+ "@nestjs/jwt": "^7.2.0",+ "@nestjs/passport": "^7.1.5",+ "@nestjs/platform-express": "^7.6.13",+ "@nestjs/schedule": "^0.4.3",+ "@nestjs/swagger": "^4.8.0",+ "@nestjs/typeorm": "^7.1.5",+ "bcrypt": "^5.0.1",+ "class-validator": "^0.13.1",+ "cookie-parser": "^1.4.5",+ "handlebars": "^4.7.7",+ "moment": "^2.29.1",+ "mysql": "^2.18.1",+ "nodemailer": "^6.5.0",+ "passport": "^0.4.1",+ "passport-jwt": "^4.0.0",+ "passport-local": "^1.0.0",+ "reflect-metadata": "^0.1.13",+ "rimraf": "^3.0.2",+ "rxjs": "^6.6.6",+ "sqlstring": "^2.3.2",+ "swagger-ui-express": "^4.1.6",+ "typeorm": "^0.2.31"+ },+ "devDependencies": {+ "@nestjs/cli": "^7.5.6",+ "@nestjs/schematics": "^7.2.7",+ "@nestjs/testing": "^7.6.13",+ "@types/bcrypt": "^3.0.0",+ "@types/cron": "^1.7.2",+ "@types/express": "^4.17.11",+ "@types/jest": "^26.0.20",+ "@types/node": "^14.14.31",+ "@types/nodemailer": "^6.4.1",+ "@types/passport-jwt": "^3.0.5",+ "@types/passport-local": "^1.0.33",+ "@types/supertest": "^2.0.10",+ "@typescript-eslint/eslint-plugin": "^4.15.2",+ "@typescript-eslint/parser": "^4.15.2",+ "eslint": "^7.20.0",+ "eslint-config-prettier": "^8.1.0",+ "eslint-plugin-prettier": "^3.3.1",+ "jest": "^26.6.3",+ "prettier": "^2.2.1",+ "supertest": "^6.1.3",+ "ts-jest": "^26.5.2",+ "ts-loader": "^8.0.17",+ "ts-node": "^9.1.1",+ "tsconfig-paths": "^3.9.0",+ "typescript": "^4.1.5"+ },+ "jest": {+ "moduleFileExtensions": [+ "js",+ "json",+ "ts"+ ],+ "rootDir": "src",+ "testRegex": ".*\\.spec\\.ts$",+ "transform": {+ "^.+\\.(t|j)s$": "ts-jest"+ },+ "collectCoverageFrom": [+ "**/*.(t|j)s"+ ],+ "coverageDirectory": "../coverage",+ "testEnvironment": "node"+ }+}diff --git a/src/action-tokens/action-token.entity.ts b/src/action-tokens/action-token.entity.tsnew file mode 100644index 000000000..cfbc289a1--- /dev/null+++ b/src/action-tokens/action-token.entity.ts@@ -0,0 +1,29 @@+import { Entity, PrimaryGeneratedColumn, ManyToOne, Timestamp, CreateDateColumn, Column } from 'typeorm'+import { User } from '../user/entities/user.entity'++export enum ActionTokenType {+ EMAIL_VERIFICATION,+ PASSWORD_RESET,+ EMAIL_CHANGE,+}++@Entity()+export class ActionToken {+ @PrimaryGeneratedColumn('uuid')+ id: string;++ @ManyToOne(() => User, user => user.actionTokens, { onDelete: 'CASCADE' })+ user: User;++ @CreateDateColumn()+ created: Timestamp++ @Column('varchar', { length: 254, default: null })+ newValue: string;++ @Column({+ type: 'enum',+ enum: ActionTokenType,+ })+ action: ActionTokenType+}\ No newline at end of filediff --git a/src/action-tokens/action-tokens.module.ts b/src/action-tokens/action-tokens.module.tsnew file mode 100644index 000000000..a45093e22--- /dev/null+++ b/src/action-tokens/action-tokens.module.ts@@ -0,0 +1,14 @@+import { Module } from '@nestjs/common'+import { TypeOrmModule } from '@nestjs/typeorm'++import { ActionTokensService } from './action-tokens.service'+import { ActionToken } from './action-token.entity'++@Module({+ imports: [+ TypeOrmModule.forFeature([ActionToken]),+ ],+ providers: [ActionTokensService],+ exports: [ActionTokensService]+})+export class ActionTokensModule {}diff --git a/src/action-tokens/action-tokens.service.spec.ts b/src/action-tokens/action-tokens.service.spec.tsnew file mode 100644index 000000000..9e8e70055--- /dev/null+++ b/src/action-tokens/action-tokens.service.spec.ts@@ -0,0 +1,18 @@+import { Test, TestingModule } from '@nestjs/testing';+import { ActionTokensService } from './action-tokens.service';++describe('ActionTokensService', () => {+ let service: ActionTokensService;++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [ActionTokensService],+ }).compile();++ service = module.get<ActionTokensService>(ActionTokensService);+ });++ it('should be defined', () => {+ expect(service).toBeDefined();+ });+});diff --git a/src/action-tokens/action-tokens.service.ts b/src/action-tokens/action-tokens.service.tsnew file mode 100644index 000000000..527ad66c6--- /dev/null+++ b/src/action-tokens/action-tokens.service.ts@@ -0,0 +1,26 @@+import { Injectable } from '@nestjs/common'+import { InjectRepository } from '@nestjs/typeorm'+import { Repository } from 'typeorm'++import { ActionToken, ActionTokenType } from './action-token.entity'+import { User } from '../user/entities/user.entity'++@Injectable()+export class ActionTokensService {+ constructor(+ @InjectRepository(ActionToken)+ private actionTokensRepository: Repository<ActionToken>,+ ) {}++ async createForUser(user: User, action: ActionTokenType, newValue: string = null): Promise<ActionToken> {+ return this.actionTokensRepository.save({user, action, newValue})+ }++ async find(id: string): Promise<ActionToken> {+ return this.actionTokensRepository.findOneOrFail(id, { relations: ['user']})+ }++ async delete(id: string): Promise<void> {+ await this.actionTokensRepository.delete(id)+ }+}diff --git a/src/app.module.ts b/src/app.module.tsnew file mode 100644index 000000000..22440d04b--- /dev/null+++ b/src/app.module.ts@@ -0,0 +1,37 @@+import { Module } from '@nestjs/common'+import { TypeOrmModule } from '@nestjs/typeorm'+import { ConfigModule } from '@nestjs/config'+import { ScheduleModule } from '@nestjs/schedule'++import { AuthModule } from './auth/auth.module'+import { UserModule } from './user/user.module'+import { User } from './user/entities/user.entity'+import { MailerModule } from './mailer/mailer.module'+import { ActionTokensModule } from './action-tokens/action-tokens.module'+import { ActionToken } from './action-tokens/action-token.entity'+import { TaskManagerModule } from './task-manager/task-manager.module'++@Module({+ imports: [+ ConfigModule.forRoot({ envFilePath: '.env' }),+ TypeOrmModule.forRoot({+ type: 'mysql',+ host: process.env.MYSQL_HOST || 'localhost',+ port: 3306,+ username: process.env.MYSQL_USER || 'root',+ password: process.env.MYSQL_ROOT_PASSWORD || '123123123',+ database: process.env.MYSQL_DATABASE || 'analytics',+ synchronize: true,+ entities: [User, ActionToken],+ }),+ ScheduleModule.forRoot(),+ TaskManagerModule,+ AuthModule,+ UserModule,+ MailerModule,+ ActionTokensModule,+ ],+})++export class AppModule {}+diff --git a/src/auth/auth.controller.spec.ts b/src/auth/auth.controller.spec.tsnew file mode 100644index 000000000..6f8bc5e16--- /dev/null+++ b/src/auth/auth.controller.spec.ts@@ -0,0 +1,18 @@+import { Test, TestingModule } from '@nestjs/testing'+import { AuthController } from './auth.controller'++describe('AuthController', () => {+ let controller: AuthController++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ controllers: [AuthController],+ }).compile()++ controller = module.get<AuthController>(AuthController)+ })++ it('should be defined', () => {+ expect(controller).toBeDefined()+ })+})diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsnew file mode 100644index 000000000..e8ba3fd1a--- /dev/null+++ b/src/auth/auth.controller.ts@@ -0,0 +1,150 @@+import {+ Controller, Post, Body, Req, Get, Param, BadRequestException, UseGuards,+} from '@nestjs/common'+import { Request } from 'express'+import { ApiTags } from '@nestjs/swagger'++import { AuthService } from './auth.service'+import { UserLoginDTO } from './dto/user-login.dto'+import { SignupUserDTO } from './dto/user-signup.dto'+import { UserService } from '../user/user.service'+import { MailerService } from '../mailer/mailer.service'+import { ActionTokensService } from '../action-tokens/action-tokens.service'+import { ActionTokenType } from '../action-tokens/action-token.entity'+import { User, UserType } from '../user/entities/user.entity'+import { PasswordChangeDTO } from './dto/password-change.dto'+import { RequestPasswordChangeDTO } from './dto/request-pass-change.dto'+import { RolesGuard } from '../common/guards/roles.guard'+import { Roles } from '../common/decorators/roles.decorator'+import { CurrentUserId } from '../common/decorators/current-user-id.decorator'+import { LetterTemplate } from '../mailer/lettter'+import { AppLoggerService } from '../logger/logger.service'+++@ApiTags('Auth')+@Controller('auth')+export class AuthController {+ constructor(+ private authService: AuthService,+ private userService: UserService,+ private mailerService: MailerService,+ private actionTokensService: ActionTokensService,+ private readonly logger: AppLoggerService+ ) {}++ @Get('/me')+ @UseGuards(RolesGuard)+ @Roles(UserType.FREE)+ async me(@CurrentUserId() user_id: string): Promise<User> {+ this.logger.log({ user_id }, 'GET /auth/me')+ return this.userService.findOneWhere({ id: user_id })+ }++ @Post('/login')+ async loginUser(@Body() userLoginDTO: UserLoginDTO, @Req() request: Request): Promise<any> {+ this.logger.log({ userLoginDTO }, 'POST /auth/login')+ // await this.authService.checkCaptcha(userLoginDTO.recaptcha)++ const user = await this.authService.validateUser(userLoginDTO.email, userLoginDTO.password)+ return await this.authService.login(user, request.res)+ }++ @Post('/register')+ async register(@Body() userDTO: SignupUserDTO, /*@Body('recaptcha') recaptcha: string,*/ @Req() request: Request): Promise<any> {+ this.logger.log({ userDTO }, 'POST /auth/register')++ // await this.authService.checkCaptcha(recaptcha)+ this.userService.validatePassword(userDTO.password)+ userDTO.password = this.authService.hashPassword(userDTO.password)++ try {+ const user = await this.userService.create(userDTO)+ const actionToken = await this.actionTokensService.createForUser(user, ActionTokenType.EMAIL_VERIFICATION)+ const url = `${request.headers.origin}/verify/${actionToken.id}`+ await this.mailerService.sendEmail(userDTO.email, LetterTemplate.SignUp, { url })++ return await this.authService.login(user, request.res)+ } catch(e){+ if(e.code === 'ER_DUP_ENTRY'){+ if(e.sqlMessage.includes(userDTO.email)) {+ throw new BadRequestException('A user with this email already exists')+ }+ }+ }+ }++ @Get('/verify/:id')+ async verify(@Param('id') id: string): Promise<User> {+ this.logger.log({id}, 'GET /auth/verify/:id')+ let actionToken++ try {+ actionToken = await this.actionTokensService.find(id)+ } catch {+ throw new BadRequestException('Wrong token')+ }++ if(actionToken.action === ActionTokenType.EMAIL_VERIFICATION){+ await this.userService.update(actionToken.user.id, { ...actionToken.user, isActive: true})+ await this.actionTokensService.delete(actionToken.id)+ return+ }+ }++ @Get('/change-email/:id')+ async changeEmail(@Param('id') id: string): Promise<User> {+ this.logger.log({id}, 'GET /auth/change-emai/:id')+ let actionToken++ try {+ actionToken = await this.actionTokensService.find(id)+ } catch {+ throw new BadRequestException('Wrong token')+ }++ if(actionToken.action === ActionTokenType.EMAIL_CHANGE){+ await this.userService.update(actionToken.user.id,+ { ...actionToken.user, email: actionToken.newValue })+ await this.mailerService.sendEmail(actionToken.user.email,+ LetterTemplate.MailAddressHadChanged, actionToken.user.locale)+ await this.actionTokensService.delete(actionToken.id)+ return+ }+ }++ @Post('/reset-password')+ async requestReset(@Body() body: RequestPasswordChangeDTO, @Req() request: Request): Promise<string> {+ const user = await this.userService.findOneWhere({ email: body.email })++ if(!user){+ return 'A password reset URL has been sent to your email!'+ }++ const actionToken = await this.actionTokensService.createForUser(user, ActionTokenType.PASSWORD_RESET)+ const url = `${request.headers.origin}/password-reset/${actionToken.id}`++ await this.mailerService.sendEmail(body.email, LetterTemplate.ConfirmPasswordChange, { url })+ return 'A password reset URL has been sent to your email!'+ }++ @Post('/password-reset/:id')+ async reset(@Param('id') id: string, @Body() body: PasswordChangeDTO): Promise<User> {+ this.logger.log({ id }, 'POST /auth/password-reset/:id')+ this.userService.validatePassword(body.password)+ let actionToken++ try {+ actionToken = await this.actionTokensService.find(id)+ } catch {+ throw new BadRequestException('Wrong token')+ }++ if(actionToken.action === ActionTokenType.PASSWORD_RESET) {+ const password = this.authService.hashPassword(body.password)++ await this.userService.update(actionToken.user.id, { ...actionToken.user, password})+ await this.actionTokensService.delete(actionToken.id)+ return+ }+ }+}diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.tsnew file mode 100644index 000000000..e3d7fe199--- /dev/null+++ b/src/auth/auth.module.ts@@ -0,0 +1,20 @@+import { Module, forwardRef } from '@nestjs/common'+import { AuthService } from './auth.service'+import { UserModule } from '../user/user.module'+import { AuthController } from './auth.controller'+import { MailerModule } from '../mailer/mailer.module'+import { ActionTokensModule } from '../action-tokens/action-tokens.module'+import { AppLoggerModule } from '../logger/logger.module'++@Module({+ imports: [+ forwardRef(() => UserModule),+ MailerModule,+ ActionTokensModule,+ AppLoggerModule+ ],+ controllers: [AuthController],+ providers: [AuthService],+ exports: [AuthService],+})+export class AuthModule {}\ No newline at end of filediff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsnew file mode 100644index 000000000..25685647a--- /dev/null+++ b/src/auth/auth.service.ts@@ -0,0 +1,50 @@+import { Injectable, UnprocessableEntityException } from '@nestjs/common'+import { sign } from 'jsonwebtoken'+import { Response } from 'express'+import * as bcrypt from 'bcrypt'++import { UserService } from '../user/user.service'+import { User } from '../user/entities/user.entity'+import { JWT_LIFE_TIME } from '../common/constants'++@Injectable()+export class AuthService {+ constructor(+ private userService: UserService,+ ) {}++ hashPassword(pass: string): string {+ return bcrypt.hashSync(pass, process.env.PASSWORD_SALT)+ }++ checkPassword(passToCheck: string, hashedPass: string): boolean {+ const hashedPassToCheck = this.hashPassword(passToCheck)++ return hashedPassToCheck === hashedPass+ }++ async validateUser(email: string, pass: string): Promise<User> {+ const user = await this.userService.findOneWhere({ email })++ if (user && this.checkPassword(pass, user.password)) {+ return user+ }++ throw new UnprocessableEntityException('Email or password is incorrect')+ }++ async login(user: User, res: Response): Promise<any> {+ const options = {+ httpOnly: true,+ sameSite: false,+ hostonly: true+ }++ const token = sign({ user_id: user.id }, process.env.JWT_SECRET, {+ expiresIn: JWT_LIFE_TIME,+ })++ res.cookie('token', token, options)+ return { access_token: token, user }+ }+}diff --git a/src/auth/dto/password-change.dto.ts b/src/auth/dto/password-change.dto.tsnew file mode 100644index 000000000..6d7f68c3c--- /dev/null+++ b/src/auth/dto/password-change.dto.ts@@ -0,0 +1,8 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty } from 'class-validator'++export class PasswordChangeDTO {+ @ApiProperty({ example: 'your_password123' })+ @IsNotEmpty()+ password: string+}diff --git a/src/auth/dto/request-pass-change.dto.ts b/src/auth/dto/request-pass-change.dto.tsnew file mode 100644index 000000000..e11f2a3ec--- /dev/null+++ b/src/auth/dto/request-pass-change.dto.ts@@ -0,0 +1,8 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsEmail } from 'class-validator'++export class RequestPasswordChangeDTO {+ @ApiProperty({example: '[email protected]'})+ @IsEmail()+ email: string+}\ No newline at end of filediff --git a/src/auth/dto/user-login.dto.ts b/src/auth/dto/user-login.dto.tsnew file mode 100644index 000000000..5adf89778--- /dev/null+++ b/src/auth/dto/user-login.dto.ts@@ -0,0 +1,16 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsEmail, IsNotEmpty } from 'class-validator'++export class UserLoginDTO {+ @ApiProperty({ example: '[email protected]', required: true })+ @IsEmail()+ email: string++ @ApiProperty({ example: 'your_password123', required: true })+ @IsNotEmpty()+ password: string++ // @ApiProperty()+ // @IsNotEmpty()+ // recaptcha: string+}diff --git a/src/auth/dto/user-signup.dto.ts b/src/auth/dto/user-signup.dto.tsnew file mode 100644index 000000000..046abd7b5--- /dev/null+++ b/src/auth/dto/user-signup.dto.ts@@ -0,0 +1,20 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsEmail, IsNotEmpty, IsEmpty, IsDate } from 'class-validator'+// import { UserRole, Locale } from '../../users/entities/user.entity'++export class SignupUserDTO {+ @ApiProperty({ example: '[email protected]', required: true })+ @IsEmail()+ email: string++ @ApiProperty({ example: 'your_password123', required: true })+ @IsNotEmpty()+ password: string++ // @IsEmpty()+ // role: UserRole++ @ApiProperty()+ @IsNotEmpty()+ tos: Date+}\ No newline at end of filediff --git a/src/auth/jwt-payload.interface.ts b/src/auth/jwt-payload.interface.tsnew file mode 100644index 000000000..966898ee0--- /dev/null+++ b/src/auth/jwt-payload.interface.ts@@ -0,0 +1,3 @@+export interface JwtPayload {+ user_id: string+}\ No newline at end of filediff --git a/src/auth/jwt.strategy.ts b/src/auth/jwt.strategy.tsnew file mode 100644index 000000000..3ef429f5c--- /dev/null+++ b/src/auth/jwt.strategy.ts@@ -0,0 +1,19 @@+import { ExtractJwt, Strategy } from 'passport-jwt'+import { PassportStrategy } from '@nestjs/passport'+import { Injectable } from '@nestjs/common'+import { JwtPayload } from './jwt-payload.interface'++@Injectable()+export class JwtStrategy extends PassportStrategy(Strategy) {+ constructor() {+ super({+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),+ ignoreExpiration: false,+ secretOrKey: process.env.JWT_SECRET,+ })+ }++ async validate(payload: JwtPayload): Promise<JwtPayload> {+ return { user_id: payload.user_id }+ }+}\ No newline at end of filediff --git a/src/common/constants.ts b/src/common/constants.tsnew file mode 100644index 000000000..7ad7fa607--- /dev/null+++ b/src/common/constants.ts@@ -0,0 +1,2 @@+export const JWT_LIFE_TIME = 7 * 24 * 60 * 60+export const HISTORY_LIFE_TIME_DAYS = 30\ No newline at end of filediff --git a/src/common/decorators/current-user-id.decorator.ts b/src/common/decorators/current-user-id.decorator.tsnew file mode 100644index 000000000..3946aa91f--- /dev/null+++ b/src/common/decorators/current-user-id.decorator.ts@@ -0,0 +1,23 @@+import { createParamDecorator, ExecutionContext } from '@nestjs/common'+import { Request } from 'express'+import { verify } from 'jsonwebtoken'+import { ExtractJwt } from 'passport-jwt'++export const CurrentUserId = createParamDecorator(+ async (data: unknown, context: ExecutionContext) => {+ const request: Request = context.switchToHttp().getRequest()+ let token = ''+ if(request.cookies['token']) {+ token = request.cookies['token']+ } else {+ const extract = ExtractJwt.fromAuthHeaderAsBearerToken()+ token = extract(request)+ }+ try {+ const decoded: any = verify(token, process.env.JWT_SECRET)+ return decoded.userId+ } catch {+ return null+ }+ },+)\ No newline at end of filediff --git a/src/common/decorators/roles.decorator.ts b/src/common/decorators/roles.decorator.tsnew file mode 100644index 000000000..8bfc177ab--- /dev/null+++ b/src/common/decorators/roles.decorator.ts@@ -0,0 +1,3 @@+import { SetMetadata, CustomDecorator } from '@nestjs/common'++export const Roles = (...roles: string[]): CustomDecorator<string> => SetMetadata('roles', roles)\ No newline at end of filediff --git a/src/common/guards/roles.guard.ts b/src/common/guards/roles.guard.tsnew file mode 100644index 000000000..9cb0fa449--- /dev/null+++ b/src/common/guards/roles.guard.ts@@ -0,0 +1,47 @@+import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common'+import { Reflector } from '@nestjs/core'+import { Request } from 'express'+import { verify } from 'jsonwebtoken'+import { ExtractJwt } from 'passport-jwt'++import { UserService } from '../../user/user.service'+import { User } from '../../user/entities/user.entity'++@Injectable()+export class RolesGuard implements CanActivate {+ constructor(+ private reflector: Reflector,+ private userService: UserService,+ ) {}++ async canActivate(context: ExecutionContext): Promise<boolean> {+ const secret = process.env.JWT_SECRET+ const roles = this.reflector.get<string[]>('roles', context.getHandler())+ if (!roles) {+ return true+ }++ const request: Request = context.switchToHttp().getRequest()+ let token = ''+ if(request.cookies['token']) {+ token = request.cookies['token']+ } else {+ const extract = ExtractJwt.fromAuthHeaderAsBearerToken()+ token = extract(request)+ }++ try {+ const decoded: any = verify(token, secret)++ if(decoded){+ let user: User = await this.userService.findOneWhere({ id: decoded.user_id })+ const hasRole = user.roles.some(role => !!roles.find(item => item === role))+ return hasRole+ }+ } catch {+ throw new UnauthorizedException()+ }+ }+++}\ No newline at end of filediff --git a/src/common/pagination/index.ts b/src/common/pagination/index.tsnew file mode 100644index 000000000..9d91dd9ca--- /dev/null+++ b/src/common/pagination/index.ts@@ -0,0 +1,3 @@+export * from './pagination.options.interface'+export * from './pagination.results.interface'+export * from './pagination'\ No newline at end of filediff --git a/src/common/pagination/pagination.options.interface.ts b/src/common/pagination/pagination.options.interface.tsnew file mode 100644index 000000000..2b0d713d8--- /dev/null+++ b/src/common/pagination/pagination.options.interface.ts@@ -0,0 +1,4 @@+export interface PaginationOptionsInterface {+ take: number;+ skip: number;+}\ No newline at end of filediff --git a/src/common/pagination/pagination.results.interface.ts b/src/common/pagination/pagination.results.interface.tsnew file mode 100644index 000000000..53b1c4e96--- /dev/null+++ b/src/common/pagination/pagination.results.interface.ts@@ -0,0 +1,6 @@+export interface PaginationResultInterface<PaginationEntity> {+ results: PaginationEntity[];+ total: number;+ next?: string;+ previous?: string;+}\ No newline at end of filediff --git a/src/common/pagination/pagination.ts b/src/common/pagination/pagination.tsnew file mode 100644index 000000000..b3124ac5b--- /dev/null+++ b/src/common/pagination/pagination.ts@@ -0,0 +1,13 @@+import { PaginationResultInterface } from './pagination.results.interface'++export class Pagination<PaginationEntity> {+ public results: PaginationEntity[];+ public page_total: number;+ public total: number;++ constructor(paginationResults: PaginationResultInterface<PaginationEntity>) {+ this.results = paginationResults.results+ this.page_total = paginationResults.results.length+ this.total = paginationResults.total+ }+}\ No newline at end of filediff --git a/src/logger/logger.module.ts b/src/logger/logger.module.tsnew file mode 100644index 000000000..d690bb97e--- /dev/null+++ b/src/logger/logger.module.ts@@ -0,0 +1,8 @@+import { Module } from '@nestjs/common'+import { AppLoggerService } from './logger.service'++@Module({+ providers: [AppLoggerService],+ exports: [AppLoggerService],+})+export class AppLoggerModule {}\ No newline at end of filediff --git a/src/logger/logger.service.ts b/src/logger/logger.service.tsnew file mode 100644index 000000000..c1e04224c--- /dev/null+++ b/src/logger/logger.service.ts@@ -0,0 +1,5 @@+import { Logger } from '@nestjs/common'++export class AppLoggerService extends Logger {++}\ No newline at end of filediff --git a/src/mailer/lettter.ts b/src/mailer/lettter.tsnew file mode 100644index 000000000..3a682911c--- /dev/null+++ b/src/mailer/lettter.ts@@ -0,0 +1,8 @@+export enum LetterTemplate {+ SignUp = 'guest_sign-up',+ ConfirmPasswordChange = 'password-change_confirmation',+ PasswordChanged = 'password-change_information',+ MailAddressChangeConfirmation = 'mailaddress-change_confirmation',+ MailAddressHadChanged = 'mailaddress-change_information',+ PasswordChangeRequest = 'password-change_request',+}\ No newline at end of filediff --git a/src/mailer/mailer.module.ts b/src/mailer/mailer.module.tsnew file mode 100644index 000000000..c564e269a--- /dev/null+++ b/src/mailer/mailer.module.ts@@ -0,0 +1,10 @@+import { Module } from '@nestjs/common'+import { AppLoggerModule } from 'src/logger/logger.module'+import { MailerService } from './mailer.service'++@Module({+ providers: [MailerService],+ exports: [MailerService],+ imports: [AppLoggerModule]+})+export class MailerModule {}diff --git a/src/mailer/mailer.service.spec.ts b/src/mailer/mailer.service.spec.tsnew file mode 100644index 000000000..d16256003--- /dev/null+++ b/src/mailer/mailer.service.spec.ts@@ -0,0 +1,18 @@+import { Test, TestingModule } from '@nestjs/testing'+import { MailerService } from './mailer.service'++describe('MailerService', () => {+ let service: MailerService++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [MailerService],+ }).compile()++ service = module.get<MailerService>(MailerService)+ })++ it('should be defined', () => {+ expect(service).toBeDefined()+ })+})diff --git a/src/mailer/mailer.service.ts b/src/mailer/mailer.service.tsnew file mode 100644index 000000000..eca11d9bc--- /dev/null+++ b/src/mailer/mailer.service.ts@@ -0,0 +1,100 @@+import { Injectable } from '@nestjs/common'+import * as nodemailer from 'nodemailer'+import handlebars from 'handlebars'+import { LetterTemplate } from './lettter'+import fs = require('fs')+import path = require('path')+import { AppLoggerService } from 'src/logger/logger.service'++const TEMPLATES_PATH = path.join(__dirname, '..', 'common', 'templates')+const metaInfoJson = {+ [LetterTemplate.SignUp]: {+ subject: {+ EN: 'Please verify your account registration',+ },+ },+ [LetterTemplate.ConfirmPasswordChange]: {+ subject: {+ EN: 'Please confirm the password change',+ },+ },+ [LetterTemplate.MailAddressChangeConfirmation]: {+ subject: {+ EN: 'Please confirm the new e-mail address',+ },+ },+ [LetterTemplate.MailAddressHadChanged]: {+ subject: {+ EN: 'A new e-mail-address has been saved',+ },+ },+ [LetterTemplate.PasswordChangeRequest]: {+ subject: {+ EN: 'Changing your password',+ },+ },+ [LetterTemplate.PasswordChanged]: {+ subject: {+ EN: 'Your password was successfully changed',+ },+ },+}++interface Params {+ [name: string]: any+}++@Injectable()+export class MailerService {+ constructor(+ private readonly logger: AppLoggerService+ ) {}++ async sendEmail(email: string, templateName: LetterTemplate, params: Params = null): Promise<void> {+ try {+ const templatePath = TEMPLATES_PATH ++ '/' + 'EN' ++ '/' + templateName + '_en.html'++ const letter = fs.readFileSync(templatePath, { encoding: 'utf-8' })+ const subject = metaInfoJson[templateName]['subject']['EN']+ const template = handlebars.compile(letter)+ const htmlToSend = template(params)++ const transporter = nodemailer.createTransport({+ host: process.env.SMTP_HOST,+ port: Number(process.env.SMTP_PORT),+ auth: {+ user: process.env.SMTP_USER,+ pass: process.env.SMTP_PASSWORD,+ },+ })++ const message = {+ from: {+ name: 'Studentenwerk Frankfurt',+ address: process.env.FROM_EMAIL+ },+ to: email,+ subject: subject,+ html: htmlToSend,+ attachments: [],+ }++ if (process.env.SMTP_MOCK) {+ this.logger.log(message, 'sendEmail')+ } else {+ transporter.sendMail(message, (err, info) => {+ if (err) {+ console.log('Error in transporter.sendMail', err)+ console.log('Info in transporter.sendMail', info)++ return process.exit(1)+ }+ })+ }+ } catch (error) {+ console.log(error)+ }+ }+}\ No newline at end of filediff --git a/src/main.ts b/src/main.tsnew file mode 100644index 000000000..ca8903e99--- /dev/null+++ b/src/main.ts@@ -0,0 +1,26 @@+import { NestFactory } from '@nestjs/core'+import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'+import { ValidationPipe } from '@nestjs/common'+import * as cookieParser from 'cookie-parser'++import { AppModule } from './app.module'++async function bootstrap() {+ const app = await NestFactory.create(AppModule)+ app.enableCors()+ app.use(cookieParser())+ app.useGlobalPipes(new ValidationPipe())++ const options = new DocumentBuilder()+ .setTitle('Analytics API')+ .addTag('Auth')+ .addTag('User')+ .setVersion('1.0')+ .build()+ const document = SwaggerModule.createDocument(app, options)++ SwaggerModule.setup('', app, document)++ await app.listen(3005)+}+bootstrap();diff --git a/src/task-manager/task-manager.module.ts b/src/task-manager/task-manager.module.tsnew file mode 100644index 000000000..b59d45b9f--- /dev/null+++ b/src/task-manager/task-manager.module.ts@@ -0,0 +1,9 @@+import { Module, HttpModule } from '@nestjs/common'+import { TaskManagerService } from './task-manager.service'+import { MailerModule } from '../mailer/mailer.module'++@Module({+ imports: [MailerModule, HttpModule],+ providers: [TaskManagerService]+})+export class TaskManagerModule {}diff --git a/src/task-manager/task-manager.service.spec.ts b/src/task-manager/task-manager.service.spec.tsnew file mode 100644index 000000000..82e663ab2--- /dev/null+++ b/src/task-manager/task-manager.service.spec.ts@@ -0,0 +1,18 @@+import { Test, TestingModule } from '@nestjs/testing'+import { TaskManagerService } from './task-manager.service'++describe('TaskManagerService', () => {+ let service: TaskManagerService++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [TaskManagerService],+ }).compile()++ service = module.get<TaskManagerService>(TaskManagerService)+ });++ it('should be defined', () => {+ expect(service).toBeDefined()+ })+})diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.tsnew file mode 100644index 000000000..62daed5c1--- /dev/null+++ b/src/task-manager/task-manager.service.ts@@ -0,0 +1,18 @@+import { Injectable, HttpService } from '@nestjs/common'+import { Cron, CronExpression } from '@nestjs/schedule'+// import * as moment from 'moment'++import { MailerService } from '../mailer/mailer.service'++@Injectable()+export class TaskManagerService {+ constructor(+ private readonly mailerService: MailerService,+ private readonly httpService: HttpService+ ) {}++ @Cron(CronExpression.EVERY_6_MONTHS)+ async someTask(): Promise<void> {++ }+}\ No newline at end of filediff --git a/src/user/dto/user.dto.ts b/src/user/dto/user.dto.tsnew file mode 100644index 000000000..59aa5b10c--- /dev/null+++ b/src/user/dto/user.dto.ts@@ -0,0 +1,12 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsEmail, IsNotEmpty } from 'class-validator'++export class UserProfileDTO {+ @ApiProperty({ example: '[email protected]', required: true })+ @IsEmail()+ email: string++ @ApiProperty({ example: 'your_password123', required: true })+ @IsNotEmpty()+ password: string+}diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsnew file mode 100644index 000000000..f8d44659a--- /dev/null+++ b/src/user/entities/user.entity.ts@@ -0,0 +1,37 @@+import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm'+import { ActionToken } from 'src/action-tokens/action-token.entity'++export enum UserType {+ FREE = 'free',+ TIER_1 = 'tier_1',+ TIER_2 = 'tier_2',+ ENTERPRISE = 'enterprise',+ ADMIN = 'admin'+}++export const MAX_EMAIL_REQUESTS = 4 // 1 confirmation email on sign up + 3 additional ones++@Entity()+export class User {+ @PrimaryGeneratedColumn('uuid')+ id: string++ @Column({+ type: 'set',+ enum: UserType,+ default: UserType.FREE+ })+ roles: UserType[]++ @Column('varchar', { length: 254, unique: true })+ email: string++ @Column('varchar', { length: 200, default: '' })+ password: string++ @Column({ default: true })+ isActive: boolean++ @OneToMany(() => ActionToken, actionToken => actionToken.user)+ actionTokens: ActionToken[]+}\ No newline at end of filediff --git a/src/user/user.controller.spec.ts b/src/user/user.controller.spec.tsnew file mode 100644index 000000000..c4723dce1--- /dev/null+++ b/src/user/user.controller.spec.ts@@ -0,0 +1,18 @@+import { Test, TestingModule } from '@nestjs/testing';+import { UserController } from './user.controller';++describe('UserController', () => {+ let controller: UserController++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ controllers: [UserController],+ }).compile()++ controller = module.get<UserController>(UserController)+ })++ it('should be defined', () => {+ expect(controller).toBeDefined()+ })+})diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsnew file mode 100644index 000000000..00a9db3c3--- /dev/null+++ b/src/user/user.controller.ts@@ -0,0 +1,187 @@+import {+ Controller, Query, Req, Body, Param, Get, Post, Put, Delete, HttpCode, BadRequestException, UseGuards+} from '@nestjs/common'+import { Request } from 'express'+import { ApiTags, ApiQuery } from '@nestjs/swagger'++import { UserService } from './user.service'+// import { UserType } from './entities/user.entity'+// import { Roles } from '../common/decorators/roles.decorator'+// import { Pagination } from '../common/pagination/pagination'+// import { User, UserType, MAX_EMAIL_REQUESTS } from './entities/user.entity'+// import { CustomerDto } from './dto/customer.dto'+import { RolesGuard } from 'src/common/guards/roles.guard'+// import { UsersService } from '../users/users.service'+// import { UpdateCustomerDto } from './dto/update-customer'+// import { CurrentUserId } from 'src/common/decorators/current-user-id.decorator'+import { ActionTokensService } from '../action-tokens/action-tokens.service'+import { MailerService } from '../mailer/mailer.service'+// import { ActionTokenType } from '../action-tokens/action-token.entity'+import { AuthService } from '../auth/auth.service'+// import { LetterTemplate } from 'src/mailer/lettter'+import { AppLoggerService } from 'src/logger/logger.service'++@ApiTags('User')+@Controller('user')+@UseGuards(RolesGuard)+export class UserController {+ constructor(+ private readonly userService: UserService,+ private readonly authService: AuthService,+ private readonly actionTokensService: ActionTokensService,+ private readonly mailerService: MailerService,+ private readonly logger: AppLoggerService+ ) {}++ // @Get('/')+ // @ApiQuery({ name: 'take', required: false })+ // @ApiQuery({ name: 'skip', required: false })+ // @Roles(UserType.ADMIN)+ // async get(@Query('take') take: number | undefined, @Query('skip') skip: number | undefined):+ // Promise<Pagination<Customer> | Customer[]>+ // {+ // this.logger.log({take, skip}, 'GET /customers')+ // return await this.customersService.paginate({take, skip})+ // }++ // @Get('/search')+ // @ApiQuery({ name: 'query', required: false })+ // @Roles(UserType.ADMIN)+ // async searchCustomers(+ // @Query('query') query: string | undefined,+ // ) :Promise<Customer[]>+ // {+ // this.logger.log({query}, 'GET /customers/search')+ // return await this.customersService.search(query)+ // }++ // @Post('/')+ // @Roles(UserType.ADMIN)+ // async create(@Body() customerDto: CustomerDto): Promise<Customer> {+ // this.logger.log({customerDto}, 'POST /customers')+ // this.usersService.validatePassword(customerDto.password)+ // customerDto.password = this.authService.hashPassword(customerDto.password)+ // try {+ // const customer = await this.customersService.create({...customerDto, isActive: true})+ // return customer+ // } catch(e){+ // if(e.code === 'ER_DUP_ENTRY'){+ // if(e.sqlMessage.includes(customerDto.email)) {+ // throw new BadRequestException('User with this email already exists')+ // } else if(e.sqlMessage.includes(customerDto.phone)) {+ // throw new BadRequestException('User with this phone already exists')+ // }+ // }+ // }+ // }++ // @Delete('/:id')+ // @HttpCode(204)+ // @Roles(UserType.ADMIN)+ // async delete(@Param('id') id: string, @CurrentUserId() currentUserId: string):+ // Promise<any> {+ // this.logger.log({id, currentUserId}, 'DELETE /customers/:id')+ // const userToDelete = await this.customersService.findOneWhere({id})+ // if(!userToDelete){+ // throw new BadRequestException(`User with id ${id} does not exist`)+ // }+ // await this.customersService.checkIfDeletionAllowed(currentUserId)+ // await this.customersService.delete(id)+ // return+ // }++ // @Delete('/')+ // @HttpCode(204)+ // @Roles(UserType.FREE)+ // async deleteSelf(@CurrentUserId() currentUserId: string): Promise<any> {+ // this.logger.log({currentUserId}, 'DELETE /customers')+ // await this.customersService.checkIfDeletionAllowed(currentUserId)+ // await this.customersService.delete(currentUserId)+ // return+ // }++ // @Put('/:id')+ // @Roles(UserType.ADMIN)+ // async update(@Body() customerDto: UpdateCustomerDto, @Param('id') id: string): Promise<Customer> {+ // this.logger.log({customerDto, id}, 'DELETE /customers/:id')+ // if(customerDto.password) {+ // this.usersService.validatePassword(customerDto.password)+ // customerDto.password = this.authService.hashPassword(customerDto.password)+ // }+ // const customer = await this.customersService.findOneWhere({id})+ // if(!customer){+ // throw new BadRequestException('User does not exist')+ // }+ // try {+ // await this.customersService.update(id, {...customer, ...customerDto})+ // return this.customersService.findOneWhere({id})+ // } catch (e) {+ // if(e.code === 'ER_DUP_ENTRY'){+ // if(e.sqlMessage.includes(customerDto.email)) {+ // throw new BadRequestException('User with this email already exists')+ // } else if(e.sqlMessage.includes(customerDto.phone)) {+ // throw new BadRequestException('User with this phone already exists')+ // }+ // }+ // throw new BadRequestException(e.message)+ // }+ // }++ // @Post('/confirm_email')+ // @Roles(UserType.FREE)+ // async sendEmailConfirmation(@CurrentUserId() id: string, @Req() request: Request): Promise<boolean> {+ // this.logger.log({ id }, 'POST /confirm_email')++ // const customer = await this.customersService.findOneWhere({ id })+ // console.log(customer)+ // if (!customer || !customer.email || customer.isActive || customer.emailRequests >= MAX_EMAIL_REQUESTS) return false++ // const token = await this.actionTokensService.createForCustomer(customer, ActionTokenType.EMAIL_VERIFICATION, customer.email)+ // const url = `${request.headers.origin}/verify/${token.id}`++ // await this.customersService.update(id, { emailRequests: 1 + customer.emailRequests })+ // await this.mailerService.sendEmail(customer.email, LetterTemplate.SignUp, customer.locale, { url })+ // return true+ // }++ // @Put('/')+ // @Roles(UserType.FREE)+ // async updateCurrentCustomer(+ // @Body() customerDto: UpdateCustomerDto,+ // @CurrentUserId() customerId: string,+ // @Req() request: Request):+ // Promise<Customer> {+ // this.logger.log({customerDto, customerId}, 'PUT /customers')+ // const customer = await this.customersService.findOneWhere({id: customerId})+ // if(customerDto.password && customerDto.password.length > 0) {+ // this.usersService.validatePassword(customerDto.password)+ // customerDto.password = this.authService.hashPassword(customerDto.password)+ // await this.mailerService.sendEmail(customerDto.email, LetterTemplate.PasswordChanged, customerDto.locale )+ // }+ // try {+ // if(customerDto.email && customer.email !== customerDto.email) {+ // const userWithByEmail = this.customersService.findOneWhere({email: customerDto.email})+ // if(userWithByEmail){+ // customerDto.email = customer.email+ // } else {+ // throw new BadRequestException('User with this email already exists')+ // }+ // const token = await this.actionTokensService.createForCustomer(+ // customer, ActionTokenType.EMAIL_CHANGE, customerDto.email)+ // const url = `${request.headers.origin}/change-email/${token.id}`+ // await this.mailerService.sendEmail(+ // customer.email, LetterTemplate.MailAddressChangeConfirmation, customerDto.locale, { url })+ // }+ // await this.customersService.update(customerId, {...customerDto})++ // return this.customersService.findOneWhere({id: customerId})+ // } catch (e) {+ // if(e.code === 'ER_DUP_ENTRY'){+ // if(e.sqlMessage.includes(customerDto.phone)) {+ // throw new BadRequestException('User with this phone already exists')+ // }+ // }+ // throw new BadRequestException(e.message)+ // }+ // }+}diff --git a/src/user/user.module.ts b/src/user/user.module.tsnew file mode 100644index 000000000..cea68bce8--- /dev/null+++ b/src/user/user.module.ts@@ -0,0 +1,23 @@+import { Module, forwardRef } from '@nestjs/common'+import { TypeOrmModule } from '@nestjs/typeorm'++import { UserController } from './user.controller'+import { UserService } from './user.service'+import { User } from './entities/user.entity'+import { ActionTokensModule } from 'src/action-tokens/action-tokens.module'+import { MailerModule } from '../mailer/mailer.module'+import { AuthModule } from '../auth/auth.module'+import { AppLoggerModule } from '../logger/logger.module'++@Module({+ imports: [+ TypeOrmModule.forFeature([User]),+ ActionTokensModule, MailerModule,+ forwardRef(() => AuthModule),+ AppLoggerModule+ ],+ providers: [UserService],+ exports: [UserService],+ controllers: [UserController],+})+export class UserModule {}diff --git a/src/user/user.service.spec.ts b/src/user/user.service.spec.tsnew file mode 100644index 000000000..aab4c1dc0--- /dev/null+++ b/src/user/user.service.spec.ts@@ -0,0 +1,18 @@+import { Test, TestingModule } from '@nestjs/testing'+import { UserService } from './user.service'++describe('UserService', () => {+ let service: UserService++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [UserService],+ }).compile()++ service = module.get<UserService>(UserService)+ })++ it('should be defined', () => {+ expect(service).toBeDefined()+ })+})diff --git a/src/user/user.service.ts b/src/user/user.service.tsnew file mode 100644index 000000000..b3ffe765a--- /dev/null+++ b/src/user/user.service.ts@@ -0,0 +1,81 @@+import { Injectable, BadRequestException } from '@nestjs/common'+import { InjectRepository } from '@nestjs/typeorm'+import { Repository } from 'typeorm'++import { Pagination, PaginationOptionsInterface } from '../common/pagination'+import { User } from './entities/user.entity'+import { UserProfileDTO } from './dto/user.dto'++@Injectable()+export class UserService {+ constructor(+ @InjectRepository(User)+ private usersRepository: Repository<User>,+ ) {}++ async create(userDTO: UserProfileDTO | User): Promise<User> {+ return await this.usersRepository.save(userDTO)+ }++ async paginate(options: PaginationOptionsInterface): Promise<Pagination<User>> {+ const [results, total] = await this.usersRepository.findAndCount({+ take: options.take || 10,+ skip: options.skip || 0,+ })++ return new Pagination<User>({+ results,+ total,+ })+ }+++ async update(id: string, update: Record<string, unknown>): Promise<any> {+ return this.usersRepository.update({id}, update)+ }++ async delete(id: string): Promise<any> {+ return this.usersRepository.delete(id)+ }++ findOneWhere(where: Record<string, unknown>, relations: string[] = []): Promise<User> {+ return this.usersRepository.findOne({ where, relations })+ }++ findWhere(where: Record<string, unknown>): Promise<User[]> {+ return this.usersRepository.find({ where })+ }++ validatePassword(pass: string): string | null {+ if(!pass) {+ return null+ }++ const err = []+ if(pass.length > 50)+ err.push('Maximum password length is 50 letters')+ if(pass.length < 8)+ err.push('at least 8 characters')+ // if(!/[a-z]/.test(pass))+ // err.push('should contain at least one lower case')+ // if(!/[A-Z]/.test(pass))+ // err.push('should contain at least one upper case')+ // if(!(/[!@#$%^&*(),.?":{}|<>]/g.test(pass)))+ // err.push('should contain at least one symbol')++ if (err.length > 0)+ throw new BadRequestException(err)+ else {+ return null+ }+ }++ search(query: string): Promise<User[]> {+ return this.usersRepository+ .createQueryBuilder('user')+ .select()+ .where('email like :query', { query: `%${query}%` })+ .limit(5)+ .getMany()+ }+}diff --git a/test/app.e2e-spec.ts b/test/app.e2e-spec.tsnew file mode 100644index 000000000..50cda6233--- /dev/null+++ b/test/app.e2e-spec.ts@@ -0,0 +1,24 @@+import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import * as request from 'supertest';+import { AppModule } from './../src/app.module';++describe('AppController (e2e)', () => {+ let app: INestApplication;++ beforeEach(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();++ app = moduleFixture.createNestApplication();+ await app.init();+ });++ it('/ (GET)', () => {+ return request(app.getHttpServer())+ .get('/')+ .expect(200)+ .expect('Hello World!');+ });+});diff --git a/test/jest-e2e.json b/test/jest-e2e.jsonnew file mode 100644index 000000000..e9d912f3e--- /dev/null+++ b/test/jest-e2e.json@@ -0,0 +1,9 @@+{+ "moduleFileExtensions": ["js", "json", "ts"],+ "rootDir": ".",+ "testEnvironment": "node",+ "testRegex": ".e2e-spec.ts$",+ "transform": {+ "^.+\\.(t|j)s$": "ts-jest"+ }+}diff --git a/tsconfig.build.json b/tsconfig.build.jsonnew file mode 100644index 000000000..64f86c6bd--- /dev/null+++ b/tsconfig.build.json@@ -0,0 +1,4 @@+{+ "extends": "./tsconfig.json",+ "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]+}diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 000000000..bf10a2398--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,15 @@+{+ "compilerOptions": {+ "module": "commonjs",+ "declaration": true,+ "removeComments": true,+ "emitDecoratorMetadata": true,+ "experimentalDecorators": true,+ "allowSyntheticDefaultImports": true,+ "target": "es2017",+ "sourceMap": true,+ "outDir": "./dist",+ "baseUrl": "./",+ "incremental": true+ }+}