Compare commits

..

No commits in common. "main" and "feature/auth-mode" have entirely different histories.

118 changed files with 14769 additions and 13053 deletions

25
.env Normal file
View File

@ -0,0 +1,25 @@
COMPOSE_PROJECT_NAME=
NETWORK_NAME=
TRAEFIK_APP_NAME=
TRAEFIK_ENTRYPOINTS=web-secure
# TRAEFIK_ENTRYPOINTS=web-secure-ext
WEB_HOST=
APPLICATION=
# WEB
APP_BASE_PATH=/login
APP_TITLE=
APP_DESCRIPTION=
# API
LDAP_BIND_DN=
LDAP_BIND_CREDENTIALS=
LDAP_DOMAIN=
LDAP_URL=
LDAP_BASE=
LDAP_ATTRIBUTE=
API_SECRET=
API_TOKEN_TTL=
API_CACHE_TTL=
COOKIE_TOKEN_NAME=token

View File

@ -1,6 +0,0 @@
node_modules
dist
*.config.*
next-env.d.ts
.next
.eslintrc.js

1
.npmrc
View File

@ -1 +0,0 @@
auto-install-peers = true

View File

@ -13,8 +13,9 @@
"editor.defaultFormatter": "esbenp.prettier-vscode", "editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true, "editor.formatOnSave": true,
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.fixAll": "explicit", "source.fixAll": true,
"source.fixAll.eslint": "explicit" "source.fixAll.eslint": true,
"source.removeUnusedImports": true
}, },
"workbench.editor.labelFormat": "short", "workbench.editor.labelFormat": "short",
"eslint.workingDirectories": [ "eslint.workingDirectories": [
@ -28,6 +29,5 @@
"typescriptreact", "typescriptreact",
"yaml" "yaml"
], ],
"eslint.lintTask.enable": true, "eslint.lintTask.enable": true
"editor.inlineSuggest.showToolbar": "always"
} }

View File

