Compare commits

..

34 Commits

Author SHA1 Message Date
vchikalkin
5cde4b0385 span.error: fix overflow text 2024-07-18 21:15:27 +03:00
vchikalkin
1d8e40535e Form: fix telegram-bot link 2024-07-18 21:11:06 +03:00
vchikalkin
e0e84a7638 button: disable uppercase 2024-07-18 21:09:03 +03:00
vchikalkin
658b678d80 ws: send auth-deny and reload page 2024-07-18 20:57:59 +03:00
vchikalkin
67019e3aba apps/web: Form: show telegram link on step login-success 2024-07-18 20:32:09 +03:00
vchikalkin
40d5771845 context/form-state: add step refresh-token 2024-07-18 20:27:52 +03:00
vchikalkin
fd43833aca context/form-state: rename steps 2024-07-18 20:22:44 +03:00
vchikalkin
e41d6e3c46 show default telegram error | remove sending error from api 2024-07-18 20:18:51 +03:00
vchikalkin
cc8b59011c apps/web: pass children to buttons 2024-07-18 19:45:38 +03:00
vchikalkin
3bdfbbbfb1 apps/web: add margin-bottom for logo 2024-07-18 19:04:20 +03:00
vchikalkin
4eaf62da0b apps/web: always show telegram bot link for ldap-tfa 2024-07-18 19:02:52 +03:00
vchikalkin
2d41e403ce apps/web: fix reset error on next step 2024-07-18 18:44:09 +03:00
vchikalkin
06ced758d1 apps/web: enable wrap for error string 2024-07-18 18:07:56 +03:00
vchikalkin
5d1dba3a2f apps/web: fix login form width > vw 2024-07-18 18:00:03 +03:00
vchikalkin
712142a474 merge branch release/dyn-4251_2fa-telegram-auth 2024-07-14 17:15:29 +03:00
vchikalkin
26a7092d74 packages: upgrade @vchikalkin/eslint-config-awesome 2024-04-25 12:17:04 +03:00
vchikalkin
e8824d6b8c apps/web: replace normalize.css -> modern-normalize
upgrade next
2024-04-25 12:14:51 +03:00
vchikalkin
8dbdbd8053 docker: fix build
redis: add restart option
2024-02-17 21:37:07 +03:00
vchikalkin
ab4612ff12 apps/api: fix /reset-password 2024-01-17 17:54:25 +03:00
vchikalkin
f8c78bfa40 apps/api:add UpdateAccountDto 2024-01-17 17:45:57 +03:00
vchikalkin
01f4378e11 apps/api: add /reset-password method 2024-01-17 17:40:30 +03:00
vchikalkin
76c1e0f8d1 apps/api: refresh token (ldap mode) 2024-01-16 14:19:32 +03:00
vchikalkin
fd8837c835 apps/api: refresh account mode token 2024-01-16 14:07:51 +03:00
vchikalkin
85f1976386 docker-compose.yml: add COOKIE_TOKEN_NAME & COOKIE_TOKEN_MAX_AGE envvariables 2024-01-16 12:45:45 +03:00
vchikalkin
69ff7a8ff7 merge fix/refresh-token 2024-01-16 12:32:42 +03:00
vchikalkin
946d977db8 apps/api: check if account exists before create 2024-01-12 16:08:24 +03:00
vchikalkin
7ac3f0cc6a apps/api: update: return updated account 2024-01-12 13:54:10 +03:00
vchikalkin
0643080e68 apps/api: get-user: return data from db 2024-01-12 13:51:31 +03:00
vchikalkin
2f3f0183e5 apps/api: add /update method 2024-01-11 13:39:57 +03:00
vchikalkin
b28c5a4f3f merge experimental/migrate-to-pnpm 2023-11-28 23:47:19 +03:00
vchikalkin
1a7cf3f3c5 apps/api: read token from headers 2023-11-17 12:29:02 +03:00
vchikalkin
6e323803bd apps/api: send token after login 2023-11-17 12:21:59 +03:00
vchikalkin
741a1d69ee apps/api: pass token to Authorization header 2023-11-17 11:36:29 +03:00
vchikalkin
bca8a64efd apps/api: change route */signin -> */login 2023-11-02 12:46:22 +03:00
95 changed files with 12534 additions and 14825 deletions

23
.env
View File

@ -1,23 +0,0 @@
COMPOSE_PROJECT_NAME=
TRAEFIK_APP_NAME=
TRAEFIK_ENTRYPOINTS=web-secure
# TRAEFIK_ENTRYPOINTS=web-secure-ext
WEB_HOST=
# 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

6
.eslintignore Normal file
View File

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

1
.npmrc Normal file
View File

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

View File

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

View File

