Skip to content

📈 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!

All other modules cleared

Yevhenii Kulisidi540f33fa0685
diff --git a/.env.example b/.env.example
index 4bfb7a80d..385a9b8e3 100644
--- a/.env.example
+++ b/.env.example
@@ -1,5 +1,4 @@
# Auth
-JWT_SECRET=SOME_SECRET_TOKEN
TWO_FACTOR_AUTHENTICATION_APP_NAME=Swetrix
# App
diff --git a/Dockerfile b/Dockerfile
index 3f7b82781..a374070ab 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -7,7 +7,6 @@ RUN npm i -g pnpm && pnpm i && npm run deploy
#Stage 2
FROM node:lts-alpine as run
ENV TZ=UTC \
- JWT_SECRET=SOME_SECRET_TOKEN \
MYSQL_HOST=localhost \
MYSQL_USER=root \
MYSQL_ROOT_PASSWORD=password \
@@ -24,7 +23,7 @@ ENV TZ=UTC \
API_ORIGINS=\
PASSWORD=12345678 \
- SMTP_MOCK=true \
+ SMTP_MOCK=true \
SELFHOSTED=true
RUN apk add --no-cache tzdata && cp /usr/share/zoneinfo/$TZ /etc/localtime
WORKDIR /app
diff --git a/README.md b/README.md
index 680b2f7e6..9d7b9d9a5 100644
--- a/README.md
+++ b/README.md
@@ -42,9 +42,6 @@ Then fill out the Environment Variables below accordingly.
Below you will find the Environment Variables that are required to run the API. The values next to them are their default values. You can change them to your own values or just not set them if they suit you anyway. (e.g. Ports, Username, etc.)
-#### Security
-
-`JWT_SECRET`=SOME_SECRET_TOKEN
#### MySQL Database
diff --git a/src/app.module.ts b/src/app.module.ts
index bc83ea9eb..be29adf4c 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -4,7 +4,6 @@ import { ConfigModule } from '@nestjs/config'
import { ScheduleModule } from '@nestjs/schedule'
import { TelegrafModule } from 'nestjs-telegraf'
-import { OldAuthModule } from './old-auth/auth.module'
import { UserModule } from './user/user.module'
import { AnalyticsModule } from './analytics/analytics.module'
import { ProjectModule } from './project/project.module'
@@ -36,7 +35,6 @@ const modules = [
I18nModule.forRootAsync(getI18nConfig()),
ScheduleModule.forRoot(),
TaskManagerModule,
- OldAuthModule,
UserModule,
MailerModule,
ActionTokensModule,
diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts
index 31f7b74ae..1497e2e30 100644
--- a/src/auth/auth.module.ts
+++ b/src/auth/auth.module.ts
@@ -1,4 +1,4 @@
-import { Module } from '@nestjs/common'
+import { forwardRef, Module } from '@nestjs/common'
import { JwtModule } from '@nestjs/jwt'
import { PassportModule } from '@nestjs/passport'
import { ActionTokensModule } from 'src/action-tokens/action-tokens.module'
@@ -12,12 +12,13 @@ import { JwtAccessTokenStrategy, JwtRefreshTokenStrategy } from './strategies'
imports: [
JwtModule.register({}),
PassportModule,
- UserModule,
+ forwardRef(() => UserModule),
ActionTokensModule,
MailerModule,
ActionTokensModule,
],
controllers: [AuthController],
providers: [AuthService, JwtAccessTokenStrategy, JwtRefreshTokenStrategy],
+ exports: [AuthService],
})
export class AuthModule {}
diff --git a/src/old-auth/auth.controller.spec.ts b/src/old-auth/auth.controller.spec.ts
deleted file mode 100644
index c41754b43..000000000
--- a/src/old-auth/auth.controller.spec.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { getRepositoryToken } from '@nestjs/typeorm'
-import { OldAuthController } from './auth.controller'
-import { UserService } from '../user/user.service'
-import { OldAuthService } from './auth.service'
-import { MailerService } from '../mailer/mailer.service'
-import { ActionTokensService } from '../action-tokens/action-tokens.service'
-import { ProjectService } from '../project/project.service'
-import { AppLoggerService } from '../logger/logger.service'
-import { User } from '../user/entities/user.entity'
-import { Repository } from 'typeorm'
-import { ActionToken } from '../action-tokens/action-token.entity'
-import { Project } from '../project/entity/project.entity'
-import { ProjectShare } from '../project/entity/project-share.entity'
-import { Test, TestingModule } from '@nestjs/testing'
-
-describe('OldAuthController', () => {
- let controller: OldAuthController
-
- const USER_REPOSITORY_TOKEN = getRepositoryToken(User)
- const ACTION_TOKEN_REPOSITORY_TOKEN = getRepositoryToken(ActionToken)
- const PROJECT_REPOSITORY_TOKEN = getRepositoryToken(Project)
- const PROJECT_SHARE_REPOSITORY_TOKEN = getRepositoryToken(ProjectShare)
-
- beforeEach(async () => {
- const module: TestingModule = await Test.createTestingModule({
- controllers: [OldAuthController],
- providers: [
- OldAuthService,
- UserService,
- {
- provide: USER_REPOSITORY_TOKEN,
- useValue: { create: jest.fn(), save: jest.fn(), findOne: jest.fn() },
- },
- MailerService,
- ActionTokensService,
- {
- provide: ACTION_TOKEN_REPOSITORY_TOKEN,
- useValue: {
- delete: jest.fn(),
- save: jest.fn(),
- findOneOrFail: jest.fn(),
- },
- },
- ProjectService,
- {
- provide: PROJECT_REPOSITORY_TOKEN,
- useValue: {
- count: jest.fn(),
- save: jest.fn(),
- update: jest.fn(),
- delete: jest.fn(),
- findOne: jest.fn(),
- find: jest.fn(),
- },
- },
- ProjectService,
- {
- provide: PROJECT_SHARE_REPOSITORY_TOKEN,
- useValue: {
- count: jest.fn(),
- save: jest.fn(),
- update: jest.fn(),
- delete: jest.fn(),
- findOne: jest.fn(),
- find: jest.fn(),
- },
- },
- AppLoggerService,
- ],
- }).compile()
-
- controller = module.get<OldAuthController>(OldAuthController)
- })
-
- describe('root', () => {
- it('should be defined with controller', () => {
- expect(controller).toBeDefined()
- })
- }),
- describe('auth.controller definding', () => {
- it('should be defined with changeEmail()', () => {
- expect(controller.changeEmail).toBeDefined()
- }),
- it('should be defined with loginUser()', () => {
- expect(controller.loginUser).toBeDefined()
- }),
- it('should be defined with me()', () => {
- expect(controller.me).toBeDefined()
- }),
- it('should be defined with register()', () => {
- expect(controller.register).toBeDefined()
- }),
- it('should be defined with requestReset()', () => {
- expect(controller.requestReset).toBeDefined()
- }),
- it('should be defined with reset()', () => {
- expect(controller.reset).toBeDefined()
- }),
- it('should be defined with verify()', () => {
- expect(controller.verify).toBeDefined()
- })
- })
-})
diff --git a/src/old-auth/auth.controller.ts b/src/old-auth/auth.controller.ts
deleted file mode 100644
index ad3979849..000000000
--- a/src/old-auth/auth.controller.ts
+++ /dev/null
@@ -1,339 +0,0 @@
-import {
- Controller,
- Post,
- Body,
- Req,
- Get,
- Param,
- BadRequestException,
- UseGuards,
- Ip,
- Headers,
- UnprocessableEntityException,
-} from '@nestjs/common'
-import { Request } from 'express'
-import { ApiTags } from '@nestjs/swagger'
-
-import { OldAuthService } 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 { ProjectService } from '../project/project.service'
-import { PasswordChangeDTO } from './dto/password-change.dto'
-import { RequestPasswordChangeDTO } from './dto/request-pass-change.dto'
-import { RolesGuard } from '../auth/guards/roles.guard'
-import { Roles } from '../auth/decorators/roles.decorator'
-import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
-import { checkRateLimit } from '../common/utils'
-import { LetterTemplate } from '../mailer/letter'
-import { AppLoggerService } from '../logger/logger.service'
-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'
-import {
- isSelfhosted,
- SELFHOSTED_EMAIL,
- SELFHOSTED_PASSWORD,
- SELFHOSTED_UUID,
-} from '../common/constants'
-import * as _pick from 'lodash/pick'
-import { InjectBot } from 'nestjs-telegraf'
-import { TelegrafContext } from 'src/user/user.controller'
-import { Telegraf } from 'telegraf'
-import * as UAParser from 'ua-parser-js'
-import ct from 'countries-and-timezones'
-
-// TODO: Add logout endpoint to invalidate the token
-@ApiTags('Auth')
-@Controller('auth')
-export class OldAuthController {
- constructor(
- private oldAuthService: OldAuthService,
- private userService: UserService,
- private mailerService: MailerService,
- private actionTokensService: ActionTokensService,
- private readonly projectService: ProjectService,
- private readonly logger: AppLoggerService,
- @InjectBot() private bot: Telegraf<TelegrafContext>,
- ) {}
-
- @Get('/me')
- @UseGuards(RolesGuard)
- @Roles(UserType.CUSTOMER, UserType.ADMIN)
- async me(@CurrentUserId() user_id: string): Promise<User> {
- this.logger.log({ user_id }, 'GET /auth/me')
- let user
-
- if (isSelfhosted) {
- user = {
- id: SELFHOSTED_UUID,
- email: SELFHOSTED_EMAIL,
- }
- } else {
- const sharedProjects = await this.projectService.findShare({
- where: {
- user: user_id,
- },
- relations: ['project'],
- })
- user = this.oldAuthService.processUser(
- await this.userService.findOneWhere({ id: user_id }),
- )
-
- user.sharedProjects = sharedProjects
- }
-
- return this.userService.omitSensitiveData(user)
- }
-
- @Post('/login')
- async loginUser(
- @Body() userLoginDTO: UserLoginDTO,
- @Headers() headers,
- @Ip() reqIP,
- ): Promise<any> {
- this.logger.log({ userLoginDTO }, 'POST /auth/login')
- const ip =
- headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''
- await checkRateLimit(ip, 'login', 10, 1800)
- const { 'user-agent': userAgent } = headers
- // await this.oldAuthService.checkCaptcha(userLoginDTO.recaptcha)
-
- if (isSelfhosted) {
- if (
- userLoginDTO.email !== SELFHOSTED_EMAIL ||
- userLoginDTO.password !== SELFHOSTED_PASSWORD
- ) {
- throw new UnprocessableEntityException('Email or password is incorrect')
- }
- return this.oldAuthService.login({
- email: SELFHOSTED_EMAIL,
- })
- } else {
- const user = await this.oldAuthService.validateUser(
- userLoginDTO.email,
- userLoginDTO.password,
- )
-
- if (user.isTwoFactorAuthenticationEnabled) {
- const processedUser = this.oldAuthService.postLoginProcess(user)
- return this.oldAuthService.login(processedUser)
- }
-
- const sharedProjects = await this.projectService.findShare({
- where: {
- user: user.id,
- },
- relations: ['project'],
- })
-
- user.sharedProjects = sharedProjects
-
- if (user.isTelegramChatIdConfirmed && process.env.TG_BOT_TOKEN) {
- const ua = UAParser(userAgent)
- const br = ua.browser.name || 'Unknown'
- const dv = ua.device.type || 'Desktop'
- const os = ua.os.name || 'Unknown'
- let country
-
- if (headers['cf-ipcountry'] === 'XX') {
- country = 'Unknown'
- } else if (headers['cf-ipcountry'] === 'T1') {
- country = 'Unknown (Tor Browser detected)'
- } else {
- ct.getCountry(headers['cf-ipcountry'])?.name || 'Unknown'
- }
-
- this.bot.telegram.sendMessage(
- user.telegramChatId,
- `🚨 *Someone has logged into your account!*` +
- '\n\n' +
- `Browser: \`${br}\`` +
- '\n' +
- `Device: \`${dv}\`` +
- '\n' +
- `OS: \`${os}\`` +
- '\n' +
- `Country: \`${country}\`` +
- '\n' +
- `IP: \`${ip}\`` +
- '\n\n' +
- `If it was you, ignore this message. If not, please contact customer support immediately.`,
- {
- parse_mode: 'Markdown',
- },
- )
- }
-
- return this.oldAuthService.login(user)
- }
- }
-
- @UseGuards(SelfhostedGuard)
- @Post('/register')
- async register(
- @Body() userDTO: SignupUserDTO,
- /*@Body('recaptcha') recaptcha: string,*/ @Req() request: Request,
- @Headers() headers,
- @Ip() reqIP,
- ): Promise<any> {
- this.logger.log({ userDTO }, 'POST /auth/register')
- const ip =
- headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''
-
- if (userDTO.checkIfLeaked) {
- await this.oldAuthService.checkIfPasswordLeaked(userDTO.password)
- }
-
- await checkRateLimit(ip, 'register', 6)
-
- // await this.oldAuthService.checkCaptcha(recaptcha)
- this.userService.validatePassword(userDTO.password)
-
- const doesEmailExist = await this.userService.findOneWhere({
- email: userDTO.email,
- })
-
- if (doesEmailExist) {
- throw new BadRequestException('emailRegistered')
- }
-
- userDTO.password = await this.oldAuthService.hashPassword(userDTO.password)
-
- try {
- const userToUpdate = _pick(userDTO, ['email', 'password'])
- const user = await this.userService.create(userToUpdate)
- 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,
- })
- user.sharedProjects = []
-
- return this.oldAuthService.login(user)
- } catch (e) {
- this.logger.log(
- `[ERROR WHILE CREATING ACCOUNT]: ${e}`,
- 'POST /auth/register',
- true,
- )
- }
- }
-
- @UseGuards(SelfhostedGuard)
- @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('Incorrect token provided')
- }
-
- if (actionToken.action === ActionTokenType.EMAIL_VERIFICATION) {
- await this.userService.update(actionToken.user.id, {
- ...actionToken.user,
- isActive: true,
- })
- await this.actionTokensService.delete(actionToken.id)
- return
- }
- }
-
- @UseGuards(SelfhostedGuard)
- @Get('/change-email/:id')
- async changeEmail(@Param('id') id: string): Promise<User> {
- this.logger.log({ id }, 'GET /auth/change-email/:id')
- let actionToken
-
- try {
- actionToken = await this.actionTokensService.find(id)
- } catch {
- throw new BadRequestException('Incorrect token provided')
- }
-
- 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
- }
- }
-
- @UseGuards(SelfhostedGuard)
- @Post('/reset-password')
- async requestReset(
- @Body() body: RequestPasswordChangeDTO,
- @Req() request: Request,
- @Headers() headers,
- @Ip() reqIP,
- ): Promise<string> {
- this.logger.log({ body }, 'POST /auth/password-reset')
- const { email } = body
- const ip =
- headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''
- await checkRateLimit(ip, 'reset-password')
- await checkRateLimit(email, 'reset-password')
-
- const user = await this.userService.findOneWhere({ 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(
- email,
- LetterTemplate.ConfirmPasswordChange,
- { url },
- )
- return 'A password reset URL has been sent to your email'
- }
-
- @UseGuards(SelfhostedGuard)
- @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('Incorrect token provided')
- }
-
- if (actionToken.action === ActionTokenType.PASSWORD_RESET) {
- const password = await this.oldAuthService.hashPassword(body.password)
-
- await this.userService.update(actionToken.user.id, {
- ...actionToken.user,
- password,
- })
- await this.actionTokensService.delete(actionToken.id)
- return
- }
- }
-}
diff --git a/src/old-auth/auth.module.ts b/src/old-auth/auth.module.ts
deleted file mode 100644
index 833858003..000000000
--- a/src/old-auth/auth.module.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { Module, forwardRef } from '@nestjs/common'
-import { OldAuthService } from './auth.service'
-import { UserModule } from '../user/user.module'
-import { OldAuthController } from './auth.controller'
-import { MailerModule } from '../mailer/mailer.module'
-import { ProjectModule } from '../project/project.module'
-import { ActionTokensModule } from '../action-tokens/action-tokens.module'
-import { AppLoggerModule } from '../logger/logger.module'
-
-@Module({
- imports: [
- forwardRef(() => UserModule),
- MailerModule,
- ActionTokensModule,
- AppLoggerModule,
- ProjectModule,
- ],
- controllers: [OldAuthController],
- providers: [OldAuthService],
- exports: [OldAuthService],
-})
-export class OldAuthModule {}
diff --git a/src/old-auth/auth.service.spec.ts b/src/old-auth/auth.service.spec.ts
deleted file mode 100644
index 5ce3bf115..000000000
--- a/src/old-auth/auth.service.spec.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { Test, TestingModule } from '@nestjs/testing'
-import { getRepositoryToken } from '@nestjs/typeorm'
-import { AppLoggerService } from 'src/logger/logger.service'
-import { User } from 'src/user/entities/user.entity'
-import { UserService } from 'src/user/user.service'
-import { Util } from 'src/Util/Util'
-import { Repository } from 'typeorm'
-import { OldAuthService } from './auth.service'
-import * as bcrypt from 'bcrypt'
-
-describe('OldAuthService', () => {
- let service: OldAuthService
- let repository: Repository<User>
- let util = new Util()
- const USER_REPOSITORY_TOKEN = getRepositoryToken(User)
-
- beforeEach(async () => {
- const module: TestingModule = await Test.createTestingModule({
- providers: [
- OldAuthService,
- UserService,
- {
- provide: USER_REPOSITORY_TOKEN,
- useValue: { create: jest.fn(), save: jest.fn(), findOne: jest.fn() },
- },
- AppLoggerService,
- ],
- }).compile()
-
- repository = module.get<Repository<User>>(USER_REPOSITORY_TOKEN)
- service = module.get<OldAuthService>(OldAuthService)
- })
- describe('root', () => {
- it('should be defined service', () => {
- expect(service).toBeDefined()
- }),
- it('should be defined repository', () => {
- expect(repository).toBeDefined()
- })
- }),
- describe('auth.service definding', () => {
- it('should be defined checkIfPasswordLeaked()', () => {
- expect(service.checkIfPasswordLeaked).toBeDefined()
- }),
- it('should be defined checkPassword()', () => {
- expect(service.checkPassword).toBeDefined()
- }),
- it('should be defined get()', () => {
- expect(service.get).toBeDefined()
- }),
- it('should be defined hashPassword()', () => {
- expect(service.hashPassword).toBeDefined()
- }),
- it('should be defined login()', () => {
- expect(service.login).toBeDefined()
- }),
- it('should be defined postLoginProcess()', () => {
- expect(service.postLoginProcess).toBeDefined()
- }),
- it('should be defined processUser()', () => {
- expect(service.processUser).toBeDefined()
- }),
- it('should be defined sha1hash()', () => {
- expect(service.sha1hash).toBeDefined()
- }),
- it('should be defined validateUser()', () => {
- expect(service.validateUser).toBeDefined()
- })
-
- it('should be defined', () => {
- expect(repository).toBeDefined()
- })
-
- it('should be hashPassword function not null and tobedefined', () => {
- let pass = util.getString()
- expect(service.hashPassword(pass)).resolves.not.toBeNull()
- expect(service.hashPassword).toBeDefined()
- })
-
- it('should be get function not null and tobedefined', () => {
- let hash = util.getString()
- expect(service.get(hash)).resolves.not.toBeNull()
- expect(service.get).toBeDefined()
- })
-
- it('should be sha1hash function not null and tobedefined', () => {
- let string = util.getString()
- expect(service.sha1hash(string)).resolves.not.toBeNull()
- expect(service.sha1hash).toBeDefined()
- })
- it('should be checkIfPasswordLeaked function not null and tobedefined', () => {
- let pass = util.getString()
- expect(service.checkIfPasswordLeaked(pass)).resolves.not.toBeNull()
- expect(service.checkIfPasswordLeaked).toBeDefined()
- })
- it('should be checkPassword function not null and tobedefined', () => {
- let passToCheck = util.getString()
- let hashedPass = util.getString()
- expect(service.checkPassword(passToCheck, hashedPass)).not.toBeNull()
- expect(service.checkPassword).toBeDefined()
- })
-
- it('should be validateUser function not null and tobedefined', () => {
- let email = util.getString()
- let pass = util.getString()
- expect(service.validateUser(email, pass)).rejects.toThrow()
- expect(service.validateUser).toBeDefined()
- })
-
- it('should be processUser function not null and tobedefined', () => {
- let user = util.getUser()
- expect(service.processUser(user)).not.toBeNull()
- expect(service.processUser).toBeDefined()
- })
-
- it('should be postLoginProcess function not null and tobedefined', () => {
- let user = util.getUser()
- expect(service.postLoginProcess(user)).not.toBeNull()
- expect(service.postLoginProcess).toBeDefined()
- })
-
- it('should be login function not null and tobedefined', () => {
- let user = util.getUser()
- expect(service.login(user)).not.toBeNull()
- expect(service.login).toBeDefined()
- })
- })
- // describe('auth.service testing', () => {
- // it('should return correct hashPassword()', async () => {
- // const password = 'test'
- // const salt = await bcrypt.genSalt(10)
- // const hashedStringFromService = await service.hashPassword(password)
- // const hashedPass = await bcrypt.hash(password, salt)
- // console.log('Hashed password1: ' + hashedStringFromService)
- // console.log('Hashed password2: ' + hashedPass)
- // expect(hashedStringFromService).toEqual(hashedPass)
- // })
- // })
-})
diff --git a/src/old-auth/auth.service.ts b/src/old-auth/auth.service.ts
deleted file mode 100644
index 965e1e52c..000000000
--- a/src/old-auth/auth.service.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import {
- Injectable,
- UnprocessableEntityException,
- BadRequestException,
-} from '@nestjs/common'
-import { sign } from 'jsonwebtoken'
-import * as bcrypt from 'bcrypt'
-import * as crypto from 'crypto'
-import * as https from 'https'
-import * as _toUpper from 'lodash/toUpper'
-import * as _includes from 'lodash/includes'
-import * as _pick from 'lodash/pick'
-
-import { UserService } from '../user/user.service'
-import { ACCOUNT_PLANS } from '../user/entities/user.entity'
-import { AppLoggerService } from '../logger/logger.service'
-import { User } from '../user/entities/user.entity'
-import {
- isSelfhosted,
- JWT_LIFE_TIME,
- SELFHOSTED_UUID,
-} from '../common/constants'
-import { splitAt } from '../common/utils'
-
-const HIBP_URL = 'https://api.pwnedpasswords.com/range'
-const BCRYPT_SALT_ROUNDS = 10
-
-const httpsOptions = {
- headers: {
- 'User-Agent': 'Swetrix API ([email protected])',
- },
-}
-
-@Injectable()
-export class OldAuthService {
- constructor(
- private userService: UserService,
- private readonly logger: AppLoggerService,
- ) {}
-
- async hashPassword(pass: string): Promise<string> {
- const salt = await bcrypt.genSalt(BCRYPT_SALT_ROUNDS)
- return await bcrypt.hash(pass, salt)
- }
-
- async get(hash) {
- return new Promise((resolve, reject) => {
- https
- .get(`${HIBP_URL}/${hash}`, httpsOptions, res => {
- let data = ''
-
- if (res.statusCode !== 200) {
- return reject(`Failed to load ${HIBP_URL} API: ${res.statusCode}`)
- }
-
- res.on('data', chunk => {
- data += chunk
- })
-
- res.on('end', () => {
- resolve(data)
- })
-
- return true
- })
- .on('error', err => {
- reject(err)
- })
- })
- }
-
- async sha1hash(string): Promise<string> {
- return new Promise(resolve => {
- const shasum = _toUpper(
- crypto.createHash('sha1').update(string).digest('hex'),
- )
- resolve(shasum)
- })
- }
-
- async checkIfPasswordLeaked(pass: string): Promise<void> {
- const shasum = splitAt(await this.sha1hash(pass), 5)
- let isLeaked
-
- try {
- const result = await this.get(shasum[0])
- isLeaked = _includes(result, shasum[1])
- } catch (e) {
- this.logger.log(`[ERROR / HAVEIBEENPWNED]: ${e}`, 'AUTH SERVICE', true)
- }
-
- if (isLeaked) {
- throw new BadRequestException('leakedPassword')
- }
- }
-
- async checkPassword(
- passToCheck: string,
- hashedPass: string,
- ): Promise<boolean> {
- return await bcrypt.compare(passToCheck, hashedPass)
- }
-
- async validateUser(email: string, pass: string): Promise<User> {
- const user = await this.userService.findOneWhere({ email }, [
- 'sharedProjects',
- ])
-
- if (user && (await this.checkPassword(pass, user.password))) {
- return user
- }
-
- throw new UnprocessableEntityException('Email or password is incorrect')
- }
-
- processUser(user: User): object {
- // @ts-ignore
- const maxEventsCount = ACCOUNT_PLANS[user?.planCode]?.monthlyUsageLimit || 0
- const userData = {
- // @ts-ignore
- ...user,
- password: undefined,
- twoFactorRecoveryCode: undefined,
- twoFactorAuthenticationSecret: undefined,
- maxEventsCount,
- }
-
- return userData
- }
-
- postLoginProcess(user: User): object {
- if (user.isTwoFactorAuthenticationEnabled) {
- return _pick(user, ['id', 'email', 'isTwoFactorAuthenticationEnabled'])
- }
-
- return user
- }
-
- login(user: User | object, isSecondFactorAuthenticated = false): object {
- let userData = user
-
- if (isSelfhosted) {
- // @ts-ignore
- userData = {
- ...user,
- id: SELFHOSTED_UUID,
- }
- } else {
- // @ts-ignore
- userData = this.processUser(user)
- }
-
- // @ts-ignore
- const token = sign(
- // @ts-ignore
- { user_id: userData.id, isSecondFactorAuthenticated },
- process.env.JWT_SECRET,
- {
- expiresIn: JWT_LIFE_TIME,
- },
- )
-
- return { access_token: token, user: userData }
- }
-}
diff --git a/src/old-auth/dto/password-change.dto.ts b/src/old-auth/dto/password-change.dto.ts
deleted file mode 100644
index 6d7f68c3c..000000000
--- a/src/old-auth/dto/password-change.dto.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsNotEmpty } from 'class-validator'
-
-export class PasswordChangeDTO {
- @ApiProperty({ example: 'your_password123' })
- @IsNotEmpty()
- password: string
-}
diff --git a/src/old-auth/dto/request-pass-change.dto.ts b/src/old-auth/dto/request-pass-change.dto.ts
deleted file mode 100644
index dd328565b..000000000
--- a/src/old-auth/dto/request-pass-change.dto.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsEmail } from 'class-validator'
-
-export class RequestPasswordChangeDTO {
- @ApiProperty({ example: '[email protected]' })
- @IsEmail()
- email: string
-}
diff --git a/src/old-auth/dto/user-login.dto.ts b/src/old-auth/dto/user-login.dto.ts
deleted file mode 100644
index 5adf89778..000000000
--- a/src/old-auth/dto/user-login.dto.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-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/old-auth/dto/user-signup.dto.ts b/src/old-auth/dto/user-signup.dto.ts
deleted file mode 100644
index e44eb9d24..000000000
--- a/src/old-auth/dto/user-signup.dto.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsEmail, IsNotEmpty } 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()
- checkIfLeaked: boolean
-}
diff --git a/src/twoFactorAuth/twoFactorAuth.controller.spec.ts b/src/twoFactorAuth/twoFactorAuth.controller.spec.ts
index a2042f210..93407c637 100644
--- a/src/twoFactorAuth/twoFactorAuth.controller.spec.ts
+++ b/src/twoFactorAuth/twoFactorAuth.controller.spec.ts
@@ -1,6 +1,6 @@
import { Test, TestingModule } from '@nestjs/testing'
import { getRepositoryToken } from '@nestjs/typeorm'
-import { OldAuthService } from 'src/old-auth/auth.service'
+import { AuthService } from 'src/auth/auth.service'
import { AppLoggerService } from 'src/logger/logger.service'
import { MailerService } from 'src/mailer/mailer.service'
import { User } from 'src/user/entities/user.entity'
@@ -22,7 +22,7 @@ describe('TwoFactorAuthController', () => {
provide: USER_REPOSITORY_TOKEN,
useValue: { create: jest.fn(), save: jest.fn(), findOne: jest.fn() },
},
- OldAuthService,
+ AuthService,
AppLoggerService,
MailerService,
],
diff --git a/src/twoFactorAuth/twoFactorAuth.controller.ts b/src/twoFactorAuth/twoFactorAuth.controller.ts
index 2c227f561..ff4987682 100644
--- a/src/twoFactorAuth/twoFactorAuth.controller.ts
+++ b/src/twoFactorAuth/twoFactorAuth.controller.ts
@@ -12,7 +12,7 @@ import { ApiTags } from '@nestjs/swagger'
import { TwoFactorAuthService } from './twoFactorAuth.service'
import { UserService } from '../user/user.service'
-import { OldAuthService } from '../old-auth/auth.service'
+import { AuthService } from '../auth/auth.service'
import { UserType } from '../user/entities/user.entity'
import { AppLoggerService } from '../logger/logger.service'
import { MailerService } from '../mailer/mailer.service'
@@ -31,7 +31,7 @@ export class TwoFactorAuthController {
constructor(
private twoFactorAuthService: TwoFactorAuthService,
private userService: UserService,
- private oldAuthService: OldAuthService,
+ private authService: AuthService,
private readonly logger: AppLoggerService,
private readonly mailerService: MailerService,
) {}
@@ -90,7 +90,7 @@ export class TwoFactorAuthController {
user.isTwoFactorAuthenticationEnabled = true
- const authData = this.oldAuthService.login(user, true)
+ const authData = this.authService.generateJwtTokens(user.id, true)
return {
twoFactorRecoveryCode,
@@ -170,6 +170,6 @@ export class TwoFactorAuthController {
throw new BadRequestException('Wrong authentication code')
}
- return this.oldAuthService.login(user, true)
+ return this.authService.generateJwtTokens(user.id, true)
}
}
diff --git a/src/twoFactorAuth/twoFactorAuth.module.ts b/src/twoFactorAuth/twoFactorAuth.module.ts
index 3c9d70c9e..ab13390ec 100644
--- a/src/twoFactorAuth/twoFactorAuth.module.ts
+++ b/src/twoFactorAuth/twoFactorAuth.module.ts
@@ -1,13 +1,13 @@
import { Module } from '@nestjs/common'
import { TwoFactorAuthService } from './twoFactorAuth.service'
import { UserModule } from '../user/user.module'
-import { OldAuthModule } from '../old-auth/auth.module'
+import { AuthModule } from '../auth/auth.module'
import { TwoFactorAuthController } from './twoFactorAuth.controller'
import { AppLoggerModule } from '../logger/logger.module'
import { MailerModule } from '../mailer/mailer.module'
@Module({
- imports: [UserModule, AppLoggerModule, OldAuthModule, MailerModule],
+ imports: [UserModule, AppLoggerModule, AuthModule, MailerModule],
controllers: [TwoFactorAuthController],
providers: [TwoFactorAuthService],
exports: [TwoFactorAuthService],
diff --git a/src/user/user.controller.spec.ts b/src/user/user.controller.spec.ts
index 6bee2520a..04cabdb13 100644
--- a/src/user/user.controller.spec.ts
+++ b/src/user/user.controller.spec.ts
@@ -2,7 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing'
import { getRepositoryToken } from '@nestjs/typeorm'
import { ActionToken } from 'src/action-tokens/action-token.entity'
import { ActionTokensService } from 'src/action-tokens/action-tokens.service'
-import { OldAuthService } from 'src/old-auth/auth.service'
+import { AuthService } from 'src/auth/auth.service'
import { AppLoggerService } from 'src/logger/logger.service'
import { MailerService } from 'src/mailer/mailer.service'
import { ProjectShare } from 'src/project/entity/project-share.entity'
@@ -27,7 +27,7 @@ describe('UserController', () => {
provide: USER_REPOSITORY_TOKEN,
useValue: { create: jest.fn(), save: jest.fn(), findOne: jest.fn() },
},
- OldAuthService,
+ AuthService,
ProjectService,
{
provide: PROJECT_REPOSITORY_TOKEN,
diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts
index a44830c6a..d6d15b00a 100644
--- a/src/user/user.controller.ts
+++ b/src/user/user.controller.ts
@@ -49,7 +49,7 @@ import { CurrentUserId } from '../auth/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 { OldAuthService } from '../old-auth/auth.service'
+import { AuthService } from '../auth/auth.service'
import { LetterTemplate } from '../mailer/letter'
import { AppLoggerService } from '../logger/logger.service'
import { UserProfileDTO } from './dto/user.dto'
@@ -67,7 +67,7 @@ export type TelegrafContext = Scenes.SceneContext
export class UserController {
constructor(
private readonly userService: UserService,
- private readonly oldAuthService: OldAuthService,
+ private readonly authService: AuthService,
private readonly projectService: ProjectService,
private readonly actionTokensService: ActionTokensService,
private readonly mailerService: MailerService,
@@ -120,7 +120,7 @@ export class UserController {
async create(@Body() userDTO: UserProfileDTO): Promise<User> {
this.logger.log({ userDTO }, 'POST /user')
this.userService.validatePassword(userDTO.password)
- userDTO.password = await this.oldAuthService.hashPassword(userDTO.password)
+ userDTO.password = await this.authService.hashPassword(userDTO.password)
try {
const user = await this.userService.create({ ...userDTO, isActive: true })
@@ -372,7 +372,7 @@ export class UserController {
if (userDTO.password) {
this.userService.validatePassword(userDTO.password)
- userDTO.password = await this.oldAuthService.hashPassword(userDTO.password)
+ userDTO.password = await this.authService.hashPassword(userDTO.password)
}
const user = await this.userService.findOneWhere({ id })
@@ -431,7 +431,7 @@ export class UserController {
if (!_isEmpty(userDTO.password) && _isString(userDTO.password)) {
this.userService.validatePassword(userDTO.password)
- userDTO.password = await this.oldAuthService.hashPassword(userDTO.password)
+ userDTO.password = await this.authService.hashPassword(userDTO.password)
await this.mailerService.sendEmail(
userDTO.email,
LetterTemplate.PasswordChanged,
diff --git a/src/user/user.module.ts b/src/user/user.module.ts
index 6a7b2e79d..ff350d50d 100644
--- a/src/user/user.module.ts
+++ b/src/user/user.module.ts
@@ -6,7 +6,7 @@ import { UserService } from './user.service'
import { User } from './entities/user.entity'
import { ActionTokensModule } from '../action-tokens/action-tokens.module'
import { MailerModule } from '../mailer/mailer.module'
-import { OldAuthModule } from '../old-auth/auth.module'
+import { AuthModule } from '../auth/auth.module'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
import { RefreshToken } from './entities/refresh-token.entity'
@@ -16,7 +16,7 @@ import { RefreshToken } from './entities/refresh-token.entity'
TypeOrmModule.forFeature([User, RefreshToken]),
ActionTokensModule,
MailerModule,
- forwardRef(() => OldAuthModule),
+ forwardRef(() => AuthModule),
AppLoggerModule,
ProjectModule,
],