@ -1,32 +1,24 @@
# Turborepo starter # Turborepo starter
This is an official starter Turborepo. This is an official Yarn v1 starter turborepo.
## Using this example
Run the following command:
```sh
npx create-turbo@latest
```
## What's inside? ## What's inside?
This Turborepo includes the following packages/apps: This turborepo uses [Yarn](https://classic.yarnpkg.com/) as a package manager. It includes the following packages/apps:
### Apps and Packages ### Apps and Packages
- `docs`: a [Next.js](https://nextjs.org/) app - `docs`: a [Next.js](https://nextjs.org/) app
- `web`: another [Next.js](https://nextjs.org/) app - `web`: another [Next.js](https://nextjs.org/) app
- `@repo/ui`: a stub React component library shared by both `web` and `docs` applications - `ui`: a stub React component library shared by both `web` and `docs` applications
- `@repo/eslint-config`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`) - `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
- `@repo/typescript-config`: `tsconfig.json`s used throughout the monorepo - `tsconfig`: `tsconfig.json`s used throughout the monorepo
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/). Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
### Utilities ### Utilities
This Turborepo has some additional tools already setup for you: This turborepo has some additional tools already setup for you:
- [TypeScript](https://www.typescriptlang.org/) for static type checking - [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting - [ESLint](https://eslint.org/) for code linting
@ -38,7 +30,7 @@ To build all apps and packages, run the following command:
``` ```
cd my-turborepo cd my-turborepo
pnpm build yarn run build
``` ```
### Develop ### Develop
@ -47,7 +39,7 @@ To develop all apps and packages, run the following command:
``` ```
cd my-turborepo cd my-turborepo
pnpm dev yarn run dev
``` ```
### Remote Caching ### Remote Caching
@ -63,7 +55,7 @@ npx turbo login
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview). This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo: Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your turborepo:
``` ```
npx turbo link npx turbo link
@ -73,7 +65,7 @@ npx turbo link
Learn more about the power of Turborepo: Learn more about the power of Turborepo:
- [Tasks](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks) - [Pipelines](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
- [Caching](https://turbo.build/repo/docs/core-concepts/caching) - [Caching](https://turbo.build/repo/docs/core-concepts/caching)
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) - [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering) - [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)

2
apps/api/.eslintignore Normal file
View File

@ -0,0 +1,2 @@
node_modules
dist

View File

@ -1,13 +1,12 @@
const { createConfig } = require('@vchikalkin/eslint-config-awesome'); module.exports = {
root: true,
module.exports = createConfig('typescript', { extends: [
'@vchikalkin/eslint-config-awesome/typescript/config',
'@vchikalkin/eslint-config-awesome/typescript/rules',
],
parserOptions: { parserOptions: {
project: './tsconfig.json', project: './tsconfig.json',
tsconfigRootDir: __dirname, tsconfigRootDir: __dirname,
sourceType: 'module',
}, },
ignorePatterns: ['*.config.js', '.eslintrc.js'], };
rules: {
'import/no-duplicates': 'off',
'import/consistent-type-specifier-style': 'off',
},
});

View File

@ -1,22 +1,19 @@
# This Dockerfile is copy-pasted into our main docs at /docs/handbook/deploying-with-docker. # The web Dockerfile is copy-pasted into our main docs at /docs/handbook/deploying-with-docker.
# Make sure you update both files! # Make sure you update this Dockerfile, the Dockerfile in the web workspace and copy that over to Dockerfile in the docs.
FROM node:alpine AS builder FROM node:alpine AS builder
RUN corepack enable && corepack prepare pnpm@8.9.0 --activate
ENV PNPM_HOME=/usr/local/bin
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed. # Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat RUN apk add --no-cache libc6-compat
RUN apk update RUN apk update
# Set working directory # Set working directory
WORKDIR /app WORKDIR /app
RUN pnpm add -g turbo@1.12.4 dotenv-cli RUN yarn global add turbo
RUN yarn global add dotenv-cli
COPY . . COPY . .
RUN turbo prune --scope=api --docker RUN turbo prune --scope=api --docker
# Add lockfile and package.json's of isolated subworkspace # Add lockfile and package.json's of isolated subworkspace
FROM node:alpine AS installer FROM node:alpine AS installer
RUN corepack enable && corepack prepare pnpm@8.9.0 --activate
ENV PNPM_HOME=/usr/local/bin
RUN apk add --no-cache libc6-compat RUN apk add --no-cache libc6-compat
RUN apk update RUN apk update
WORKDIR /app WORKDIR /app
@ -24,14 +21,13 @@ WORKDIR /app
# First install dependencies (as they change less often) # First install dependencies (as they change less often)
COPY .gitignore .gitignore COPY .gitignore .gitignore
COPY --from=builder /app/out/json/ . COPY --from=builder /app/out/json/ .
COPY --from=builder /app/out/pnpm-lock.yaml ./pnpm-lock.yaml COPY --from=builder /app/out/yarn.lock ./yarn.lock
COPY --from=builder /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml RUN yarn install
RUN pnpm install
# Build the project and its dependencies # Build the project and its dependencies
COPY --from=builder /app/out/full/ . COPY --from=builder /app/out/full/ .
COPY turbo.json turbo.json COPY turbo.json turbo.json
RUN pnpm dotenv -e .env turbo run build --filter=api... RUN yarn dotenv -e .env turbo run build --filter=api...
FROM node:alpine AS runner FROM node:alpine AS runner
WORKDIR /app WORKDIR /app

View File

@ -1,20 +1,5 @@
{ {
"$schema": "https://json.schemastore.org/nest-cli", "$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics", "collection": "@nestjs/schematics",
"sourceRoot": "src", "sourceRoot": "src"
"compilerOptions": {
"plugins": [
{
"name": "@nestjs/swagger/plugin",
"options": {
"dtoFileNameSuffix": [".entity.ts", ".dto.ts"],
"controllerFileNameSuffix": [".controller.ts"],
"classValidatorShim": true,
"dtoKeyOfComment": "description",
"controllerKeyOfComment": "description",
"introspectComments": true
}
}
]
}
} }

View File

@ -23,7 +23,6 @@
}, },
"dependencies": { "dependencies": {
"@fastify/cookie": "^9.1.0", "@fastify/cookie": "^9.1.0",
"@fastify/static": "^6.12.0",
"@nestjs/cache-manager": "^2.1.0", "@nestjs/cache-manager": "^2.1.0",
"@nestjs/cli": "^10.1.18", "@nestjs/cli": "^10.1.18",
"@nestjs/common": "^10.2.7", "@nestjs/common": "^10.2.7",
@ -31,39 +30,27 @@
"@nestjs/core": "^10.2.7", "@nestjs/core": "^10.2.7",
"@nestjs/jwt": "^10.1.1", "@nestjs/jwt": "^10.1.1",
"@nestjs/mapped-types": "*", "@nestjs/mapped-types": "*",
"@nestjs/mongoose": "^10.0.1", "@nestjs/platform-express": "^10.2.7",
"@nestjs/platform-fastify": "^10.2.7", "@nestjs/platform-fastify": "^10.2.7",
"@nestjs/platform-socket.io": "^10.3.8",
"@nestjs/swagger": "^7.1.14",
"@nestjs/websockets": "^10.3.8",
"axios": "^1.5.1",
"bcrypt": "^5.1.1",
"cache-manager": "^5.2.4", "cache-manager": "^5.2.4",
"cache-manager-ioredis": "^2.1.0", "cache-manager-ioredis": "^2.1.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"ldap-authentication": "2.3.1", "ldap-authentication": "2.3.1",
"mongoose": "^7.6.3",
"radash": "^11.0.0",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",
"rimraf": "^5.0.5", "rimraf": "^5.0.5",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
"socket.io": "^4.7.5",
"zod": "^3.22.4" "zod": "^3.22.4"
}, },
"devDependencies": { "devDependencies": {
"@nestjs/schematics": "^10.0.2", "@nestjs/schematics": "^10.0.2",
"@nestjs/testing": "^10.2.7", "@nestjs/testing": "^10.2.7",
"@types/bcrypt": "^5.0.1",
"@types/cache-manager": "^4.0.3", "@types/cache-manager": "^4.0.3",
"@types/ioredis": "^4.28.10", "@types/ioredis": "^4.28.10",
"@types/jest": "29.5.5", "@types/jest": "29.5.5",
"@types/ldap-authentication": "^2.2.1", "@types/ldap-authentication": "^2.2.1",
"@types/node": "^20.8.6", "@types/node": "^20.8.6",
"@types/supertest": "^2.0.14", "@types/supertest": "^2.0.14",
"@vchikalkin/eslint-config-awesome": "^1.1.6", "@vchikalkin/eslint-config-awesome": "^1.1.2",
"eslint": "^8.51.0", "eslint": "^8.51.0",
"fastify": "4.24.3",
"jest": "29.7.0", "jest": "29.7.0",
"prettier": "^3.0.3", "prettier": "^3.0.3",
"source-map-support": "^0.5.21", "source-map-support": "^0.5.21",
@ -72,7 +59,7 @@
"ts-loader": "^9.5.0", "ts-loader": "^9.5.0",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"tsconfig-paths": "4.2.0", "tsconfig-paths": "4.2.0",
"typescript": "5.3.2" "typescript": "4.9.5"
}, },
"jest": { "jest": {
"moduleFileExtensions": [ "moduleFileExtensions": [

View File

@ -1,175 +0,0 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable class-methods-use-this */
/* eslint-disable import/no-extraneous-dependencies */
import { AccountService } from './account.service';
import { CreateAccountDto } from './dto/create-account.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { UpdateAccountDto } from './dto/update-account.dto';
import {
Body,
Controller,
Delete,
Get,
HttpException,
HttpStatus,
Patch,
Post,
Query,
Req,
Res,
UnauthorizedException,
} from '@nestjs/common';
import { ApiResponse, ApiTags } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify';
import { cookieOptions } from 'src/config/cookie';
import { env } from 'src/config/env';
import { AuthParams, Params } from 'src/decorators/auth-mode.decorator';
import { AuthToken } from 'src/decorators/token.decorator';
import { Credentials } from 'src/dto/credentials';
import { Account } from 'src/schemas/account.schema';
import type { BaseAuthController } from 'src/types/auth-controller';
@Controller('account')
@ApiTags('account')
export class AccountController implements BaseAuthController {
constructor(private readonly accountService: AccountService) {}
private clearCookies(req, reply) {
if (req.cookies) {
Object.keys(req.cookies).forEach((cookieName) => {
reply.clearCookie(cookieName, {
path: '/',
});
});
}
}
@Post('/create')
@ApiResponse({
status: HttpStatus.CREATED,
type: Account,
})
async create(@Body() createAccountDto: CreateAccountDto, @Res() reply: FastifyReply) {
try {
const createdAccount = await this.accountService.create(createAccountDto);
return reply.status(HttpStatus.CREATED).send(createdAccount);
} catch (error) {
throw new HttpException(error, HttpStatus.BAD_REQUEST);
}
}
@Get()
async findAll() {
return this.accountService.findAll();
}
@Delete('/delete')
@ApiResponse({
status: HttpStatus.OK,
type: Account,
})
// @ApiQuery({ name: 'username', type: CreateAccountDto['username'] })
async delete(@Query('username') username: string) {
return this.accountService.delete(username);
}
@Patch('/update')
@ApiResponse({
status: HttpStatus.OK,
type: Account,
})
async update(@Body() updateAccountDto: UpdateAccountDto, @Res() reply: FastifyReply) {
try {
const updatedAccount = await this.accountService.update(updateAccountDto);
return reply.status(HttpStatus.OK).send(updatedAccount);
} catch (error) {
throw new HttpException(error, HttpStatus.BAD_REQUEST);
}
}
@Post('/reset-password')
@ApiResponse({
status: HttpStatus.OK,
type: Account,
})
async resetPassword(@Body() resetPasswordDto: ResetPasswordDto, @Res() reply: FastifyReply) {
try {
const updatedAccount = await this.accountService.resetPassword(resetPasswordDto);
return reply.status(HttpStatus.OK).send(updatedAccount);
} catch (error) {
throw new HttpException(error, HttpStatus.BAD_REQUEST);
}
}
@Post('/login')
async login(
@Body() credentials: Credentials,
@Req() _req: FastifyRequest,
@Res() reply: FastifyReply
) {
try {
const token = await this.accountService.login(credentials);
return reply
.setCookie(env.COOKIE_TOKEN_NAME, token, cookieOptions)
.status(200)
.send({ token });
} catch {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
}
}
@Get('/logout')
async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
this.clearCookies(req, reply);
return reply.status(302).redirect('/');
}
@Get('/refresh-token')
@ApiResponse({
status: HttpStatus.OK,
})
async refreshToken(
@AuthToken() token: string,
@AuthParams() { refreshToken }: Params,
@Res() reply: FastifyReply
) {
if (!refreshToken) return reply.status(HttpStatus.UNAUTHORIZED).send();
const newToken = await this.accountService.refreshToken(token);
reply.header('Authorization', `Bearer ${newToken}`);
return reply.setCookie(env.COOKIE_TOKEN_NAME, newToken, cookieOptions).send();
}
@Get('/get-user')
async getUser(
@Req() req: FastifyRequest,
@Res() reply: FastifyReply,
@AuthToken() token: string
) {
const account = await this.accountService.getUser(token);
if (!account) throw new UnauthorizedException('Account not found');
return reply.send(account);
}
@Get('/check-auth')
@ApiResponse({
status: HttpStatus.OK,
})
async checkAuth(@AuthToken() token: string, @Res() reply: FastifyReply) {
const { authId } = await this.accountService.parseToken(token, { ignoreExpiration: true });
if (authId) return reply.status(HttpStatus.UNAUTHORIZED).send();
const user = await this.accountService.getUser(token, { ignoreExpiration: true });
return reply.status(200).send(user);
}
}

View File

@ -1,14 +0,0 @@
import { AccountController } from './account.controller';
import { AccountService } from './account.service';
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Account, AccountSchema } from 'src/schemas/account.schema';
@Module({
controllers: [AccountController],
exports: [AccountService],
imports: [MongooseModule.forFeature([{ name: Account.name, schema: AccountSchema }])],
providers: [AccountService],
})
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class AccountModule {}

View File

@ -1,135 +0,0 @@
import type { CreateAccountDto } from './dto/create-account.dto';
import type { ResetPasswordDto } from './dto/reset-password.dto';
import type { UpdateAccountDto } from './dto/update-account.dto';
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import type { JwtVerifyOptions } from '@nestjs/jwt';
import { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/mongoose';
import * as bcrypt from 'bcrypt';
import { Model } from 'mongoose';
import { omit } from 'radash';
import type { Credentials } from 'src/dto/credentials';
import { Account } from 'src/schemas/account.schema';
import type { DecodedToken, TokenPayload } from 'src/types/jwt';
import { generatePassword } from 'src/utils/password';
@Injectable()
export class AccountService {
constructor(
private readonly jwtService: JwtService,
@InjectModel(Account.name) private accountModel: Model<Account>
) {}
public async create(createAccountDto: CreateAccountDto): Promise<Account> {
const isExist = await this.accountModel.exists({ username: createAccountDto.username }).exec();
if (isExist)
throw new BadRequestException(
`Account with username '${createAccountDto.username}' already exists`
);
Object.keys(createAccountDto).forEach((field) => {
if (['_id', '__v'].includes(field))
throw new BadRequestException(`Prop ${field} is not allowed`);
});
const password = createAccountDto.password || generatePassword();
const createdAccount = new this.accountModel({ ...createAccountDto, password });
createdAccount.save();
return { ...createdAccount.toJSON(), password };
}
public async findAll(): Promise<Account[]> {
return this.accountModel.find().exec();
}
public async delete(username: string) {
return this.accountModel.findOneAndDelete({ username }).exec();
}
public async update({ username, ...props }: UpdateAccountDto): Promise<Account> {
Object.keys(props).forEach((field) => {
if (['_id', '__v', 'password'].includes(field))
throw new BadRequestException(`Prop ${field} is not allowed`);
});
await this.accountModel.findOneAndUpdate({ username }, props).exec();
return this.accountModel.findOne({ username });
}
public async resetPassword({ username }: ResetPasswordDto): Promise<Account> {
const account = await this.accountModel.findOne({ username });
if (!account) throw new UnauthorizedException('Account not found');
const new_password = generatePassword();
await this.accountModel.findOneAndUpdate({ username }, { password: new_password }).exec();
return { password: new_password, username };
}
public async login({ login, password }: Credentials) {
try {
const account = await this.accountModel.findOne({ username: login });
if (!account) {
throw new UnauthorizedException('Account not found');
}
const passwordMatch = await bcrypt.compare(password, account.password);
if (!passwordMatch) {
throw new UnauthorizedException('Invalid login credentials');
}
const payload: TokenPayload = {
username: login,
...omit(account.toJSON(), ['password', '_id', '__v']),
};
return this.jwtService.sign(payload);
} catch (error) {
throw new UnauthorizedException(error);
}
}
public async refreshToken(token: string) {
try {
const { username } = this.jwtService.verify<DecodedToken>(token, { ignoreExpiration: true });
const account = await this.accountModel.findOne({ username });
if (!account) {
throw new UnauthorizedException('Account not found');
}
const payload: TokenPayload = {
username,
...omit(account.toJSON(), ['password', '_id', '__v']),
};
return this.jwtService.sign(payload);
} catch (error) {
throw new UnauthorizedException(error);
}
}
public async getUser(token: string, options?: JwtVerifyOptions) {
try {
const { username } = this.jwtService.verify<DecodedToken>(token, options);
return this.accountModel.findOne({
username,
});
} catch {
throw new UnauthorizedException('Invalid token');
}
}
public async parseToken(token: string, options?: JwtVerifyOptions) {
try {
return this.jwtService.verify<TokenPayload>(token, options);
} catch (error) {
throw new UnauthorizedException(error);
}
}
}

View File

@ -1,17 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, IsString, MinLength } from 'class-validator';
export class CreateAccountDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
public readonly username: string;
@ApiPropertyOptional({})
@IsString()
@MinLength(10)
@IsOptional()
public readonly password: string;
readonly [key: string]: unknown;
}

View File

@ -1,9 +0,0 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class ResetPasswordDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
public readonly username: string;
}

View File

@ -1,11 +0,0 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class UpdateAccountDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
public readonly username: string;
readonly [key: string]: unknown;
}

View File

