📈 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
Added route for registration
Yevhenii Kulisidie1ed96ea9dc0
diff --git a/.env.example b/.env.exampleindex ee482b14d..97d33bfe5 100644--- a/.env.example+++ b/.env.example@@ -2,6 +2,9 @@JWT_SECRET=SOME_SECRET_TOKENTWO_FACTOR_AUTHENTICATION_APP_NAME=Swetrix+# App+CLIENT_URL='http://localhost:3000'+# JWT Access TokenJWT_ACCESS_TOKEN_SECRET='jwt-access-token-secret'diff --git a/package.json b/package.jsonindex e85194bb4..4cad805d1 100644--- a/package.json+++ b/package.json@@ -28,11 +28,13 @@"@nestjs/common": "^9.2.1","@nestjs/config": "^2.2.0","@nestjs/core": "^9.2.1",+ "@nestjs/jwt": "^10.0.1","@nestjs/passport": "^9.0.0","@nestjs/platform-express": "^9.2.1","@nestjs/schedule": "^2.1.0","@nestjs/swagger": "^6.1.4","@nestjs/typeorm": "^9.0.1",+ "axios": "^1.2.2","bcrypt": "^5.1.0","blake3": "^2.1.7","body-parser": "^1.20.1",diff --git a/src/action-tokens/action-tokens.service.ts b/src/action-tokens/action-tokens.service.tsindex e0ef0af07..615e87833 100644--- a/src/action-tokens/action-tokens.service.ts+++ b/src/action-tokens/action-tokens.service.ts@@ -37,4 +37,16 @@ export class ActionTokensService {async delete(id: string): Promise<void> {await this.actionTokensRepository.delete(id)}++ public async createActionToken(+ userId: string,+ action: ActionTokenType,+ newValue?: string,+ ) {+ return await this.actionTokensRepository.save({+ user: { id: userId },+ action,+ newValue,+ })+ }}diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex 8deb8f429..f23d89dbb 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -3,9 +3,18 @@ import {UseFilters,UsePipes,ValidationPipe,+ Post,+ Body,+ Ip,+ ConflictException,+ Headers,} from '@nestjs/common'-import { ApiTags } from '@nestjs/swagger'-import { I18nValidationExceptionFilter } from 'nestjs-i18n'+import { ApiCreatedResponse, ApiOperation, ApiTags } from '@nestjs/swagger'+import { I18nValidationExceptionFilter, I18n, I18nContext } from 'nestjs-i18n'+import { checkRateLimit } from 'src/common/utils'+import { UserService } from 'src/user/user.service'+import { AuthService } from './auth.service'+import { RegisterDto } from './dtos'@ApiTags('Auth')@Controller({ path: 'auth', version: '1' })@@ -18,4 +27,52 @@ import { I18nValidationExceptionFilter } from 'nestjs-i18n'whitelist: true,}),)-export class AuthController {}+export class AuthController {+ constructor(+ private readonly userService: UserService,+ private readonly authService: AuthService,+ ) {}++ @ApiOperation({ summary: 'Register a new user' })+ @ApiCreatedResponse({+ description: 'User registered',+ type: RegisterDto.Response,+ })+ @Post('register')+ public async register(+ @Body() body: RegisterDto.Request,+ @I18n() i18n: I18nContext,+ @Headers() headers: unknown,+ @Ip() requestIp: string,+ ): Promise<RegisterDto.Response> {+ const ip =+ headers['x-forwarded-for'] || headers['cf-connecting-ip'] || requestIp++ await checkRateLimit(ip, 'register', 5)++ const user = await this.userService.findUser(body.email)++ if (user) {+ throw new ConflictException(i18n.t('user.emailAlreadyUsed'))+ }++ if (body.checkIfLeaked) {+ const isLeaked = await this.authService.checkIfLeaked(body.password)++ if (isLeaked) {+ throw new ConflictException(i18n.t('auth.leakedPassword'))+ }+ }++ const newUser = await this.authService.createUnverifiedUser(+ body.email,+ body.password,+ )++ const accessToken = await this.authService.generateJwtAccessToken(+ newUser.id,+ )++ return { accessToken }+ }+}diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.tsindex 7711bea6e..57b2471eb 100644--- a/src/auth/auth.module.ts+++ b/src/auth/auth.module.ts@@ -1,11 +1,21 @@import { Module } from '@nestjs/common'+import { JwtModule } from '@nestjs/jwt'import { PassportModule } from '@nestjs/passport'+import { ActionTokensModule } from 'src/action-tokens/action-tokens.module'+import { MailerModule } from 'src/mailer/mailer.module'+import { UserModule } from 'src/user/user.module'import { AuthController } from './auth.controller'import { AuthService } from './auth.service'import { JwtAccessTokenStrategy } from './strategies'@Module({- imports: [PassportModule],+ imports: [+ JwtModule.register({}),+ PassportModule,+ UserModule,+ ActionTokensModule,+ MailerModule,+ ],controllers: [AuthController],providers: [AuthService, JwtAccessTokenStrategy],})diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex 7f4cbbf63..ad5339418 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -1,4 +1,102 @@-import { Injectable } from '@nestjs/common'+import { Injectable, InternalServerErrorException } from '@nestjs/common'+import { ConfigService } from '@nestjs/config'+import { JwtService } from '@nestjs/jwt'+import axios from 'axios'+import { genSalt, hash } from 'bcrypt'+import { createHash } from 'crypto'+import { ActionTokenType } from 'src/action-tokens/action-token.entity'+import { ActionTokensService } from 'src/action-tokens/action-tokens.service'+import { LetterTemplate } from 'src/mailer/letter'+import { MailerService } from 'src/mailer/mailer.service'+import { UserService } from 'src/user/user.service'@Injectable()-export class AuthService {}+export class AuthService {+ constructor(+ private readonly userService: UserService,+ private readonly actionTokensService: ActionTokensService,+ private readonly configService: ConfigService,+ private readonly mailerService: MailerService,+ private readonly jwtService: JwtService,+ ) {}++ private async createSha1Hash(password: string): Promise<string> {+ return new Promise(resolve => {+ const sha1sum = createHash('sha1')+ .update(password)+ .digest('hex')+ .toUpperCase()+ resolve(sha1sum)+ })+ }++ private getFirstFiveChars(hash: string): string {+ return hash.slice(0, 5)+ }++ private async sendRequestToApi(hash: string) {+ const url = `https://api.pwnedpasswords.com/range/${hash}`+ const response = await axios.get(url)++ if (response.status !== 200) {+ throw new InternalServerErrorException()+ }++ return response.data+ }++ public async checkIfLeaked(password: string): Promise<boolean> {+ const sha1Hash = await this.createSha1Hash(password)+ const firstFiveChars = this.getFirstFiveChars(sha1Hash)+ const response = await this.sendRequestToApi(firstFiveChars)++ return response.includes(firstFiveChars)+ }++ public async hashPassword(password: string): Promise<string> {+ const salt = await genSalt(10)+ return await hash(password, salt)+ }++ private async sendVerificationEmail(userId: string, email: string) {+ const actionToken = await this.actionTokensService.createActionToken(+ userId,+ ActionTokenType.EMAIL_VERIFICATION,+ )++ const verificationLink = `${this.configService.get('CLIENT_URL')}/verify/${+ actionToken.id+ }`++ await this.mailerService.sendEmail(email, LetterTemplate.SignUp, {+ url: verificationLink,+ })+ }++ public async createUnverifiedUser(email: string, password: string) {+ const hashedPassword = await this.hashPassword(password)++ const user = await this.userService.createUser({+ email,+ password: hashedPassword, // Using the password field is incorrect.+ })++ await this.sendVerificationEmail(user.id, user.email)++ return user+ }++ public async generateJwtAccessToken(userId: string) {+ return await this.jwtService.signAsync(+ {+ sub: userId,+ isSecondFactorAuthenticated: false,+ },+ {+ algorithm: 'HS256',+ expiresIn: 60 * 30,+ secret: this.configService.get('JWT_ACCESS_TOKEN_SECRET'),+ },+ )+ }+}diff --git a/src/auth/strategies/access-token.strategy.ts b/src/auth/strategies/access-token.strategy.tsindex 3d15e5812..2d0a99e7f 100644--- a/src/auth/strategies/access-token.strategy.ts+++ b/src/auth/strategies/access-token.strategy.ts@@ -17,7 +17,7 @@ export class JwtAccessTokenStrategy extends PassportStrategy(})}- validate(payload: IJwtPayload) {+ public validate(payload: IJwtPayload) {return payload}}diff --git a/src/i18n/en/auth.json b/src/i18n/en/auth.jsonnew file mode 100644index 000000000..38c0438ff--- /dev/null+++ b/src/i18n/en/auth.json@@ -0,0 +1,3 @@+{+ "leakedPassword": "The password is in the leak database."+}diff --git a/src/i18n/en/user.json b/src/i18n/en/user.jsonnew file mode 100644index 000000000..b8acbdf29--- /dev/null+++ b/src/i18n/en/user.json@@ -0,0 +1,3 @@+{+ "emailAlreadyUsed": "Email already used."+}diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex 9cbcf9b4d..e0aa83ab9 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -138,4 +138,12 @@ export class UserService {.limit(5).getMany()}++ public async findUser(email: string) {+ return await this.usersRepository.findOne({ email }, { select: ['id'] })+ }++ public async createUser(user: Pick<User, 'email' | 'password'>) {+ return await this.usersRepository.save(user)+ }}