📈 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 a login route
Yevhenii Kulisidi698b66b5a81a
diff --git a/package.json b/package.jsonindex 4cad805d1..cc9251a92 100644--- a/package.json+++ b/package.json@@ -87,6 +87,7 @@"@types/node": "^18.11.18","@types/passport-jwt": "^3.0.8","@types/supertest": "^2.0.12",+ "@types/ua-parser-js": "^0.7.36","@typescript-eslint/eslint-plugin": "^5.47.1","@typescript-eslint/parser": "^5.47.1","eslint": "^8.30.0",diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex 7aa483ebe..a17e8a6d8 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -10,13 +10,19 @@ import {Ip,ConflictException,Headers,+ HttpCode,} from '@nestjs/common'-import { ApiCreatedResponse, ApiOperation, ApiTags } from '@nestjs/swagger'+import { ApiTags, ApiOperation, ApiCreatedResponse } 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 { RegisterRequestDto, RegisterResponseDto } from './dtos'+import {+ RegisterResponseDto,+ RegisterRequestDto,+ LoginResponseDto,+ LoginRequestDto,+} from './dtos'@ApiTags('Auth')@Controller({ path: 'auth', version: '1' })@@ -77,4 +83,38 @@ export class AuthController {return { accessToken }}++ @ApiOperation({ summary: 'Login a user' })+ @ApiCreatedResponse({+ description: 'User logged in',+ type: LoginResponseDto,+ })+ @Post('login')+ @HttpCode(200)+ public async login(+ @Body() body: LoginRequestDto,+ @I18n() i18n: I18nContext,+ @Headers() headers: unknown,+ @Ip() requestIp: string,+ ): Promise<LoginResponseDto> {+ const ip =+ headers['x-forwarded-for'] || headers['cf-connecting-ip'] || requestIp++ await checkRateLimit(ip, 'login', 10, 1800)++ const user = await this.authService.validateUser(body.email, body.password)++ if (!user) {+ throw new ConflictException(i18n.t('auth.invalidCredentials'))+ }++ await this.authService.sendTelegramNotification(user.id, headers, ip)++ const accessToken = await this.authService.generateJwtAccessToken(+ user.id,+ user.isTwoFactorAuthenticationEnabled,+ )++ return { accessToken }+ }}diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex ad5339418..99d53cb1a 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -2,17 +2,25 @@ 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 { genSalt, hash, compare } from 'bcrypt'+import { getCountry } from 'countries-and-timezones'import { createHash } from 'crypto'+import * as dayjs from 'dayjs'+import { InjectBot } from 'nestjs-telegraf'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 { User } from 'src/user/entities/user.entity'+import { TelegrafContext } from 'src/user/user.controller'import { UserService } from 'src/user/user.service'+import { Telegraf } from 'telegraf'+import { UAParser } from 'ua-parser-js'@Injectable()export class AuthService {constructor(+ @InjectBot() private readonly telegramBot: Telegraf<TelegrafContext>,private readonly userService: UserService,private readonly actionTokensService: ActionTokensService,private readonly configService: ConfigService,@@ -86,11 +94,14 @@ export class AuthService {return user}- public async generateJwtAccessToken(userId: string) {+ public async generateJwtAccessToken(+ userId: string,+ isSecondFactorAuthenticated = false,+ ) {return await this.jwtService.signAsync({sub: userId,- isSecondFactorAuthenticated: false,+ isSecondFactorAuthenticated,},{algorithm: 'HS256',@@ -99,4 +110,84 @@ export class AuthService {},)}++ public async validateUser(+ email: string,+ password: string,+ ): Promise<User | null> {+ const user = await this.userService.findUser(email)++ if (user && (await this.comparePassword(password, user.password))) {+ return user+ }++ return null+ }++ private async comparePassword(+ password: string,+ hashedPassword: string,+ ): Promise<boolean> {+ return await compare(password, hashedPassword)+ }++ public async sendTelegramNotification(+ userId: string,+ headers: unknown,+ ip: string,+ ) {+ const user = await this.userService.findUserById(userId)++ if (!user.telegramChatId) {+ return+ }++ const chat = await this.checkTelegramChatId(user.telegramChatId)++ if (!chat) {+ return+ }++ const headersInfo = await this.getHeadersInfo(headers)+ const loginDate = dayjs().utc().format('YYYY-MM-DD HH:mm:ss')+ const message =+ '⚠️ *New login detected* ⚠️\n\n' ++ `*Browser:* ${headersInfo.browser}\n` ++ `*Device:* ${headersInfo.device}\n` ++ `*OS:* ${headersInfo.os}\n` ++ `*Country:* ${headersInfo.country}\n` ++ `*IP:* ${ip}\n` ++ `*Date:* ${loginDate} (UTC)\n\n` ++ 'If this was not you, please change your password immediately.'+ await this.telegramBot.telegram.sendMessage(user.telegramChatId, message, {+ parse_mode: 'Markdown',+ })+ }++ private async getHeadersInfo(headers: unknown) {+ const ua = UAParser(headers['user-agent'])+ const browser = ua.browser.name || 'Unknown'+ const device = ua.device.type || 'Unknown'+ const os = ua.os.name || 'Unknown'+ const country =+ headers['cf-ipcountry'] === 'XX'+ ? 'Unknown'+ : headers['cf-ipcountry'] === 'T1'+ ? 'Unknown (Tor)'+ : headers['cf-ipcountry']+ ? getCountry(headers['cf-ipcountry']).name+ : 'Unknown'++ return {+ browser,+ device,+ os,+ country,+ }+ }++ public async checkTelegramChatId(chatId: string): Promise<boolean> {+ const chat = (await this.telegramBot.telegram.getChat(chatId)).id+ return Boolean(chat)+ }}diff --git a/src/auth/dtos/index.ts b/src/auth/dtos/index.tsindex 56290cc53..923dd2b34 100644--- a/src/auth/dtos/index.ts+++ b/src/auth/dtos/index.ts@@ -1 +1,2 @@export * from './register.dto'+export * from './login.dto'diff --git a/src/auth/dtos/login.dto.ts b/src/auth/dtos/login.dto.tsnew file mode 100644index 000000000..54fe0421f--- /dev/null+++ b/src/auth/dtos/login.dto.ts@@ -0,0 +1,10 @@+import { OmitType, PickType } from '@nestjs/swagger'+import { RegisterRequestDto, RegisterResponseDto } from './register.dto'++export class LoginRequestDto extends OmitType(RegisterRequestDto, [+ 'checkIfLeaked',+] as const) {}++export class LoginResponseDto extends PickType(RegisterResponseDto, [+ 'accessToken',+] as const) {}diff --git a/src/i18n/en/auth.json b/src/i18n/en/auth.jsonindex 38c0438ff..504fb34ad 100644--- a/src/i18n/en/auth.json+++ b/src/i18n/en/auth.json@@ -1,3 +1,4 @@{- "leakedPassword": "The password is in the leak database."+ "leakedPassword": "The password is in the leak database.",+ "invalidCredentials": "Incorrect email or password."}diff --git a/src/user/user.service.ts b/src/user/user.service.tsindex e0aa83ab9..747639d00 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -140,10 +140,14 @@ export class UserService {}public async findUser(email: string) {- return await this.usersRepository.findOne({ email }, { select: ['id'] })+ return await this.usersRepository.findOne({ email })}public async createUser(user: Pick<User, 'email' | 'password'>) {return await this.usersRepository.save(user)}++ public async findUserById(id: string) {+ return await this.usersRepository.findOne({ id })+ }}