@ -0,0 +1,23 @@
import { AppController } from './app.controller';
import { AppService } from './app.service';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@ -1,51 +1,12 @@
import { AppService } from './app.service'; import { AppService } from './app.service';
import { AuthParams, Params } from './decorators/auth-mode.decorator'; import { Controller, Get } from '@nestjs/common';
import { AuthToken } from './decorators/token.decorator';
import { Controller, Get, HttpStatus, Req, Res } from '@nestjs/common';
import { ApiExcludeController, ApiResponse } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify';
@Controller() @Controller()
@ApiExcludeController()
export class AppController { export class AppController {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@Get('auth') @Get()
public async auth( getHello(): string {
@Req() req: FastifyRequest, return this.appService.getHello();
@Res() reply: FastifyReply,
@AuthToken() token: string,
@AuthParams() { authMode }: Params
) {
try {
const { aud } = this.appService.checkToken(token);
const originalUri = req.headers['x-original-uri'];
if (
authMode === 'ldap-tfa' &&
aud === 'auth' &&
!['/auth', '/login', '/socket.io'].some((x) => originalUri.includes(x))
) {
return reply.status(HttpStatus.UNAUTHORIZED).send();
}
reply.header('Authorization', `Bearer ${token}`);
return reply.send();
} catch (error) {
return reply.status(HttpStatus.UNAUTHORIZED).send({ message: error.message });
}
}
@Get('/check-auth')
@ApiResponse({
status: HttpStatus.OK,
})
public async checkAuth(
@AuthParams() { authMode }: Params,
@Req() req: FastifyRequest,
@Res() reply: FastifyReply
) {
return reply.redirect(308, `${req.protocol}://${req.headers.host}/${authMode}/check-auth`);
} }
} }

View File

@ -1,16 +1,12 @@
import { AccountModule } from './account/account.module';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { env } from './config/env'; import { env } from './config/env';
import { LdapModule } from './ldap/ldap.module'; import { LdapModule } from './ldap/ldap.module';
import { LdapTfaModule } from './ldap-tfa/ldap-tfa.module'; import { UsersModule } from './users/users.module';
import { CacheModule } from '@nestjs/cache-manager';
import { Global, Module } from '@nestjs/common'; import { Global, Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt'; import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import * as redisStore from 'cache-manager-ioredis';
import type { RedisOptions } from 'ioredis';
@Global() @Global()
@Module({ @Module({
@ -26,17 +22,9 @@ import type { RedisOptions } from 'ioredis';
expiresIn: env.API_TOKEN_TTL, expiresIn: env.API_TOKEN_TTL,
}, },
}), }),
AuthModule,
UsersModule,
LdapModule, LdapModule,
AccountModule,
LdapTfaModule,
MongooseModule.forRoot(`mongodb://${env.MONGO_HOST}`),
CacheModule.register<RedisOptions>({
host: env.REDIS_HOST,
isGlobal: true,
port: env.REDIS_PORT,
store: redisStore,
ttl: env.API_CACHE_TTL,
}),
], ],
providers: [AppService], providers: [AppService],
}) })

View File

@ -1,19 +1,8 @@
import type { DecodedToken } from './types/jwt';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { omit } from 'radash';
@Injectable() @Injectable()
export class AppService { export class AppService {
constructor(private readonly jwtService: JwtService) {} getHello(): string {
return 'Hello World!';
public checkToken(token: string) {
return this.jwtService.verify<DecodedToken>(token);
}
public refreshToken(token: string) {
const payload = this.jwtService.decode<DecodedToken>(token);
return this.jwtService.sign(omit(payload, ['iat', 'exp']));
} }
} }

View File

@ -0,0 +1,21 @@
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
describe('AuthController', () => {
let controller: AuthController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
providers: [AuthService],
}).compile();
controller = module.get<AuthController>(AuthController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,71 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable class-methods-use-this */
/* eslint-disable import/no-extraneous-dependencies */
import { AuthService } from './auth.service';
import { Credentials } from './types/request';
import { Body, Controller, Get, HttpException, HttpStatus, Post, Req, Res } from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';
import { env } from 'src/config/env';
@Controller()
export class AuthController {
cookieOptions: { maxAge: number; path: string };
constructor(private readonly authService: AuthService) {
this.cookieOptions = {
maxAge: env.API_TOKEN_TTL,
path: '/',
};
}
private clearCookies(req, reply) {
if (req.cookies) {
Object.keys(req.cookies).forEach((cookieName) => {
reply.clearCookie(cookieName, {
path: '/',
});
});
}
}
@Post('/signin')
async login(@Body() credentials: Credentials, @Res() reply: FastifyReply) {
const { login, password } = credentials;
try {
const token = await this.authService.login(login, password);
return reply.setCookie(env.COOKIE_TOKEN_NAME, token, this.cookieOptions).status(200).send();
} catch {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
}
}
@Get('/logout')
async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
const token = req.cookies[env.COOKIE_TOKEN_NAME];
if (token) await this.authService.logout(token);
this.clearCookies(req, reply);
return reply.status(302).redirect('/login');
}
@Get('/auth')
async auth(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
const token = req.cookies[env.COOKIE_TOKEN_NAME];
try {
this.authService.checkToken(token);
return reply.send();
} catch (error) {
if (error.name === 'TokenExpiredError') {
const newToken = this.authService.refreshToken(token);
return reply.setCookie(env.COOKIE_TOKEN_NAME, newToken, this.cookieOptions).send();
}
return reply.status(HttpStatus.UNAUTHORIZED).send();
}
}
}

View File

@ -0,0 +1,13 @@
import { LdapModule } from '../ldap/ldap.module';
import { UsersModule } from '../users/users.module';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { Module } from '@nestjs/common';
@Module({
controllers: [AuthController],
imports: [UsersModule, LdapModule],
providers: [AuthService],
})
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class AuthModule {}

View File

@ -0,0 +1,19 @@
import { AuthService } from './auth.service';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,44 @@
import { LdapService } from '../ldap/ldap.service';
import { UsersCache } from '../users/users.cache';
import type { DecodedToken, TokenPayload } from './types/jwt';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { env } from 'src/config/env';
@Injectable()
export class AuthService {
constructor(
private readonly ldapService: LdapService,
private readonly usersCache: UsersCache,
private readonly jwtService: JwtService
) {}
public async login(login: string, password: string) {
const user = await this.ldapService.authenticate(login, password);
const { username } = user;
await this.usersCache.addUser(username, user);
const payload: TokenPayload = {
domain: env.LDAP_DOMAIN,
username,
};
return this.jwtService.sign(payload);
}
public async logout(token: string) {
const { username } = this.jwtService.decode(token) as DecodedToken;
await this.usersCache.deleteUser(username);
}
public checkToken(token: string) {
this.jwtService.verify(token);
}
public refreshToken(token: string) {
const { exp, iat, ...payload } = this.jwtService.decode(token) as DecodedToken;
return this.jwtService.sign(payload);
}
}

View File

@ -0,0 +1,9 @@
export type TokenPayload = {
username: string;
domain: string;
};
export type DecodedToken = {
exp: number;
iat: number;
} & TokenPayload;

View File

@ -0,0 +1,4 @@
export type Credentials = {
login: string;
password: string;
};

View File

@ -1,9 +0,0 @@
import type { CookieSerializeOptions } from '@fastify/cookie';
import { env } from 'src/config/env';
export const cookieOptions: CookieSerializeOptions = {
httpOnly: true,
maxAge: env.COOKIE_TOKEN_MAX_AGE,
path: '/',
secure: true,
};

View File

@ -4,12 +4,7 @@ const envSchema = z.object({
API_CACHE_TTL: z.string().transform((val) => Number.parseInt(val, 10)), API_CACHE_TTL: z.string().transform((val) => Number.parseInt(val, 10)),
API_PORT: z.number().optional().default(3001), API_PORT: z.number().optional().default(3001),
API_SECRET: z.string(), API_SECRET: z.string(),
API_TOKEN_TFA_TTL: z
.string()
.transform((val) => Number.parseInt(val, 10))
.default('300'),
API_TOKEN_TTL: z.string().transform((val) => Number.parseInt(val, 10)), API_TOKEN_TTL: z.string().transform((val) => Number.parseInt(val, 10)),
COOKIE_TOKEN_MAX_AGE: z.string().transform((val) => Number.parseInt(val, 10)),
COOKIE_TOKEN_NAME: z.string().default('token'), COOKIE_TOKEN_NAME: z.string().default('token'),
LDAP_ATTRIBUTE: z.string(), LDAP_ATTRIBUTE: z.string(),
LDAP_BASE: z.string(), LDAP_BASE: z.string(),
@ -17,19 +12,11 @@ const envSchema = z.object({
LDAP_BIND_DN: z.string(), LDAP_BIND_DN: z.string(),
LDAP_DOMAIN: z.string(), LDAP_DOMAIN: z.string(),
LDAP_URL: z.string().url(), LDAP_URL: z.string().url(),
MONGO_HOST: z.string(),
MONGO_PORT: z
.string()
.transform((val) => Number.parseInt(val, 10))
.default('27017'),
REDIS_HOST: z.string(), REDIS_HOST: z.string(),
REDIS_PORT: z REDIS_PORT: z
.string() .string()
.transform((val) => Number.parseInt(val, 10)) .transform((val) => Number.parseInt(val, 10))
.default('6379'), .default('6379'),
TELEGRAM_URL_SEND_AUTH_LOGIN: z.string(),
TELEGRAM_URL_SEND_AUTH_MESSAGE: z.string(),
TELEGRAM_URL_SEND_AUTH_PASSWORD: z.string(),
}); });
export default envSchema; export default envSchema;

View File

@ -1,23 +0,0 @@
import type { ExecutionContext } from '@nestjs/common';
import { createParamDecorator, UnauthorizedException } from '@nestjs/common';
export type AuthMode = 'ldap' | 'ldap-tfa' | 'account' | undefined;
export type RefreshToken = '1' | undefined;
export type Params = {
authMode: AuthMode;
refreshToken: boolean;
};
export const AuthParams = createParamDecorator<Params>((_data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const authMode = request.headers['auth-mode'] as AuthMode;
const refreshToken = (request.headers['refresh-token'] as RefreshToken) === '1';
if (!authMode) throw new UnauthorizedException('Auth mode is missing');
return {
authMode,
refreshToken,
} as Params;
});