@ -1,24 +1,32 @@
# Turborepo starter # Turborepo starter
This is an official Yarn v1 starter turborepo. This is an official starter Turborepo.
## Using this example
Run the following command:
```sh
npx create-turbo@latest
```
## What's inside? ## What's inside?
This turborepo uses [Yarn](https://classic.yarnpkg.com/) as a package manager. It includes the following packages/apps: This Turborepo 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
- `ui`: a stub React component library shared by both `web` and `docs` applications - `@repo/ui`: a stub React component library shared by both `web` and `docs` applications
- `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`) - `@repo/eslint-config`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
- `tsconfig`: `tsconfig.json`s used throughout the monorepo - `@repo/typescript-config`: `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
@ -30,7 +38,7 @@ To build all apps and packages, run the following command:
``` ```
cd my-turborepo cd my-turborepo
yarn run build pnpm build
``` ```
### Develop ### Develop
@ -39,7 +47,7 @@ To develop all apps and packages, run the following command:
``` ```
cd my-turborepo cd my-turborepo
yarn run dev pnpm dev
``` ```
### Remote Caching ### Remote Caching
@ -55,7 +63,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
@ -65,7 +73,7 @@ npx turbo link
Learn more about the power of Turborepo: Learn more about the power of Turborepo:
- [Pipelines](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks) - [Tasks](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)

View File

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

View File

@ -1,12 +1,13 @@
module.exports = { const { createConfig } = require('@vchikalkin/eslint-config-awesome');
root: true,
extends: [ module.exports = createConfig('typescript', {
'@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,19 +1,22 @@
# The web Dockerfile is copy-pasted into our main docs at /docs/handbook/deploying-with-docker. # This Dockerfile is copy-pasted into our main docs at /docs/handbook/deploying-with-docker.
# Make sure you update this Dockerfile, the Dockerfile in the web workspace and copy that over to Dockerfile in the docs. # 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 yarn global add turbo RUN pnpm add -g turbo@1.12.4 dotenv-cli
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
@ -21,13 +24,14 @@ 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/yarn.lock ./yarn.lock COPY --from=builder /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN yarn install COPY --from=builder /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml
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 yarn dotenv -e .env turbo run build --filter=api... RUN pnpm dotenv -e .env turbo run build --filter=api...
FROM node:alpine AS runner FROM node:alpine AS runner
WORKDIR /app WORKDIR /app

View File

@ -23,7 +23,6 @@
}, },
"dependencies": { "dependencies": {
"@fastify/cookie": "^9.1.0", "@fastify/cookie": "^9.1.0",
"@fastify/http-proxy": "^9.3.0",
"@fastify/static": "^6.12.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",
@ -33,9 +32,11 @@
"@nestjs/jwt": "^10.1.1", "@nestjs/jwt": "^10.1.1",
"@nestjs/mapped-types": "*", "@nestjs/mapped-types": "*",
"@nestjs/mongoose": "^10.0.1", "@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/swagger": "^7.1.14",
"@nestjs/websockets": "^10.3.8",
"axios": "^1.5.1",
"bcrypt": "^5.1.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",
@ -47,6 +48,7 @@
"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": {
@ -59,8 +61,9 @@
"@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.2", "@vchikalkin/eslint-config-awesome": "^1.1.6",
"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",
@ -69,7 +72,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": "4.9.5" "typescript": "5.3.2"
}, },
"jest": { "jest": {
"moduleFileExtensions": [ "moduleFileExtensions": [

View File

@ -3,6 +3,8 @@
/* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable import/no-extraneous-dependencies */
import { AccountService } from './account.service'; import { AccountService } from './account.service';
import { CreateAccountDto } from './dto/create-account.dto'; import { CreateAccountDto } from './dto/create-account.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { UpdateAccountDto } from './dto/update-account.dto';
import { import {
Body, Body,
Controller, Controller,
@ -10,6 +12,7 @@ import {
Get, Get,
HttpException, HttpException,
HttpStatus, HttpStatus,
Patch,
Post, Post,
Query, Query,
Req, Req,
@ -20,12 +23,15 @@ import { ApiResponse, ApiTags } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify'; import { FastifyReply, FastifyRequest } from 'fastify';
import { cookieOptions } from 'src/config/cookie'; import { cookieOptions } from 'src/config/cookie';
import { env } from 'src/config/env'; 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 { Credentials } from 'src/dto/credentials';
import { Account } from 'src/schemas/account.schema'; import { Account } from 'src/schemas/account.schema';
import type { BaseAuthController } from 'src/types/auth-controller';
@Controller('account') @Controller('account')
@ApiTags('account') @ApiTags('account')
export class AccountController { export class AccountController implements BaseAuthController {
constructor(private readonly accountService: AccountService) {} constructor(private readonly accountService: AccountService) {}
private clearCookies(req, reply) { private clearCookies(req, reply) {
@ -68,12 +74,49 @@ export class AccountController {
return this.accountService.delete(username); 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') @Post('/login')
async login(@Body() credentials: Credentials, @Res() reply: FastifyReply) { async login(
@Body() credentials: Credentials,
@Req() _req: FastifyRequest,
@Res() reply: FastifyReply
) {
try { try {
const token = await this.accountService.login(credentials); const token = await this.accountService.login(credentials);
return reply.setCookie(env.COOKIE_TOKEN_NAME, token, cookieOptions).status(200).send(); return reply
.setCookie(env.COOKIE_TOKEN_NAME, token, cookieOptions)
.status(200)
.send({ token });
} catch { } catch {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
} }
@ -83,17 +126,50 @@ export class AccountController {
async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply) { async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply) {
this.clearCookies(req, reply); this.clearCookies(req, reply);
return reply.status(302).redirect('/login'); 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') @Get('/get-user')
async getUser(@Req() req: FastifyRequest, @Res() reply: FastifyReply) { async getUser(
const token = req.cookies[env.COOKIE_TOKEN_NAME]; @Req() req: FastifyRequest,
if (!token) throw new UnauthorizedException(); @Res() reply: FastifyReply,
@AuthToken() token: string
) {
const account = await this.accountService.getUser(token); const account = await this.accountService.getUser(token);
if (!account) throw new UnauthorizedException('Account not found'); if (!account) throw new UnauthorizedException('Account not found');
return reply.send(account); 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

@ -6,7 +6,7 @@ import { Account, AccountSchema } from 'src/schemas/account.schema';
@Module({ @Module({
controllers: [AccountController], controllers: [AccountController],
exports: [], exports: [AccountService],
imports: [MongooseModule.forFeature([{ name: Account.name, schema: AccountSchema }])], imports: [MongooseModule.forFeature([{ name: Account.name, schema: AccountSchema }])],
providers: [AccountService], providers: [AccountService],
}) })

View File

@ -1,13 +1,16 @@
import type { CreateAccountDto } from './dto/create-account.dto'; import type { CreateAccountDto } from './dto/create-account.dto';
import { Injectable, UnauthorizedException } from '@nestjs/common'; 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 { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
import { Model } from 'mongoose'; import { Model } from 'mongoose';
import { omit } from 'radash'; import { omit } from 'radash';
import type { Credentials } from 'src/dto/credentials'; import type { Credentials } from 'src/dto/credentials';
import type { TokenPayload } from 'src/ldap/types/jwt';
import { Account } from 'src/schemas/account.schema'; import { Account } from 'src/schemas/account.schema';
import type { DecodedToken, TokenPayload } from 'src/types/jwt';
import { generatePassword } from 'src/utils/password'; import { generatePassword } from 'src/utils/password';
@Injectable() @Injectable()
@ -18,6 +21,18 @@ export class AccountService {
) {} ) {}
public async create(createAccountDto: CreateAccountDto): Promise<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 password = createAccountDto.password || generatePassword();
const createdAccount = new this.accountModel({ ...createAccountDto, password }); const createdAccount = new this.accountModel({ ...createAccountDto, password });
@ -35,6 +50,27 @@ export class AccountService {
return this.accountModel.findOneAndDelete({ username }).exec(); 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) { public async login({ login, password }: Credentials) {
try { try {
const account = await this.accountModel.findOne({ username: login }); const account = await this.accountModel.findOne({ username: login });
@ -48,7 +84,7 @@ export class AccountService {
const payload: TokenPayload = { const payload: TokenPayload = {
username: login, username: login,
...omit(account.toJSON(), ['password']), ...omit(account.toJSON(), ['password', '_id', '__v']),
}; };
return this.jwtService.sign(payload); return this.jwtService.sign(payload);
@ -57,11 +93,43 @@ export class AccountService {
} }
} }
public async getUser(token: string) { public async refreshToken(token: string) {
try { try {
return this.jwtService.verify(token); 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 { } catch {
throw new UnauthorizedException('Invalid token'); 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

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

View File

@ -0,0 +1,11 @@
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

@ -1,29 +1,51 @@
import { AppService } from './app.service'; import { AppService } from './app.service';
import { env } from './config/env'; import { AuthParams, Params } from './decorators/auth-mode.decorator';
import { AuthToken } from './decorators/token.decorator';
import { Controller, Get, HttpStatus, Req, Res } from '@nestjs/common'; import { Controller, Get, HttpStatus, Req, Res } from '@nestjs/common';
import { ApiExcludeController } from '@nestjs/swagger'; import { ApiExcludeController, ApiResponse } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify'; import { FastifyReply, FastifyRequest } from 'fastify';
@Controller() @Controller()
@ApiExcludeController() @ApiExcludeController()
export class AppController { export class AppController {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@Get('auth') @Get('auth')
public async auth(@Req() req: FastifyRequest, @Res() reply: FastifyReply) { public async auth(
const token = req.cookies[env.COOKIE_TOKEN_NAME]; @Req() req: FastifyRequest,
@Res() reply: FastifyReply,
@AuthToken() token: string,
@AuthParams() { authMode }: Params
) {
try { try {
this.appService.checkToken(token); const { aud } = this.appService.checkToken(token);
const originalUri = req.headers['x-original-uri'];
return reply.send();
} catch {
// if (error.name === 'TokenExpiredError') {
// const newToken = this.appService.refreshToken(token);
// return reply.setCookie(env.COOKIE_TOKEN_NAME, newToken, cookieOptions).send();
// }
if (
authMode === 'ldap-tfa' &&
aud === 'auth' &&
!['/auth', '/login', '/socket.io'].some((x) => originalUri.includes(x))
) {
return reply.status(HttpStatus.UNAUTHORIZED).send(); 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

@ -3,10 +3,14 @@ import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
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 { 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 { MongooseModule } from '@nestjs/mongoose';
import * as redisStore from 'cache-manager-ioredis';
import type { RedisOptions } from 'ioredis';
@Global() @Global()
@Module({ @Module({
@ -24,7 +28,15 @@ import { MongooseModule } from '@nestjs/mongoose';
}), }),
LdapModule, LdapModule,
AccountModule, AccountModule,
LdapTfaModule,
MongooseModule.forRoot(`mongodb://${env.MONGO_HOST}`), 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,4 +1,4 @@
import type { DecodedToken } from './ldap/types/jwt'; import type { DecodedToken } from './types/jwt';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { omit } from 'radash'; import { omit } from 'radash';
@ -8,11 +8,11 @@ export class AppService {
constructor(private readonly jwtService: JwtService) {} constructor(private readonly jwtService: JwtService) {}
public checkToken(token: string) { public checkToken(token: string) {
this.jwtService.verify(token); return this.jwtService.verify<DecodedToken>(token);
} }
public refreshToken(token: string) { public refreshToken(token: string) {
const payload = this.jwtService.decode(token) as DecodedToken; const payload = this.jwtService.decode<DecodedToken>(token);
return this.jwtService.sign(omit(payload, ['iat', 'exp'])); return this.jwtService.sign(omit(payload, ['iat', 'exp']));
} }

View File

@ -3,7 +3,7 @@ import { env } from 'src/config/env';
export const cookieOptions: CookieSerializeOptions = { export const cookieOptions: CookieSerializeOptions = {
httpOnly: true, httpOnly: true,
maxAge: env.API_TOKEN_TTL, maxAge: env.COOKIE_TOKEN_MAX_AGE,
path: '/', path: '/',
secure: true, secure: true,
}; };

View File

@ -4,7 +4,12 @@ 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(),
@ -22,7 +27,9 @@ const envSchema = z.object({
.string() .string()
.transform((val) => Number.parseInt(val, 10)) .transform((val) => Number.parseInt(val, 10))
.default('6379'), .default('6379'),
WEB_SERVER: z.string(), 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

@ -0,0 +1,23 @@
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

@ -0,0 +1,14 @@
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;
});

14
apps/api/src/dto/tfa.ts Normal file
View File

@ -0,0 +1,14 @@
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

@ -0,0 +1,116 @@
/* 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

@ -0,0 +1,49 @@
/* 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

@ -0,0 +1,14 @@
/* 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

@ -0,0 +1,57 @@
/* 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

@ -19,13 +19,16 @@ import { ApiResponse, ApiTags } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify'; import { FastifyReply, FastifyRequest } from 'fastify';
import { cookieOptions } from 'src/config/cookie'; import { cookieOptions } from 'src/config/cookie';
import { env } from 'src/config/env'; 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'; import { User } from 'src/utils/ldap';
@Controller('ldap') @Controller('ldap')
@ApiTags('ldap') @ApiTags('ldap')
export class LdapController { export class LdapController implements BaseAuthController {
cookieOptions: CookieSerializeOptions; cookieOptions: CookieSerializeOptions;
constructor(private readonly ldapService: LdapService) {} constructor(protected readonly ldapService: LdapService) {}
private clearCookies(req, reply) { private clearCookies(req, reply) {
if (req.cookies) { if (req.cookies) {
@ -41,7 +44,11 @@ export class LdapController {
@ApiResponse({ @ApiResponse({
status: HttpStatus.OK, status: HttpStatus.OK,
}) })
async login(@Body() credentials: Credentials, @Res() reply: FastifyReply) { async login(
@Body() credentials: Credentials,
@Req() _req: FastifyRequest,
@Res() reply: FastifyReply
) {
try { try {
const token = await this.ldapService.login(credentials); const token = await this.ldapService.login(credentials);
@ -52,13 +59,30 @@ export class LdapController {
} }
@Get('/logout') @Get('/logout')
async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply) { async logout(@Req() req: FastifyRequest, @Res() reply: FastifyReply, @AuthToken() token: string) {
const token = req.cookies[env.COOKIE_TOKEN_NAME];
if (token) await this.ldapService.logout(token); if (token) await this.ldapService.logout(token);
this.clearCookies(req, reply); this.clearCookies(req, reply);
return reply.status(302).redirect('/login'); 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') @Get('/get-user')
@ -66,15 +90,29 @@ export class LdapController {
status: HttpStatus.OK, status: HttpStatus.OK,
type: User, type: User,
}) })
async getUser(@Req() req: FastifyRequest, @Res() reply: FastifyReply) { async getUser(
const token = req.cookies[env.COOKIE_TOKEN_NAME]; @Req() _req: FastifyRequest,
@Res() reply: FastifyReply,
if (!token) throw new UnauthorizedException(); @AuthToken() token: string
) {
const user = await this.ldapService.getUser(token); const user = await this.ldapService.getUser(token);
if (!user) throw new UnauthorizedException('User not found'); if (!user) throw new UnauthorizedException('User not found');
return reply.send(user); 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,21 +1,11 @@
import { LdapController } from './ldap.controller'; import { LdapController } from './ldap.controller';
import { LdapService } from './ldap.service'; import { LdapService } from './ldap.service';
import { CacheModule } from '@nestjs/cache-manager';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import * as redisStore from 'cache-manager-ioredis';
import type { RedisOptions } from 'ioredis';
import { env } from 'src/config/env';
@Module({ @Module({
controllers: [LdapController], controllers: [LdapController],
imports: [ exports: [LdapService],
CacheModule.register<RedisOptions>({ imports: [],
host: env.REDIS_HOST,
port: env.REDIS_PORT,
store: redisStore,
ttl: env.API_CACHE_TTL,
}),
],
providers: [LdapService], providers: [LdapService],
}) })
// eslint-disable-next-line @typescript-eslint/no-extraneous-class // eslint-disable-next-line @typescript-eslint/no-extraneous-class

View File

@ -1,6 +1,7 @@
import type { DecodedToken, TokenPayload } from './types/jwt'; import type { DecodedToken, TokenPayload } from '../types/jwt';
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'; import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import type { JwtSignOptions, JwtVerifyOptions } from '@nestjs/jwt';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { Cache } from 'cache-manager'; import { Cache } from 'cache-manager';
import { env } from 'src/config/env'; import { env } from 'src/config/env';
@ -10,12 +11,13 @@ import * as ldap from 'src/utils/ldap';
@Injectable() @Injectable()
export class LdapService { export class LdapService {
constructor( constructor(
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache, @Inject(CACHE_MANAGER) protected readonly cacheManager: Cache,
private readonly jwtService: JwtService protected readonly jwtService: JwtService
) {} ) {}
public async login({ login, password }: Credentials) { public async login(credentials: Credentials, options?: JwtSignOptions) {
const user = await ldap.authenticate(login, password); try {
const user = await ldap.authenticate(credentials.login, credentials.password);
const { username } = user; const { username } = user;
await this.cacheManager.set(username, user); await this.cacheManager.set(username, user);
@ -25,7 +27,10 @@ export class LdapService {
username, username,
}; };
return this.jwtService.sign(payload); return this.jwtService.sign(payload, options);
} catch (error) {
throw new UnauthorizedException(error);
}
} }
public async logout(token: string) { public async logout(token: string) {
@ -36,11 +41,34 @@ export class LdapService {
} }
} }
public async getUser(token: string) { public async refreshToken(token: string) {
try { try {
const { username } = this.jwtService.verify(token) as DecodedToken; const { username, aud = '' } = this.jwtService.verify<DecodedToken>(token, {
ignoreExpiration: true,
});
const cachedUser = (await this.cacheManager.get(username)) as ldap.User; 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,
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) { if (!cachedUser) {
const user = await ldap.authenticate(username); const user = await ldap.authenticate(username);
@ -55,4 +83,12 @@ export class LdapService {
throw new UnauthorizedException('Invalid token'); 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

@ -3,7 +3,6 @@
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 proxy from '@fastify/http-proxy';
import type { INestApplication } from '@nestjs/common'; import type { INestApplication } from '@nestjs/common';
import { ValidationPipe } from '@nestjs/common'; import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
@ -33,12 +32,6 @@ async function bootstrap() {
secret: env.API_SECRET, secret: env.API_SECRET,
}); });
await app.register(proxy, {
http2: false,
httpMethods: ['GET'],
upstream: `http://${env.WEB_SERVER}`,
});
app.useGlobalPipes(new ValidationPipe({ stopAtFirstError: true })); app.useGlobalPipes(new ValidationPipe({ stopAtFirstError: true }));
setupOpenApi(app); setupOpenApi(app);

View File

@ -11,12 +11,14 @@ export class Account {
@ApiResponseProperty() @ApiResponseProperty()
@ApiProperty() @ApiProperty()
@Prop({ index: { unique: true }, required: true }) @Prop({ index: { unique: true }, required: true })
username: string; public username: string;
@ApiResponseProperty() @ApiResponseProperty()
@ApiProperty() @ApiProperty()
@Prop({ required: true }) @Prop({ required: true })
password: string; public password: string;
readonly [key: string]: unknown;
} }
export const AccountSchema = SchemaFactory.createForClass(Account); export const AccountSchema = SchemaFactory.createForClass(Account);
@ -33,3 +35,17 @@ AccountSchema.pre('save', async function (next) {
return next(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

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

View File

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

View File

@ -18,6 +18,8 @@ export class User {
public position: string; public position: string;
@ApiResponseProperty() @ApiResponseProperty()
public username: string; public username: string;
@ApiResponseProperty()
public employeeID: string;
} }
export type LdapUser = { export type LdapUser = {
@ -108,6 +110,7 @@ export async function authenticate(login: string, password?: string) {
title, title,
mail, mail,
sAMAccountName: username, sAMAccountName: username,
employeeID,
}: LdapUser = await ldap.authenticate(options); }: LdapUser = await ldap.authenticate(options);
const user: User = { const user: User = {
@ -115,6 +118,7 @@ export async function authenticate(login: string, password?: string) {
displayName, displayName,
domain: env.LDAP_DOMAIN, domain: env.LDAP_DOMAIN,
domainName: `${env.LDAP_DOMAIN}\\${username}`, domainName: `${env.LDAP_DOMAIN}\\${username}`,
employeeID,
mail, mail,
position: title, position: title,
username, username,

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -2,47 +2,49 @@
# 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 yarn global add turbo RUN pnpm add -g turbo@1.12.4 dotenv-cli
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/yarn.lock ./yarn.lock COPY --from=builder /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN yarn install COPY --from=builder /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml
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
COPY .env .env ARG APP_BASE_PATH
RUN yarn dotenv -e .env turbo run build --filter=web... ARG APP_DESCRIPTION
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.mjs . COPY --from=installer /app/apps/web/next.config.js .
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

@ -1,45 +0,0 @@
import styles from './Form.module.scss';
import { publicRuntimeConfig } from '@/config/runtime';
import Button from '@/elements/Button';
import Error from '@/elements/Error';
import Input from '@/elements/Input';
import axios from 'axios';
import { useState } from 'react';
const { APP_BASE_PATH } = 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('/login', data)
.then(() => {
const url =
(window.location.pathname.replace(APP_BASE_PATH, '') || '/') +
(window.location.search || '');
window.location.replace(url);
})
.catch(() => {
setHasError(true);
});
}}
>
<Input name="login" type="text" placeholder="Логин" required autoComplete="on" />
<Input name="password" type="password" placeholder="Пароль" required autoComplete="on" />
{error}
<Button>Войти</Button>
</form>
);
}

View File

@ -0,0 +1,44 @@
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

@ -0,0 +1,25 @@
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

@ -0,0 +1,24 @@
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

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

View File

@ -0,0 +1,11 @@
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

@ -0,0 +1,101 @@
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

@ -0,0 +1,28 @@
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

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

View File

@ -0,0 +1,55 @@
.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

@ -0,0 +1,56 @@
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

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

View File

@ -0,0 +1,10 @@
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

@ -0,0 +1,43 @@
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

@ -1,14 +0,0 @@
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-desktop: 768px; $layout-breakpoint-tablet: 768px;
$layout-breakpoint-desktop: 1680px;
@mixin center-elements { @mixin center-elements {
display: flex; display: grid;
justify-content: center; place-items: center;
align-items: center;
} }
.wrapper { .wrapper {
@ -19,23 +19,23 @@ $layout-breakpoint-desktop: 768px;
background-color: white; background-color: white;
margin: 0; margin: 0;
height: 250px; height: 250px;
width: 100%; width: 100vw;
padding: 25px 10px; padding: 25px 10px;
margin-bottom: 0;
}
img { @media screen and (min-width: $layout-breakpoint-desktop) {
display: block; .login {
margin-left: auto; margin-bottom: 100px;
margin-right: auto;
} }
} }
@media (min-width: $layout-breakpoint-desktop) { @media screen and (min-width: $layout-breakpoint-tablet) {
.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: 320px; height: 370px;
width: 380px; width: 440px;
padding: 25px 30px; padding: 25px 30px;
margin-bottom: 100px;
} }
.wrapper { .wrapper {

View File

@ -0,0 +1,17 @@
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

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

View File

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

View File

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

View File

@ -0,0 +1,78 @@
/* 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,12 +0,0 @@
/* 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

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

View File

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

View File

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

View File

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

45
apps/web/next.config.js Normal file
View File

@ -0,0 +1,45 @@
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;
},
};

View File

@ -1,26 +0,0 @@
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,7 +2,6 @@
"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",
@ -12,20 +11,24 @@
}, },
"dependencies": { "dependencies": {
"@fontsource/montserrat": "^5.0.13", "@fontsource/montserrat": "^5.0.13",
"@types/node": "^20", "@svgr/webpack": "^8.1.0",
"@types/react": "^18", "@types/node": "^20.10.0",
"@types/react-dom": "^18", "@types/react": "^18.2.39",
"@types/react-dom": "^18.2.17",
"axios": "^1.5.1", "axios": "^1.5.1",
"next": "^14.0.0", "modern-normalize": "^2.0.0",
"normalize.css": "^8.0.1", "next": "^14.2.3",
"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",
"typescript": "4.9.5", "socket.io-client": "^4.7.5",
"typescript": "5.3.2",
"zod": "^3.22.4" "zod": "^3.22.4"
}, },
"devDependencies": { "devDependencies": {
"@vchikalkin/eslint-config-awesome": "^1.1.2", "@vchikalkin/eslint-config-awesome": "^1.1.6",
"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 'normalize.css'; import '../styles/globals.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

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

View File

@ -1,23 +0,0 @@
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>
<meta name="description" content={APP_DESCRIPTION} />
</Head>
);
}
export default function Home() {
return (
<>
<PageHead />
<Login />
</>
);
}

View File

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

52
apps/web/pages/ldap.jsx Normal file
View File

@ -0,0 +1,52 @@
import { Login } from '@/components';
import { publicRuntimeConfig, serverRuntimeConfig } from '@/config/runtime';
import { FormStateProvider } from '@/context/form-state';
import axios from 'axios';
import Head from 'next/head';
import { pick } from 'radash';
const { URL_API_CHECK_AUTH } = serverRuntimeConfig;
const { APP_DESCRIPTION } = publicRuntimeConfig;
export function PageHead() {
return (
<Head>
<title>{`Вход - ${APP_DESCRIPTION}`}</title>
<meta name="description" content={APP_DESCRIPTION} />
</Head>
);
}
export default function Page(props) {
return (
<FormStateProvider {...props}>
<PageHead />
<Login tfa={props.tfa} />
</FormStateProvider>
);
}
/** @type {import('next').GetServerSideProps} */
export async function getServerSideProps({ req }) {
const headers = pick(req.headers, ['auth-mode', 'cookie', 'refresh-token']);
const tfa = headers['auth-mode'] === 'ldap-tfa';
try {
const { data: user } = await axios.get(URL_API_CHECK_AUTH, {
headers,
});
return {
props: {
tfa,
user,
},
};
} catch {
return {
props: {
tfa,
},
};
}
}

View File

@ -0,0 +1 @@
<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_P7sC{transform-origin:center;animation:spinner_svv2 .75s infinite linear}@keyframes spinner_svv2{100%{transform:rotate(360deg)}}</style><path d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z" class="spinner_P7sC"/></svg>

After

Width:  |  Height:  |  Size: 428 B

View File

@ -0,0 +1 @@
<svg height="512" width="512" xmlns="http://www.w3.org/2000/svg"><path d="m470.4354553 45.4225006-453.6081524 175.8265381c-18.253809 8.1874695-24.4278889 24.5854034-4.4127407 33.4840851l116.3710175 37.1726685 281.3674316-174.789505c15.3625488-10.9733887 31.0910339-8.0470886 17.5573425 4.023468l-241.6571311 219.9348907-7.5913849 93.0762329c7.0313721 14.3716125 19.9055786 14.4378967 28.1172485 7.2952881l66.8582916-63.5891418 114.5050659 86.1867065c26.5942688 15.8265076 41.0652466 5.6130371 46.7870789-23.3935242l75.1055603-357.4697647c7.7979126-35.7059288-5.5005798-51.437891-39.3996277-37.7579422z"/></svg>

After

Width:  |  Height:  |  Size: 610 B

View File

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

View File

@ -0,0 +1,3 @@
.primary {
color: var(--color-primary);
}

View File

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

View File

@ -0,0 +1,8 @@
@import 'node_modules/modern-normalize/modern-normalize.css';
@import './input.css';
@import './h.css';
@import './error.css';
@import './colors.css';
@import './info.css';
@import './logo.css';
@import './button.css';

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;

9
apps/web/styles/info.css Normal file
View File

@ -0,0 +1,9 @@
.info {
display: inline-block;
font-family: Montserrat;
font-size: smaller;
font-weight: bold;
text-transform: uppercase;
text-decoration: none;
color: var(--color-primary);
}

View File

@ -1,6 +1,6 @@
.input { input {
font-family: Montserrat; font-family: Montserrat;
border: 1px solid rgba(0,16,61,.12); border: 1px solid rgba(0, 16, 61, 0.12);
box-sizing: border-box; box-sizing: border-box;
height: 40px; height: 40px;
background: #fff; background: #fff;
@ -10,8 +10,13 @@
/* 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;
}

6
apps/web/styles/logo.css Normal file
View File

@ -0,0 +1,6 @@
.logo {
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 5px;
}

View File

@ -2,6 +2,7 @@
"$schema": "https://json.schemastore.org/tsconfig", "$schema": "https://json.schemastore.org/tsconfig",
"display": "Next.js", "display": "Next.js",
"compilerOptions": { "compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
@ -25,6 +26,6 @@
"@/*": ["*"] "@/*": ["*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "types/svgr.d.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }

3
apps/web/types/error.ts Normal file
View File

@ -0,0 +1,3 @@
export type TelegramUrlResponse = {
message: string;
};

12
apps/web/types/svgr.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
declare module '*.svg' {
import type { FC, SVGProps } from 'react';
const content: FC<SVGProps<SVGElement>>;
export default content;
}
declare module '*.svg?url' {
const content: any;
export default content;
}

9
apps/web/types/user.ts Normal file
View File

@ -0,0 +1,9 @@
export type LdapUser = {
department: string;
displayName: string;
domain: string;
domainName: string;
mail: string;
position: string;
username: string;
};

View File

@ -3,8 +3,16 @@ version: '3'
services: services:
auth_web: auth_web:
build: build:
args:
- APP_BASE_PATH=${APP_BASE_PATH}
- APP_DESCRIPTION=${APP_DESCRIPTION}
- TELEGRAM_BOT_URL=${TELEGRAM_BOT_URL}
context: . context: .
dockerfile: ./apps/web/Dockerfile dockerfile: ./apps/web/Dockerfile
environment:
- APP_BASE_PATH=${APP_BASE_PATH}
- APP_DESCRIPTION=${APP_DESCRIPTION}
- TELEGRAM_BOT_URL=${TELEGRAM_BOT_URL}
restart: always restart: always
networks: networks:
- auth_network - auth_network
@ -23,9 +31,13 @@ services:
- API_SECRET=${API_SECRET} - API_SECRET=${API_SECRET}
- API_TOKEN_TTL=${API_TOKEN_TTL} - API_TOKEN_TTL=${API_TOKEN_TTL}
- API_CACHE_TTL=${API_CACHE_TTL} - API_CACHE_TTL=${API_CACHE_TTL}
- COOKIE_TOKEN_NAME=${COOKIE_TOKEN_NAME}
- COOKIE_TOKEN_MAX_AGE=${COOKIE_TOKEN_MAX_AGE}
- REDIS_HOST=redis - REDIS_HOST=redis
- MONGO_HOST=mongo - MONGO_HOST=mongo
- WEB_SERVER=auth_web:3000 - TELEGRAM_URL_SEND_AUTH_MESSAGE=${TELEGRAM_URL_SEND_AUTH_MESSAGE}
- TELEGRAM_URL_SEND_AUTH_LOGIN=${TELEGRAM_URL_SEND_AUTH_LOGIN}
- TELEGRAM_URL_SEND_AUTH_PASSWORD=${TELEGRAM_URL_SEND_AUTH_PASSWORD}
restart: always restart: always
networks: networks:
- auth_network - auth_network
@ -36,6 +48,7 @@ services:
ALLOW_EMPTY_PASSWORD: 'yes' ALLOW_EMPTY_PASSWORD: 'yes'
networks: networks:
- auth_network - auth_network
restart: always
mongo: mongo:
image: mongo:latest image: mongo:latest

View File

@ -2,9 +2,6 @@
"name": "evo-auth", "name": "evo-auth",
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"workspaces": [
"apps/*"
],
"scripts": { "scripts": {
"build": "dotenv -e .env turbo run build", "build": "dotenv -e .env turbo run build",
"dev": "dotenv -e .env.local turbo run dev", "dev": "dotenv -e .env.local turbo run dev",
@ -17,11 +14,10 @@
"devDependencies": { "devDependencies": {
"dotenv-cli": "^7.3.0", "dotenv-cli": "^7.3.0",
"prettier": "latest", "prettier": "latest",
"turbo": "latest" "turbo": "^1.12.4"
}, },
"packageManager": "pnpm@8.9.0",
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=18"
}, }
"dependencies": {},
"packageManager": "yarn@1.22.19"
} }

11049
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

3
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,3 @@
packages:
- "apps/*"
- "packages/*"

8717
yarn.lock

File diff suppressed because it is too large Load Diff