View File

@ -1,14 +0,0 @@
import { env } from '../config/env';
import type { ExecutionContext } from '@nestjs/common';
import { createParamDecorator, UnauthorizedException } from '@nestjs/common';
export const AuthToken = createParamDecorator((_data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const token =
request.cookies[env.COOKIE_TOKEN_NAME] || request.headers?.authorization?.split(' ')[1];
if (!token) throw new UnauthorizedException('Token is missing');
return token;
});

View File

@ -1,14 +0,0 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class Credentials {
@ApiProperty()
@IsString()
@IsNotEmpty()
readonly login: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
readonly password: string;
}

View File

@ -1,14 +0,0 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class TelegramDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
readonly authId: string;
@ApiProperty()
@IsString()
@IsNotEmpty()
readonly employeeID: string;
}

View File

@ -1,116 +0,0 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { LdapTfaService } from './ldap-tfa.service';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import {
Body,
Controller,
Get,
HttpException,
HttpStatus,
Inject,
Post,
Query,
Req,
Res,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { ApiResponse, ApiTags } from '@nestjs/swagger';
import axios from 'axios';
import { Cache } from 'cache-manager';
import { FastifyReply, FastifyRequest } from 'fastify';
import { cookieOptions } from 'src/config/cookie';
import { env } from 'src/config/env';
import { AuthToken } from 'src/decorators/token.decorator';
import { Credentials } from 'src/dto/credentials';
import { TelegramDto } from 'src/dto/tfa';
import { LdapController } from 'src/ldap/ldap.controller';
import { LdapTfaGateway } from 'src/ldap-tfa/ldap-tfa.gateway';
@Controller('ldap-tfa')
@ApiTags('ldap-tfa')
export class LdapTfaController extends LdapController {
constructor(
protected readonly ldapTfaService: LdapTfaService,
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
private readonly ldapTfaGateway: LdapTfaGateway
) {
super(ldapTfaService);
}
@Post('/login')
@ApiResponse({
status: HttpStatus.OK,
})
async login(
@Body() credentials: Credentials,
@Req() _req: FastifyRequest,
@Res() reply: FastifyReply
) {
try {
const authId = crypto.randomUUID();
const token = await this.ldapTfaService.login(credentials, { authId });
const user = await this.ldapTfaService.getUser(token);
await this.cacheManager.set(authId, user, env.API_TOKEN_TFA_TTL);
return reply.setCookie(env.COOKIE_TOKEN_NAME, token, cookieOptions).status(200).send(user);
} catch {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
}
}
@Post('/login-telegram')
@ApiResponse({
status: HttpStatus.OK,
})
async loginTelegram(@AuthToken() token: string, @Res() reply: FastifyReply) {
const { employeeID } = await this.ldapTfaService.getUser(token, { audience: 'auth' });
const { authId } = await this.ldapTfaService.parseToken(token, { audience: 'auth' });
return axios
.get(env.TELEGRAM_URL_SEND_AUTH_MESSAGE, {
auth: {
password: env.TELEGRAM_URL_SEND_AUTH_PASSWORD,
username: env.TELEGRAM_URL_SEND_AUTH_LOGIN,
},
params: {
authId,
employeeID,
},
})
.then((res) => reply.status(200).send(res.data))
.catch(() => reply.status(500).send());
}
@Get('/telegram-confirm')
@ApiResponse({
status: HttpStatus.OK,
})
@UsePipes(new ValidationPipe({ transform: true }))
async telegramConfirm(@Query() query: TelegramDto, @Res() reply: FastifyReply) {
this.ldapTfaGateway.notify('auth-allow', query);
return reply.status(200).send({ success: true });
}
@Get('/telegram-reject')
@ApiResponse({
status: HttpStatus.OK,
})
@UsePipes(new ValidationPipe({ transform: true }))
async telegramReject(@Query() query: TelegramDto, @Res() reply: FastifyReply) {
this.ldapTfaGateway.notify('auth-deny', query);
return reply.status(200).send({ success: true });
}
@Get('/login-confirm')
@ApiResponse({
status: HttpStatus.OK,
})
async loginConfirm(@AuthToken() token: string, @Res() reply: FastifyReply) {
const activatedToken = await this.ldapTfaService.activateToken(token, { audience: 'auth' });
return reply.setCookie(env.COOKIE_TOKEN_NAME, activatedToken, cookieOptions).status(200).send();
}
}

View File

@ -1,49 +0,0 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import type { OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Cache } from 'cache-manager';
import type { Socket } from 'socket.io';
import { Server } from 'socket.io';
import { env } from 'src/config/env';
import type { TelegramDto } from 'src/dto/tfa';
import type { DecodedToken } from 'src/types/jwt';
import type { User } from 'src/utils/ldap';
type UserWithSocketId = User & { socketId: string };
@WebSocketGateway({ cors: { credentials: true } })
export class LdapTfaGateway implements OnGatewayConnection, OnGatewayDisconnect {
constructor(
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
private readonly jwtService: JwtService
) {
this.cacheManager = cacheManager;
}
@WebSocketServer() server: Server;
async handleConnection(client: Socket, ...args: any[]) {
const token = client.request.headers?.authorization?.split(' ')[1];
const { authId } = this.jwtService.decode(token) as DecodedToken;
const cached = this.cacheManager.get<User>(authId);
await this.cacheManager.set(authId, { ...cached, socketId: client.id }, env.API_TOKEN_TFA_TTL);
}
async handleDisconnect(client: Socket) {
const token = client.request.headers?.authorization?.split(' ')[1];
const { authId } = this.jwtService.decode(token) as DecodedToken;
await this.cacheManager.del(authId);
}
async notify<T>(event: string, { authId }: TelegramDto): Promise<void> {
const { socketId } = await this.cacheManager.get<UserWithSocketId>(authId);
this.server.to([socketId]).emit(event);
await this.cacheManager.del(authId);
}
}

View File

@ -1,14 +0,0 @@
/* eslint-disable @typescript-eslint/no-extraneous-class */
import { LdapTfaController } from './ldap-tfa.controller';
import { LdapTfaService } from './ldap-tfa.service';
import { Module } from '@nestjs/common';
import { LdapModule } from 'src/ldap/ldap.module';
import { LdapTfaGateway } from 'src/ldap-tfa/ldap-tfa.gateway';
@Module({
controllers: [LdapTfaController],
exports: [LdapTfaService],
imports: [LdapModule],
providers: [LdapTfaGateway, LdapTfaService],
})
export class LdapTfaModule {}

View File

@ -1,57 +0,0 @@
/* eslint-disable unicorn/no-object-as-default-parameter */
import type { TokenPayload } from '../types/jwt';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject, UnauthorizedException } from '@nestjs/common';
import type { JwtVerifyOptions } from '@nestjs/jwt';
import { JwtService } from '@nestjs/jwt';
import { Cache } from 'cache-manager';
import { env } from 'src/config/env';
import type { Credentials } from 'src/dto/credentials';
import { LdapService } from 'src/ldap/ldap.service';
import * as ldap from 'src/utils/ldap';
import type { PartialBy } from 'src/utils/types';
export class LdapTfaService extends LdapService {
constructor(
@Inject(CACHE_MANAGER) protected readonly cacheManager: Cache,
protected readonly jwtService: JwtService
) {
super(cacheManager, jwtService);
}
public async login(credentials: PartialBy<Credentials, 'password'>, additionalPayload?: object) {
try {
const user = await ldap.authenticate(credentials.login, credentials.password);
const { username } = user;
await this.cacheManager.set(username, user);
const payload: TokenPayload = {
domain: env.LDAP_DOMAIN,
username,
...additionalPayload,
};
return this.jwtService.sign(payload, { audience: 'auth' });
} catch (error) {
throw new UnauthorizedException(error);
}
}
public async activateToken(token: string, options: JwtVerifyOptions = { audience: 'auth' }) {
try {
const { username } = this.jwtService.verify<TokenPayload>(token, options);
const user = await ldap.authenticate(username);
await this.cacheManager.set(username, user);
const payload: TokenPayload = {
domain: env.LDAP_DOMAIN,
username,
};
return this.jwtService.sign(payload);
} catch (error) {
throw new UnauthorizedException(error);
}
}
}

View File

@ -1,118 +0,0 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable class-methods-use-this */
/* eslint-disable import/no-extraneous-dependencies */
import { Credentials } from '../dto/credentials';
import { LdapService } from './ldap.service';
import type { CookieSerializeOptions } from '@fastify/cookie';
import {
Body,
Controller,
Get,
HttpException,
HttpStatus,
Post,
Req,
Res,
UnauthorizedException,
} from '@nestjs/common';
import { ApiResponse, ApiTags } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify';
import { cookieOptions } from 'src/config/cookie';
import { env } from 'src/config/env';
import { AuthParams, Params } from 'src/decorators/auth-mode.decorator';
import { AuthToken } from 'src/decorators/token.decorator';
import type { BaseAuthController } from 'src/types/auth-controller';
import { User } from 'src/utils/ldap';
@Controller('ldap')
@ApiTags('ldap')
export class LdapController implements BaseAuthController {
cookieOptions: CookieSerializeOptions;
constructor(protected readonly ldapService: LdapService) {}
private clearCookies(req, reply) {
if (req.cookies) {
Object.keys(req.cookies).forEach((cookieName) => {
reply.clearCookie(cookieName, {
path: '/',
});
});
}
}
@Post('/login')
@ApiResponse({
status: HttpStatus.OK,
})
async login(
@Body() credentials: Credentials,
@Req() _req: FastifyRequest,
@Res() reply: FastifyReply
) {
try {
const token = await this.ldapService.login(credentials);
return reply.setCookie(env.COOKIE_TOKEN_NAME, token, cookieOptions).status(200).send();
} catch {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
}
}
@Get('/logout')
async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply, @AuthToken() token: string) {
if (token) await this.ldapService.logout(token);
this.clearCookies(req, reply);
return reply.status(302).redirect('/');
}
@Get('/refresh-token')
@ApiResponse({
status: HttpStatus.OK,
})
async refreshToken(
@AuthToken() token: string,
@AuthParams() { refreshToken }: Params,
@Res() reply: FastifyReply
) {
if (!refreshToken) return reply.status(HttpStatus.UNAUTHORIZED).send();
const newToken = await this.ldapService.refreshToken(token);
reply.header('Authorization', `Bearer ${newToken}`);
return reply.setCookie(env.COOKIE_TOKEN_NAME, newToken, cookieOptions).send();
}
@Get('/get-user')
@ApiResponse({
status: HttpStatus.OK,
type: User,
})
async getUser(
@Req() _req: FastifyRequest,
@Res() reply: FastifyReply,
@AuthToken() token: string
) {
const user = await this.ldapService.getUser(token);
if (!user) throw new UnauthorizedException('User not found');
return reply.send(user);
}
@Get('/check-auth')
@ApiResponse({
status: HttpStatus.OK,
})
async checkAuth(@AuthToken() token: string, @Res() reply: FastifyReply) {
const { authId } = await this.ldapService.parseToken(token, { ignoreExpiration: true });
if (authId) return reply.status(HttpStatus.UNAUTHORIZED).send();
const user = await this.ldapService.getUser(token, { ignoreExpiration: true });
return reply.status(200).send(user);
}
}

View File

@ -1,11 +1,8 @@
import { LdapController } from './ldap.controller';
import { LdapService } from './ldap.service'; import { LdapService } from './ldap.service';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
@Module({ @Module({
controllers: [LdapController],
exports: [LdapService], exports: [LdapService],
imports: [],
providers: [LdapService], providers: [LdapService],
}) })
// eslint-disable-next-line @typescript-eslint/no-extraneous-class // eslint-disable-next-line @typescript-eslint/no-extraneous-class

View File

@ -0,0 +1,19 @@
import { LdapService } from './ldap.service';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
describe('LdapService', () => {
let service: LdapService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [LdapService],
}).compile();
service = module.get<LdapService>(LdapService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -1,94 +1,44 @@
import type { DecodedToken, TokenPayload } from '../types/jwt'; import { env } from '../config/env';
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import type { User } from '../types/user';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'; import type { LdapUser } from './types/user';
import type { JwtSignOptions, JwtVerifyOptions } from '@nestjs/jwt'; import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'; import type { AuthenticationOptions } from 'ldap-authentication';
import { Cache } from 'cache-manager'; import { authenticate } from 'ldap-authentication';
import { env } from 'src/config/env';
import type { Credentials } from 'src/dto/credentials';
import * as ldap from 'src/utils/ldap';
@Injectable() @Injectable()
export class LdapService { export class LdapService {
constructor( public async authenticate(login: string, password?: string) {
@Inject(CACHE_MANAGER) protected readonly cacheManager: Cache, const options: AuthenticationOptions = {
protected readonly jwtService: JwtService adminDn: env.LDAP_BIND_DN,
) {} adminPassword: env.LDAP_BIND_CREDENTIALS,
ldapOpts: {
public async login(credentials: Credentials, options?: JwtSignOptions) { url: env.LDAP_URL,
try { },
const user = await ldap.authenticate(credentials.login, credentials.password); userPassword: password,
const { username } = user; userSearchBase: env.LDAP_BASE,
username: login,
await this.cacheManager.set(username, user); usernameAttribute: env.LDAP_ATTRIBUTE,
verifyUserExists: password === undefined,
const payload: TokenPayload = {
domain: env.LDAP_DOMAIN,
username,
}; };
return this.jwtService.sign(payload, options); const {
} catch (error) { displayName,
throw new UnauthorizedException(error); department,
} title,
} mail,
sAMAccountName: username,
}: LdapUser = await authenticate(options);
public async logout(token: string) { const user: User = {
const { username } = this.jwtService.decode(token) as DecodedToken; department,
displayName,
if (this.cacheManager.get(username)) {
await this.cacheManager.del(username);
}
}
public async refreshToken(token: string) {
try {
const { username, aud = '' } = this.jwtService.verify<DecodedToken>(token, {
ignoreExpiration: true,
});
if (aud === 'auth') throw new UnauthorizedException();
const user = await ldap.authenticate(username);
await this.cacheManager.set(username, user);
const payload: TokenPayload = {
domain: env.LDAP_DOMAIN, domain: env.LDAP_DOMAIN,
domainName: `${env.LDAP_DOMAIN}\\${username}`,
mail,
position: title,
username, username,
}; };
return this.jwtService.sign(payload);
} catch (error) {
throw new UnauthorizedException(error);
}
}
public async getUser(token: string, options?: JwtVerifyOptions) {
try {
const { username } = this.jwtService.verify(token, options) as DecodedToken;
const cachedUser = await this.cacheManager.get<ldap.User>(username);
if (!cachedUser) {
const user = await ldap.authenticate(username);
await this.cacheManager.set(username, user);
return user; return user;
} }
return cachedUser;
} catch {
throw new UnauthorizedException('Invalid token');
}
}
public async parseToken(token: string, options?: JwtVerifyOptions) {
try {
return this.jwtService.verify<TokenPayload>(token, options);
} catch (error) {
throw new UnauthorizedException(error);
}
}
} }

View File

@ -1,27 +1,3 @@
import { ApiResponseProperty } from '@nestjs/swagger';
import type { AuthenticationOptions } from 'ldap-authentication';
import * as ldap from 'ldap-authentication';
import { env } from 'src/config/env';
export class User {
@ApiResponseProperty()
public department: string;
@ApiResponseProperty()
public displayName: string;
@ApiResponseProperty()
public domain: string;
@ApiResponseProperty()
public domainName: string;
@ApiResponseProperty()
public mail: string;
@ApiResponseProperty()
public position: string;
@ApiResponseProperty()
public username: string;
@ApiResponseProperty()
public employeeID: string;
}
export type LdapUser = { export type LdapUser = {
accountExpires: string; accountExpires: string;
badPasswordTime: string; badPasswordTime: string;
@ -85,44 +61,3 @@ export type LdapUser = {
whenChanged: string; whenChanged: string;
whenCreated: string; whenCreated: string;
}; };
const BASE_OPTIONS: AuthenticationOptions = {
adminDn: env.LDAP_BIND_DN,
adminPassword: env.LDAP_BIND_CREDENTIALS,
ldapOpts: {
url: env.LDAP_URL,
},
userSearchBase: env.LDAP_BASE,
usernameAttribute: env.LDAP_ATTRIBUTE,
};
export async function authenticate(login: string, password?: string) {
const options: AuthenticationOptions = {
...BASE_OPTIONS,
userPassword: password,
username: login,
verifyUserExists: password === undefined,
};
const {
displayName,
department,
title,
mail,
sAMAccountName: username,
employeeID,
}: LdapUser = await ldap.authenticate(options);
const user: User = {
department,
displayName,
domain: env.LDAP_DOMAIN,
domainName: `${env.LDAP_DOMAIN}\\${username}`,
employeeID,
mail,
position: title,
username,
};
return user;
}

View File

@ -1,24 +1,10 @@
/* eslint-disable import/no-duplicates */
/* eslint-disable unicorn/prefer-top-level-await */ /* eslint-disable unicorn/prefer-top-level-await */
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { env } from './config/env'; import { env } from './config/env';
import { fastifyCookie } from '@fastify/cookie'; import { fastifyCookie } from '@fastify/cookie';
import type { INestApplication } from '@nestjs/common';
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import type { NestFastifyApplication } from '@nestjs/platform-fastify'; import type { NestFastifyApplication } from '@nestjs/platform-fastify';
import { FastifyAdapter } from '@nestjs/platform-fastify'; import { FastifyAdapter } from '@nestjs/platform-fastify';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
function setupOpenApi(app: INestApplication) {
const config = new DocumentBuilder()
.setTitle('Evo.Auth')
.setVersion('1.0')
// .addTag('api')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('swagger', app, document, { useGlobalPrefix: true });
}
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>( const app = await NestFactory.create<NestFastifyApplication>(
@ -32,10 +18,6 @@ async function bootstrap() {
secret: env.API_SECRET, secret: env.API_SECRET,
}); });
app.useGlobalPipes(new ValidationPipe({ stopAtFirstError: true }));
setupOpenApi(app);
await app.listen(env.API_PORT, '0.0.0.0'); await app.listen(env.API_PORT, '0.0.0.0');
} }

View File

@ -1,51 +0,0 @@
/* eslint-disable @babel/no-invalid-this */
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { ApiProperty, ApiResponseProperty } from '@nestjs/swagger';
import * as bcrypt from 'bcrypt';
import type { HydratedDocument } from 'mongoose';
export type UserDocument = HydratedDocument<Account>;
@Schema({ strict: false })
export class Account {
@ApiResponseProperty()
@ApiProperty()
@Prop({ index: { unique: true }, required: true })
public username: string;
@ApiResponseProperty()
@ApiProperty()
@Prop({ required: true })
public password: string;
readonly [key: string]: unknown;
}
export const AccountSchema = SchemaFactory.createForClass(Account);
AccountSchema.pre('save', async function (next) {
try {
if (!this.isModified('password')) return next();
const hash = await bcrypt.hash(this.password, 10);
this.password = hash;
return next();
} catch (error) {
return next(error);
}
});
AccountSchema.pre('findOneAndUpdate', async function (next) {
try {
const password = this.get('password');
if (password) {
const hash = await bcrypt.hash(password, 10);
this.set('password', hash);
}
return next();
} catch (error) {
return next(error);
}
});

View File

@ -1,8 +0,0 @@
import type { FastifyReply, FastifyRequest } from 'fastify';
import type { Credentials } from 'src/dto/credentials';
export type BaseAuthController = {
getUser: (req: FastifyRequest, reply: FastifyReply, token: string) => Promise<never>;
login: (credentials: Credentials, req: FastifyRequest, reply: FastifyReply) => Promise<never>;
logout: (req: FastifyRequest, reply: FastifyReply, token: string) => Promise<never>;
};

View File

@ -1,13 +0,0 @@
import type { JwtSignOptions } from '@nestjs/jwt';
export type TokenPayload = {
[key: string]: unknown;
authId?: string;
username: string;
};
export type DecodedToken = {
aud?: JwtSignOptions['audience'];
exp: number;
iat: number;
} & TokenPayload;

View File

@ -1,4 +1,4 @@
export type LdapUser = { export type User = {
department: string; department: string;
displayName: string; displayName: string;
domain: string; domain: string;

View File

@ -0,0 +1,22 @@
import type { User } from '../types/user';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
@Injectable()
export class UsersCache {
constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {}
async getUser(username: string) {
return (await this.cacheManager.get(username)) as User;
}
async addUser(username: string, user: User) {
await this.cacheManager.set(username, user);
}
async deleteUser(username: string) {
if (this.cacheManager.get(username)) {
await this.cacheManager.del(username);
}
}
}

View File

@ -0,0 +1,21 @@
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
describe('UsersController', () => {
let controller: UsersController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [UsersService],
}).compile();
controller = module.get<UsersController>(UsersController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,21 @@
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable class-methods-use-this */
/* eslint-disable import/no-extraneous-dependencies */
import { UsersService } from './users.service';
import { Controller, Get, Req, Res } from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';
import { env } from 'src/config/env';
@Controller()
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get('/get-user')
async getUser(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
const token = req.cookies[env.COOKIE_TOKEN_NAME];
const user = await this.usersService.getUser(token);
return reply.send(user);
}
}

View File

@ -0,0 +1,26 @@
import { LdapModule } from '../ldap/ldap.module';
import { UsersCache } from './users.cache';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { CacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-ioredis';
import type { RedisOptions } from 'ioredis';
import { env } from 'src/config/env';
@Module({
controllers: [UsersController],
exports: [UsersCache],
imports: [
CacheModule.register<RedisOptions>({
host: env.REDIS_HOST,
port: env.REDIS_PORT,
store: redisStore,
ttl: env.API_CACHE_TTL,
}),
LdapModule,
],
providers: [UsersService, UsersCache],
})
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class UsersModule {}

View File

@ -0,0 +1,19 @@
import { UsersService } from './users.service';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,30 @@
import type { DecodedToken } from '../auth/types/jwt';
import { LdapService } from '../ldap/ldap.service';
import { UsersCache } from './users.cache';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class UsersService {
constructor(
private readonly usersCache: UsersCache,
private readonly jwtService: JwtService,
private readonly ldapService: LdapService
) {}
public async getUser(token: string) {
const { username } = this.jwtService.decode(token) as DecodedToken;
const cachedUser = await this.usersCache.getUser(username);
if (!cachedUser) {
const user = await this.ldapService.authenticate(username);
await this.usersCache.addUser(username, user);
return user;
}
return cachedUser;
}
}

View File

@ -1,3 +0,0 @@
export function isTokenExpired(error: Error) {
return error.name?.toLocaleLowerCase().includes('expired');
}

View File

@ -1,7 +0,0 @@
const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$';
export function generatePassword(length = 10) {
return Array.from(crypto.getRandomValues(new Uint32Array(length)))
.map((x) => characters[x % characters.length])
.join('');
}

View File

@ -1 +0,0 @@
export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

View File

@ -17,6 +17,5 @@
"strictBindCallApply": false, "strictBindCallApply": false,
"forceConsistentCasingInFileNames": false, "forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false "noFallthroughCasesInSwitch": false
}, }
"exclude": ["node_modules"]
} }

5767
apps/api/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,11 @@
const { createConfig } = require('@vchikalkin/eslint-config-awesome'); module.exports = {
extends: [
module.exports = createConfig('next-typescript', { '@vchikalkin/eslint-config-awesome/next-typescript/config',
'@vchikalkin/eslint-config-awesome/next-typescript/rules',
],
parserOptions: { parserOptions: {
project: './tsconfig.json', project: './tsconfig.json',
tsconfigRootDir: __dirname, tsconfigRootDir: __dirname,
}, },
rules: { root: true,
'import/no-duplicates': 'off', };
'import/consistent-type-specifier-style': 'off',
'react/forbid-component-props': 'off',
},
ignorePatterns: ['*.config.js', '.eslintrc.js'],
});

View File

@ -2,49 +2,47 @@
# Make sure you update both files! # Make sure you update both files!
FROM node:alpine AS builder FROM node:alpine AS builder
RUN corepack enable && corepack prepare pnpm@8.9.0 --activate
ENV PNPM_HOME=/usr/local/bin
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed. # Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat RUN apk add --no-cache libc6-compat
RUN apk update RUN apk update
# Set working directory # Set working directory
WORKDIR /app WORKDIR /app
RUN pnpm add -g turbo@1.12.4 dotenv-cli RUN yarn global add turbo
RUN yarn global add dotenv-cli
COPY . . COPY . .
RUN turbo prune --scope=web --docker RUN turbo prune --scope=web --docker
# Add lockfile and package.json's of isolated subworkspace # Add lockfile and package.json's of isolated subworkspace
FROM node:alpine AS installer FROM node:alpine AS installer
RUN corepack enable && corepack prepare pnpm@8.9.0 --activate
ENV PNPM_HOME=/usr/local/bin
RUN apk add --no-cache libc6-compat RUN apk add --no-cache libc6-compat
RUN apk update RUN apk update
WORKDIR /app WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED 1
# First install the dependencies (as they change less often) # First install the dependencies (as they change less often)
COPY .gitignore .gitignore COPY .gitignore .gitignore
COPY --from=builder /app/out/json/ . COPY --from=builder /app/out/json/ .
COPY --from=builder /app/out/pnpm-lock.yaml ./pnpm-lock.yaml COPY --from=builder /app/out/yarn.lock ./yarn.lock
COPY --from=builder /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml RUN yarn install
RUN pnpm install
# Build the project # Build the project
COPY --from=builder /app/out/full/ . COPY --from=builder /app/out/full/ .
COPY turbo.json turbo.json COPY turbo.json turbo.json
ARG APP_BASE_PATH COPY .env .env
ARG APP_DESCRIPTION RUN yarn dotenv -e .env turbo run build --filter=web...
ARG TELEGRAM_BOT_URL
RUN pnpm dotenv -e .env turbo run build --filter=web...
FROM node:alpine AS runner FROM node:alpine AS runner
WORKDIR /app WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED 1
# Don't run production as root # Don't run production as root
RUN addgroup --system --gid 1001 nodejs RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs RUN adduser --system --uid 1001 nextjs
USER nextjs USER nextjs
COPY --from=installer /app/apps/web/next.config.js . COPY --from=installer /app/apps/web/next.config.mjs .
COPY --from=installer /app/apps/web/package.json . COPY --from=installer /app/apps/web/package.json .
# Automatically leverage output traces to reduce image size # Automatically leverage output traces to reduce image size

View File

@ -0,0 +1,47 @@
import styles from './Form.module.scss';
import { publicRuntimeConfig } from '@/config/runtime';
import Button from '@/elements/Button';
import Error from '@/elements/Error';
import { H3 } from '@/elements/H';
import Input from '@/elements/Input';
import axios from 'axios';
import { useState } from 'react';
const { APP_BASE_PATH, APP_TITLE } = publicRuntimeConfig;
export default function Form() {
const [hasError, setHasError] = useState(false);
const error = hasError ? <Error>Неверный логин или пароль</Error> : null;
return (
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
const login = e.target[0].value;
const password = e.target[1].value;
const data = { login, password };
axios
.post('/signin', data)
.then(() => {
const url =
(window.location.pathname.replace(APP_BASE_PATH, '') || '/') +
(window.location.search || '');
window.location.replace(url);
})
.catch(() => {
setHasError(true);
});
}}
>
<H3>{APP_TITLE}</H3>
<Input name="login" type="text" placeholder="Логин" required autoComplete="on" />
<Input name="password" type="password" placeholder="Пароль" required autoComplete="on" />
{error}
<Button>Войти</Button>
</form>
);
}

View File

@ -1,44 +0,0 @@
import styles from './Form.module.scss';
import type { FormData, FormProps } from './lib/types';
import { publicRuntimeConfig } from '@/config/runtime';
import { FormStateContext } from '@/context/form-state';
import type { PropsWithChildren } from 'react';
import { useContext } from 'react';
import { useForm } from 'react-hook-form';
const { TELEGRAM_BOT_URL } = publicRuntimeConfig;
export function BaseForm({ children, onSubmit }: FormProps & PropsWithChildren) {
const { handleSubmit, register } = useForm<FormData>();
const {
state: { error, step },
} = useContext(FormStateContext);
return (
<form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
<input
disabled={step !== 'login'}
type="text"
placeholder="Логин"
required
autoComplete="on"
{...register('login', { required: true })}
/>
<input
disabled={step !== 'login'}
type="password"
placeholder="Пароль"
required
autoComplete="on"
{...register('password', { required: true })}
/>
{step === 'login-success' || step === 'telegram-notification' ? (
<a target="_blank" className="info" href={TELEGRAM_BOT_URL} rel="noreferrer">
Открыть чат с ботом
</a>
) : null}
{error ? <span className="error">{error}</span> : null}
{children}
</form>
);
}

View File

@ -1,25 +0,0 @@
import { BaseForm } from './base-form';
import { useLogin } from './hooks/default';
import { useRefreshToken } from './hooks/token';
import { ButtonLoading, ButtonLogin } from './lib/buttons';
import { FormStateContext } from '@/context/form-state';
import { useContext } from 'react';
export function DefaultForm() {
useRefreshToken();
const { handleLogin } = useLogin();
const {
state: { step },
} = useContext(FormStateContext);
if (step === 'refresh-token') {
return <ButtonLoading>Подождите...</ButtonLoading>;
}
return (
<BaseForm onSubmit={(data) => handleLogin(data)}>
<ButtonLogin>Войти</ButtonLogin>
</BaseForm>
);
}

View File

@ -1,24 +0,0 @@
import type { FormData } from '../lib/types';
import { redirect } from '@/components/Form/lib/utils';
import { ERROR_INVALID_CREDENTIALS } from '@/constants/errors';
import { FormStateContext } from '@/context/form-state';
import axios from 'axios';
import { useContext } from 'react';
export function useLogin() {
const { dispatch } = useContext(FormStateContext);
function handleLogin(data: FormData) {
return axios
.post('/login', data)
.then(() => redirect())
.catch(() =>
dispatch({
payload: { error: ERROR_INVALID_CREDENTIALS },
type: 'set-error',
})
);
}
return { handleLogin };
}

View File

@ -1,2 +0,0 @@
export * from './socket';
export * from './token';

View File

@ -1,11 +0,0 @@
import { useMemo } from 'react';
import { io } from 'socket.io-client';
export function useSocket() {
const socket = useMemo(
() => io({ autoConnect: false, path: '/socket.io', reconnectionAttempts: 3 }),
[]
);
return { socket };
}

View File

@ -1,101 +0,0 @@
import type { FormData } from '../lib/types';
import { useSocket } from './socket';
import { redirect } from '@/components/Form/lib/utils';
import {
ERROR_INVALID_CREDENTIALS,
ERROR_SERVER,
ERROR_TELEGRAM_SEND_MESSAGE,
} from '@/constants/errors';
import { FormStateContext } from '@/context/form-state';
import type { LdapUser } from '@/types/user';
import axios from 'axios';
import { useContext, useEffect } from 'react';
export function useLogin() {
const { dispatch } = useContext(FormStateContext);
function handleLogin(data: FormData) {
axios
.post<LdapUser>('/login', data)
.then((res) => {
dispatch({
payload: {
step: 'login-success',
user: res.data,
},
type: 'set-step',
});
})
.catch(() =>
dispatch({
payload: { error: ERROR_INVALID_CREDENTIALS },
type: 'set-error',
})
);
}
return { handleLogin };
}
export function useTelegramLogin() {
const { dispatch } = useContext(FormStateContext);
function handleTelegramLogin() {
axios
.post<LdapUser>('/login-telegram')
.then(() => {
dispatch({
payload: {
step: 'telegram-notification',
},
type: 'set-step',
});
})
.catch(() =>
dispatch({
payload: { error: ERROR_TELEGRAM_SEND_MESSAGE },
type: 'set-error',
})
);
}
return { handleTelegramLogin };
}
export function useTelegramConfirm() {
const {
dispatch,
state: { step },
} = useContext(FormStateContext);
const { socket } = useSocket();
useEffect(() => {
if (step === 'telegram-notification') {
socket.open();
socket.on('connect', () => {});
socket.on('auth-allow', () => {
socket.off('connect');
axios
.get('/login-confirm')
.then(() => redirect())
.catch(() =>
dispatch({
payload: { error: ERROR_SERVER },
type: 'set-error',
})
);
});
socket.on('auth-deny', () => {
socket.off('connect');
window.location.reload();
});
}
return () => {
socket.off('connect');
};
}, [dispatch, socket, step]);
}

View File

@ -1,28 +0,0 @@
import { redirect } from '@/components/Form/lib/utils';
import { ERROR_SERVER } from '@/constants/errors';
import { FormStateContext } from '@/context/form-state';
import axios from 'axios';
import { useContext, useEffect } from 'react';
export function useRefreshToken() {
const {
dispatch,
state: { step, user },
} = useContext(FormStateContext);
function handleRefreshToken() {
axios
.get('/refresh-token')
.then(() => redirect())
.catch(() =>
dispatch({
payload: { error: ERROR_SERVER, user: undefined },
type: 'set-error',
})
);
}
useEffect(() => {
if (step === 'refresh-token') handleRefreshToken();
}, []);
}

View File

@ -1,2 +0,0 @@
export * from './default-form';
export * from './telegram-form';

View File

@ -1,55 +0,0 @@
.button-submit {
display: flex;
justify-content: center;
align-items: center;
}
.button-telegram {
@extend .button-submit;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
// text-transform: none;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
animation: colorTransition 1s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.button-telegram {
img {
margin: 0;
margin-right: 10px;
}
}
@keyframes colorTransition {
0% {
background-color: var(--color-primary);
}
100% {
background-color: #54a9eb;
}
}
.button-telegram-icon {
filter: brightness(0) invert(1);
margin: 0 !important;
margin-right: 13px !important;
margin-left: none !important;
}
.spinner-icon {
filter: brightness(0) invert(1);
fill: var(--color-primary);
margin: 0 !important;
margin-right: 6px !important;
}
.loading-wrapper {
display: flex;
justify-content: center;
align-items: center;
}

View File

@ -1,56 +0,0 @@
import styles from './buttons.module.scss';
import Spinner from '@/public/assets/animated/90-ring.svg';
import TelegramIcon from '@/public/assets/images/telegram.svg?url';
import Image from 'next/image';
import type { ButtonHTMLAttributes } from 'react';
type Props = ButtonHTMLAttributes<HTMLButtonElement>;
export function ButtonLogin(props: Props) {
return (
<button className={styles['button-submit']} type="submit" {...props}>
{props.children}
</button>
);
}
export function ButtonLoading(props: Props) {
return (
<button disabled type="button" className={styles['button-submit']} {...props}>
<div className={styles['loading-wrapper']}>
<Spinner alt="spinner" className={styles['spinner-icon']} />
{props.children}
</div>
</button>
);
}
export function ButtonTelegram(props: Props) {
return (
<button type="submit" className={styles['button-telegram']} {...props}>
<Image
className={styles['button-telegram-icon']}
src={TelegramIcon}
width={24}
height={22}
alt="Telegram icon"
/>
{props.children}
</button>
);
}
export function ButtonTelegramLogin(props: Props) {
return (
<button disabled type="submit" className={styles['button-telegram']} {...props}>
<Image
className={styles['button-telegram-icon']}
src={TelegramIcon}
width={24}
height={22}
alt="Telegram icon"
/>
{props.children}
</button>
);
}

View File

@ -1,7 +0,0 @@
export type FormData = {
readonly login: string;
readonly password: string;
};
export type FormProps = {
readonly onSubmit: (data: FormData) => void;
};

View File

@ -1,10 +0,0 @@
import { publicRuntimeConfig } from '@/config/runtime';
const { APP_BASE_PATH } = publicRuntimeConfig;
export function redirect() {
const redirectUrl =
(window.location.pathname.replace(APP_BASE_PATH, '') || '/') + (window.location.search || '');
window.location.replace(redirectUrl);
}

View File

@ -1,43 +0,0 @@
import { BaseForm } from './base-form';
import { useLogin, useTelegramConfirm, useTelegramLogin } from './hooks/telegram';
import { useRefreshToken } from './hooks/token';
import { ButtonLoading, ButtonLogin, ButtonTelegram, ButtonTelegramLogin } from './lib/buttons';
import { FormStateContext } from '@/context/form-state';
import { useContext } from 'react';
export function TelegramForm() {
useRefreshToken();
const { handleLogin } = useLogin();
const { handleTelegramLogin } = useTelegramLogin();
useTelegramConfirm();
const {
state: { step },
} = useContext(FormStateContext);
if (step === 'refresh-token') {
return <ButtonLoading>Подождите...</ButtonLoading>;
}
if (step === 'login-success') {
return (
<BaseForm onSubmit={() => handleTelegramLogin()}>
<ButtonTelegram>Войти через Telegram</ButtonTelegram>
</BaseForm>
);
}
if (step === 'telegram-notification') {
return (
<BaseForm onSubmit={() => {}}>
<ButtonTelegramLogin>Ожидаем подтверждения...</ButtonTelegramLogin>
</BaseForm>
);
}
return (
<BaseForm onSubmit={(data) => handleLogin(data)}>
<ButtonLogin>Далее</ButtonLogin>
</BaseForm>
);
}

View File

@ -0,0 +1,14 @@
import Form from './Form';
import styles from './Login.module.scss';
import Logo from '@/elements/Logo';
export default function Login() {
return (
<div className={styles.wrapper}>
<div className={styles.login}>
<Logo />
<Form />
</div>
</div>
);
}

View File

@ -1,9 +1,9 @@
$layout-breakpoint-tablet: 768px; $layout-breakpoint-desktop: 768px;
$layout-breakpoint-desktop: 1680px;
@mixin center-elements { @mixin center-elements {
display: grid; display: flex;
place-items: center; justify-content: center;
align-items: center;
} }
.wrapper { .wrapper {
@ -19,23 +19,23 @@ $layout-breakpoint-desktop: 1680px;
background-color: white; background-color: white;
margin: 0; margin: 0;
height: 250px; height: 250px;
width: 100vw; width: 100%;
padding: 25px 10px; padding: 25px 10px;
margin-bottom: 0;
}
@media screen and (min-width: $layout-breakpoint-desktop) { img {
.login { display: block;
margin-bottom: 100px; margin-left: auto;
margin-right: auto;
} }
} }
@media screen and (min-width: $layout-breakpoint-tablet) { @media (min-width: $layout-breakpoint-desktop) {
.login { .login {
box-shadow: 4px 5px 17px -11px rgba(0, 0, 0, 0.75); box-shadow: 4px 5px 17px -11px rgba(0, 0, 0, 0.75);
height: 370px; height: 320px;
width: 440px; width: 380px;
padding: 25px 30px; padding: 25px 30px;
margin-bottom: 100px;
} }
.wrapper { .wrapper {

View File

@ -1,17 +0,0 @@
import styles from './Login.module.scss';
import { Logo } from '@/elements';
import dynamic from 'next/dynamic';
const DynamicDefaultForm = dynamic(() => import('../Form').then((m) => m.DefaultForm));
const DynamicTelegramForm = dynamic(() => import('../Form').then((m) => m.TelegramForm));
export function Login({ tfa }) {
return (
<div className={styles.wrapper}>
<div className={styles.login}>
<Logo />
{tfa ? <DynamicTelegramForm /> : <DynamicDefaultForm />}
</div>
</div>
);
}

View File

@ -1,2 +0,0 @@
export * from './Form';
export * from './Login';

View File

@ -1,10 +1,9 @@
const { z } = require('zod'); import { z } from 'zod';
const envSchema = z.object({ const envSchema = z.object({
APP_BASE_PATH: z.string().optional().default(''),
APP_DESCRIPTION: z.string(), APP_DESCRIPTION: z.string(),
TELEGRAM_BOT_URL: z.string(), APP_TITLE: z.string(),
URL_API_CHECK_AUTH: z.string().default('http://auth_api:3001/check-auth'), APP_BASE_PATH: z.string().optional().default(''),
}); });
module.exports = envSchema; export default envSchema;

View File

@ -1,3 +0,0 @@
export const ERROR_INVALID_CREDENTIALS = 'Неверный логин или пароль';
export const ERROR_SERVER = 'Не удалось войти. Повторите попытку позже';
export const ERROR_TELEGRAM_SEND_MESSAGE = 'Не удалось отправить сообщение в Telegram';

View File

@ -1,78 +0,0 @@
/* eslint-disable sonarjs/no-small-switch */
import type { LdapUser } from '@/types/user';
import type { PropsWithChildren } from 'react';
import { createContext, useMemo, useReducer } from 'react';
type State = {
error: string | undefined;
step: 'login' | 'login-success' | 'telegram-notification' | 'refresh-token';
tfa: boolean;
user: LdapUser | undefined;
};
type Action = {
payload: Partial<State>;
type: 'set-step' | 'set-error' | 'reset-error';
};
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case 'set-step': {
if (action.payload.step)
return {
...state,
error: undefined,
step: action.payload.step,
user: action.payload.user || state.user,
};
return state;
}
case 'set-error': {
if (action.payload.error) {
return {
...state,
error: action.payload.error,
};
}
return state;
}
case 'reset-error': {
return {
...state,
error: undefined,
};
}
default:
return state;
}
};
type Context = {
dispatch: React.Dispatch<Action>;
state: State;
};
export const FormStateContext = createContext<Context>({} as Context);
type FormStateProviderProps = {
readonly tfa: boolean;
readonly user?: LdapUser;
} & PropsWithChildren;
export function FormStateProvider({ children, tfa, user = undefined }: FormStateProviderProps) {
const [state, dispatch] = useReducer(reducer, {
error: undefined,
step: user ? 'refresh-token' : 'login',
tfa,
user,
});
const value = useMemo(() => ({ dispatch, state }), [state]);
return <FormStateContext.Provider value={value}>{children}</FormStateContext.Provider>;
}

View File

@ -1,22 +1,16 @@
button { .btn {
border: 0;
background-color: var(--color-primary); background-color: var(--color-primary);
font-family: Montserrat;
border: 0;
color: #fff; color: #fff;
cursor: pointer; cursor: pointer;
font-family: Montserrat;
font-size: 14px; font-size: 14px;
font-weight: bold; font-weight: bold;
height: 40px; line-height: 2;
outline: 0; outline: 0;
outline: none;
padding: 0.55rem 0.75rem; padding: 0.55rem 0.75rem;
text-align: center; text-align: center;
text-transform: none; text-transform: uppercase;
vertical-align: middle; vertical-align: middle;
width: 100%; width: 100%;
} }
button:disabled {
opacity: 0.8;
cursor: not-allowed;
}

View File

@ -0,0 +1,12 @@
/* eslint-disable react/button-has-type */
import styles from './Button.module.css';
type ButtonProps = JSX.IntrinsicElements['button'];
export default function Button({ children, ...props }: ButtonProps) {
return (
<button className={styles.btn} {...props}>
{children}
</button>
);
}

View File

@ -0,0 +1,5 @@
import styles from './Error.module.css';
export default function Error({ children }) {
return <span className={styles.error}>{children}</span>;
}

View File

@ -4,7 +4,4 @@
font-weight: bold; font-weight: bold;
text-transform: uppercase; text-transform: uppercase;
color: red; color: red;
overflow: hidden;
/* white-space: nowrap; */
text-overflow: ellipsis;
} }

5
apps/web/elements/H.jsx Normal file
View File

@ -0,0 +1,5 @@
import styles from './H.module.css';
export function H3({ children }) {
return <h3 className={styles.h3}>{children}</h3>;
}

View File

@ -1,4 +1,4 @@
h3 { .h3 {
color: var(--color-primary); color: var(--color-primary);
font-family: Montserrat; font-family: Montserrat;
font-weight: 700; font-weight: 700;

View File

@ -1,6 +1,6 @@
input { .input {
font-family: Montserrat; font-family: Montserrat;
border: 1px solid rgba(0, 16, 61, 0.12); border: 1px solid rgba(0,16,61,.12);
box-sizing: border-box; box-sizing: border-box;
height: 40px; height: 40px;
background: #fff; background: #fff;
@ -10,13 +10,8 @@ input {
/* font-size: 15px; */ /* font-size: 15px; */
} }
input::placeholder { .input::placeholder {
color: var(--color-primary); color: var(--color-primary);
filter: brightness(0.25); filter: brightness(0.25);
opacity: 0.9; opacity: 0.9;
} }
input:disabled {
opacity: 0.8;
cursor: not-allowed;
}

View File

@ -0,0 +1,7 @@
import styles from './Input.module.css';
type InputProps = JSX.IntrinsicElements['input'];
export default function Input(props: InputProps) {
return <input className={styles.input} {...props} />;
}

View File

@ -1,6 +1,6 @@
import Image from 'next/image'; import Image from 'next/image';
import logo from 'public/assets/images/logo-primary.svg?url'; import logo from 'public/assets/images/logo-primary.svg';
export function Logo() { export default function Logo() {
return <Image className="logo" src={logo} alt="logo" width={154} />; return <Image src={logo} alt="logo" width={154} />;
} }

View File

@ -1 +0,0 @@
export * from './Logo';

View File

@ -1,45 +0,0 @@
const envSchema = require('./config/schema/env.js');
const { join } = require('path');
const runtimeConfig = envSchema.parse(process.env);
/** @type {import('next').NextConfig} */
module.exports = {
basePath: process.env.APP_BASE_PATH,
eslint: {
ignoreDuringBuilds: true,
},
experimental: {
outputFileTracingRoot: join(__dirname, '../../'),
},
output: 'standalone',
publicRuntimeConfig: runtimeConfig,
reactStrictMode: true,
serverRuntimeConfig: runtimeConfig,
swcMinify: true,
webpack(config) {
// Grab the existing rule that handles SVG imports
const fileLoaderRule = config.module.rules.find((rule) => rule.test?.test?.('.svg'));
config.module.rules.push(
// Reapply the existing rule, but only for svg imports ending in ?url
{
...fileLoaderRule,
test: /\.svg$/i,
resourceQuery: /url/, // *.svg?url
},
// Convert all other *.svg imports to React components
{
test: /\.svg$/i,
issuer: fileLoaderRule.issuer,
resourceQuery: { not: [...fileLoaderRule.resourceQuery.not, /url/] }, // exclude if *.svg?url
use: ['@svgr/webpack'],
}
);
// Modify the file loader rule to ignore *.svg, since we have it handled now.
fileLoaderRule.exclude = /\.svg$/i;
return config;
},
};

26
apps/web/next.config.mjs Normal file
View File

@ -0,0 +1,26 @@
import envSchema from './config/schema/env.js';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const runtimeConfig = envSchema.parse(process.env);
/** @type {import('next').NextConfig} */
const nextConfig = {
basePath: process.env.APP_BASE_PATH,
eslint: {
ignoreDuringBuilds: true,
},
experimental: {
outputFileTracingRoot: join(__dirname, '../../'),
},
output: 'standalone',
publicRuntimeConfig: runtimeConfig,
reactStrictMode: true,
serverRuntimeConfig: runtimeConfig,
swcMinify: true,
};
export default nextConfig;

View File

@ -2,6 +2,7 @@
"name": "web", "name": "web",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"type": "module",
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
@ -11,24 +12,20 @@
}, },
"dependencies": { "dependencies": {
"@fontsource/montserrat": "^5.0.13", "@fontsource/montserrat": "^5.0.13",
"@svgr/webpack": "^8.1.0", "@types/node": "^20",
"@types/node": "^20.10.0", "@types/react": "^18",
"@types/react": "^18.2.39", "@types/react-dom": "^18",
"@types/react-dom": "^18.2.17",
"axios": "^1.5.1", "axios": "^1.5.1",
"modern-normalize": "^2.0.0", "next": "^13.5.4",
"next": "^14.2.3", "normalize.css": "^8.0.1",
"radash": "^11.0.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-hook-form": "^7.51.3",
"sass": "^1.69.3", "sass": "^1.69.3",
"socket.io-client": "^4.7.5", "typescript": "4.9.5",
"typescript": "5.3.2",
"zod": "^3.22.4" "zod": "^3.22.4"
}, },
"devDependencies": { "devDependencies": {
"@vchikalkin/eslint-config-awesome": "^1.1.6", "@vchikalkin/eslint-config-awesome": "^1.1.2",
"eslint": "^8.51.0" "eslint": "^8.51.0"
} }
} }

View File

@ -1,5 +1,5 @@
/* eslint-disable react/no-unknown-property */ /* eslint-disable react/no-unknown-property */
import '../styles/globals.css'; import 'normalize.css';
import '@fontsource/montserrat/400.css'; import '@fontsource/montserrat/400.css';
import '@fontsource/montserrat/600.css'; import '@fontsource/montserrat/600.css';
import '@fontsource/montserrat/700.css'; import '@fontsource/montserrat/700.css';

View File

@ -2,7 +2,7 @@
import { serverRuntimeConfig } from '@/config/runtime'; import { serverRuntimeConfig } from '@/config/runtime';
import Document, { Head, Html, Main, NextScript } from 'next/document'; import Document, { Head, Html, Main, NextScript } from 'next/document';
const { APP_BASE_PATH } = serverRuntimeConfig; const { APP_BASE_PATH, APP_DESCRIPTION } = serverRuntimeConfig;
export default class MyDocument extends Document { export default class MyDocument extends Document {
render() { render() {
@ -10,6 +10,7 @@ export default class MyDocument extends Document {
<Html lang="ru" translate="no"> <Html lang="ru" translate="no">
<Head> <Head>
<meta charSet="utf-8" /> <meta charSet="utf-8" />
<meta name="description" content={APP_DESCRIPTION} />
<link <link
rel="apple-touch-icon" rel="apple-touch-icon"
sizes="120x120" sizes="120x120"

View File

@ -1 +0,0 @@
export { default, getServerSideProps } from './ldap';

22
apps/web/pages/index.jsx Normal file
View File

@ -0,0 +1,22 @@
import Login from '@/components/Login';
import { publicRuntimeConfig } from '@/config/runtime';
import Head from 'next/head';
const { APP_DESCRIPTION } = publicRuntimeConfig;
function PageHead() {
return (
<Head>
<title>{`Вход - ${APP_DESCRIPTION}`}</title>
</Head>
);
}
export default function Home() {
return (
<>
<PageHead />
<Login />
</>
);
}

View File

@ -1 +0,0 @@
export { default, getServerSideProps } from './ldap';

Some files were not shown because too many files have changed in this diff Show More