first commit
This commit is contained in:
38
apps/api-gateway/Dockerfile
Normal file
38
apps/api-gateway/Dockerfile
Normal file
@@ -0,0 +1,38 @@
|
||||
# syntax=docker/dockerfile:1.4
|
||||
|
||||
FROM node:24-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ARG NPM_REGISTRY=https://registry.npmjs.org
|
||||
|
||||
COPY package.json package-lock.json .npmrc ./
|
||||
COPY apps/sso-core/package.json ./apps/sso-core/
|
||||
COPY apps/api-gateway/package.json ./apps/api-gateway/
|
||||
COPY apps/frontend/package.json ./apps/frontend/
|
||||
COPY apps/docs/package.json ./apps/docs/
|
||||
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm config set registry "${NPM_REGISTRY}" && \
|
||||
for i in 1 2 3 4 5; do \
|
||||
echo "npm ci: попытка $i/5" && \
|
||||
npm ci --no-audit --no-fund && exit 0; \
|
||||
echo "npm ci: ошибка сети, повтор через $((i * 15)) сек..."; \
|
||||
sleep $((i * 15)); \
|
||||
done; \
|
||||
echo "npm ci: все попытки исчерпаны"; \
|
||||
exit 1
|
||||
|
||||
COPY apps ./apps
|
||||
COPY shared ./shared
|
||||
COPY tsconfig.base.json ./
|
||||
|
||||
ENV PORT="3000"
|
||||
ENV SSO_CORE_GRPC_URL="sso-core:50051"
|
||||
ENV JWT_ACCESS_SECRET="docker-access-secret"
|
||||
|
||||
RUN npm --workspace @lendry/api-gateway run build
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", "apps/api-gateway/dist/main.js"]
|
||||
8
apps/api-gateway/nest-cli.json
Normal file
8
apps/api-gateway/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
31
apps/api-gateway/package.json
Normal file
31
apps/api-gateway/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@lendry/api-gateway",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"start": "nest start",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1075.0",
|
||||
"@grpc/grpc-js": "^1.14.3",
|
||||
"@grpc/proto-loader": "^0.8.0",
|
||||
"@nestjs/common": "^11.1.9",
|
||||
"@nestjs/config": "^4.0.2",
|
||||
"@nestjs/core": "^11.1.9",
|
||||
"@nestjs/jwt": "^11.0.2",
|
||||
"@nestjs/microservices": "^11.1.9",
|
||||
"@nestjs/platform-express": "^11.1.9",
|
||||
"@nestjs/swagger": "^11.2.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.3",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^11.0.14",
|
||||
"@types/node": "^24.10.1",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
60
apps/api-gateway/src/app.module.ts
Normal file
60
apps/api-gateway/src/app.module.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ClientsModule, Transport } from '@nestjs/microservices';
|
||||
import { join } from 'node:path';
|
||||
import { AdminController } from './controllers/admin.controller';
|
||||
import { AuthController } from './controllers/auth.controller';
|
||||
import { RbacController } from './controllers/rbac.controller';
|
||||
import { SecurityController } from './controllers/security.controller';
|
||||
import { SettingsController } from './controllers/settings.controller';
|
||||
import { HealthController } from './controllers/health.controller';
|
||||
import { PublicSettingsController } from './controllers/public-settings.controller';
|
||||
import { ProfileController } from './controllers/profile.controller';
|
||||
import { DocumentsController } from './controllers/documents.controller';
|
||||
import { AddressesController } from './controllers/addresses.controller';
|
||||
import { OAuthController } from './controllers/oauth.controller';
|
||||
import { AdvancedAuthController } from './controllers/advanced-auth.controller';
|
||||
import { FamilyController } from './controllers/family.controller';
|
||||
import { ChatController } from './controllers/chat.controller';
|
||||
import { NotificationsController } from './controllers/notifications.controller';
|
||||
import { MediaController } from './controllers/media.controller';
|
||||
import { CoreGrpcService } from './core-grpc.service';
|
||||
import { AdminGuard, SuperAdminGuard } from './guards/admin.guard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
JwtModule.register({}),
|
||||
ClientsModule.registerAsync([
|
||||
{
|
||||
name: 'SSO_CORE',
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
transport: Transport.GRPC,
|
||||
options: {
|
||||
package: ['auth', 'admin', 'rbac', 'security', 'profile', 'documents', 'addresses', 'identity', 'media', 'notifications', 'chat'],
|
||||
protoPath: [
|
||||
join(__dirname, '../../../shared/proto/auth.proto'),
|
||||
join(__dirname, '../../../shared/proto/admin.proto'),
|
||||
join(__dirname, '../../../shared/proto/rbac.proto'),
|
||||
join(__dirname, '../../../shared/proto/security.proto'),
|
||||
join(__dirname, '../../../shared/proto/profile.proto'),
|
||||
join(__dirname, '../../../shared/proto/documents.proto'),
|
||||
join(__dirname, '../../../shared/proto/addresses.proto'),
|
||||
join(__dirname, '../../../shared/proto/identity.proto'),
|
||||
join(__dirname, '../../../shared/proto/media.proto'),
|
||||
join(__dirname, '../../../shared/proto/notifications.proto'),
|
||||
join(__dirname, '../../../shared/proto/chat.proto')
|
||||
],
|
||||
url: config.get<string>('SSO_CORE_GRPC_URL', 'localhost:50051')
|
||||
}
|
||||
})
|
||||
}
|
||||
])
|
||||
],
|
||||
controllers: [AuthController, AdminController, RbacController, SecurityController, SettingsController, PublicSettingsController, HealthController, ProfileController, DocumentsController, AddressesController, OAuthController, AdvancedAuthController, FamilyController, ChatController, NotificationsController, MediaController],
|
||||
providers: [CoreGrpcService, AdminGuard, SuperAdminGuard]
|
||||
})
|
||||
export class AppModule {}
|
||||
14
apps/api-gateway/src/auth-token.ts
Normal file
14
apps/api-gateway/src/auth-token.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
|
||||
export function extractBearerToken(authorization?: string): string {
|
||||
if (!authorization?.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException('Не передан токен доступа');
|
||||
}
|
||||
|
||||
const token = authorization.slice('Bearer '.length).trim();
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Не передан токен доступа');
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
68
apps/api-gateway/src/controllers/addresses.controller.ts
Normal file
68
apps/api-gateway/src/controllers/addresses.controller.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { Body, Controller, Delete, ForbiddenException, Get, Headers, Param, Post } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { getAuthorizedUserId } from '../document-access';
|
||||
import { UpsertAddressDto } from '../dto/addresses.dto';
|
||||
|
||||
@ApiTags('Адреса')
|
||||
@ApiBearerAuth()
|
||||
@Controller('addresses/users/:userId')
|
||||
export class AddressesController {
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
private readonly jwt: JwtService
|
||||
) {}
|
||||
|
||||
private async assertSelfAccess(authorization: string | undefined, userId: string) {
|
||||
const requesterId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
if (requesterId !== userId) {
|
||||
throw new ForbiddenException('Можно управлять только своими адресами');
|
||||
}
|
||||
return requesterId;
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Список адресов пользователя' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
async list(@Headers('authorization') authorization: string | undefined, @Param('userId') userId: string) {
|
||||
await this.assertSelfAccess(authorization, userId);
|
||||
return firstValueFrom(
|
||||
this.core.addresses.ListAddresses({ userId }).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { addresses?: unknown[] };
|
||||
return { addresses: payload.addresses ?? [] };
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Создать или обновить адрес' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: UpsertAddressDto })
|
||||
async upsert(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('userId') userId: string,
|
||||
@Body() dto: UpsertAddressDto
|
||||
) {
|
||||
await this.assertSelfAccess(authorization, userId);
|
||||
return firstValueFrom(this.core.addresses.UpsertAddress({ userId, ...dto }));
|
||||
}
|
||||
|
||||
@Delete(':addressId')
|
||||
@ApiOperation({ summary: 'Удалить адрес' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'addressId', description: 'ID адреса' })
|
||||
@ApiResponse({ status: 200, description: 'Адрес удалён' })
|
||||
async delete(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('userId') userId: string,
|
||||
@Param('addressId') addressId: string
|
||||
) {
|
||||
await this.assertSelfAccess(authorization, userId);
|
||||
return firstValueFrom(this.core.addresses.DeleteAddress({ userId, addressId }));
|
||||
}
|
||||
}
|
||||
69
apps/api-gateway/src/controllers/admin.controller.ts
Normal file
69
apps/api-gateway/src/controllers/admin.controller.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { Body, Controller, ForbiddenException, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
|
||||
import { map } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { CurrentAdmin } from '../decorators/current-admin.decorator';
|
||||
import { ListUsersQueryDto, ResetPasswordDto, SetSuperAdminDto, UpdateUserDto } from '../dto/admin.dto';
|
||||
import { AdminGuard, AdminRequestUser, assertAdminPermission, SuperAdminGuard } from '../guards/admin.guard';
|
||||
|
||||
@ApiTags('Администрирование')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminGuard)
|
||||
@Controller('admin/users')
|
||||
export class AdminController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Список пользователей', description: 'Возвращает пользователей для административной таблицы.' })
|
||||
listUsers(@Query() query: ListUsersQueryDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
if (!admin.canViewUsers && !admin.canManageUsers) {
|
||||
throw new ForbiddenException('Недостаточно прав для просмотра пользователей');
|
||||
}
|
||||
return this.core.admin.ListUsers(query).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { users?: Array<{ roles?: string[] }> };
|
||||
return {
|
||||
users: (payload.users ?? []).map((user) => ({
|
||||
...user,
|
||||
roles: user.roles ?? []
|
||||
}))
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Patch(':userId')
|
||||
@ApiOperation({ summary: 'Обновить профиль пользователя', description: 'Обновляет основные и резервные контакты пользователя.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: UpdateUserDto })
|
||||
updateUser(@Param('userId') userId: string, @Body() dto: UpdateUserDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageUsers');
|
||||
return this.core.admin.UpdateUserProfile({ userId, ...dto });
|
||||
}
|
||||
|
||||
@Post(':userId/reset-password')
|
||||
@ApiOperation({ summary: 'Сбросить пароль', description: 'Назначает пользователю новый пароль.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: ResetPasswordDto })
|
||||
resetPassword(@Param('userId') userId: string, @Body() dto: ResetPasswordDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageUsers');
|
||||
return this.core.admin.ResetPassword({ userId, newPassword: dto.newPassword });
|
||||
}
|
||||
|
||||
@Post(':userId/suspend')
|
||||
@ApiOperation({ summary: 'Заблокировать пользователя', description: 'Переводит пользователя в статус SUSPENDED и отзывает активные сессии.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
suspend(@Param('userId') userId: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageUsers');
|
||||
return this.core.admin.SuspendUser({ userId });
|
||||
}
|
||||
|
||||
@Patch(':userId/super-admin')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@ApiOperation({ summary: 'Выдать или снять права супер-администратора', description: 'Доступно только супер-администратору.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: SetSuperAdminDto })
|
||||
setSuperAdmin(@Param('userId') userId: string, @Body() dto: SetSuperAdminDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
return this.core.admin.SetSuperAdmin({ actorUserId: admin.id, userId, isSuperAdmin: dto.isSuperAdmin });
|
||||
}
|
||||
}
|
||||
42
apps/api-gateway/src/controllers/advanced-auth.controller.ts
Normal file
42
apps/api-gateway/src/controllers/advanced-auth.controller.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { QrSessionDto, WebAuthnDto } from '../dto/identity.dto';
|
||||
|
||||
@ApiTags('Биометрия и QR-вход')
|
||||
@Controller('auth/advanced')
|
||||
export class AdvancedAuthController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Post('webauthn/register/challenge')
|
||||
@ApiOperation({ summary: 'Challenge регистрации WebAuthn', description: 'Создает challenge для регистрации лица/отпечатка. Endpoint готов для подключения настоящего WebAuthn attestation.' })
|
||||
@ApiBody({ type: WebAuthnDto })
|
||||
@ApiResponse({ status: 201, description: 'Challenge создан' })
|
||||
webAuthnRegister(@Body() dto: WebAuthnDto) {
|
||||
return this.core.advancedAuth.CreateWebAuthnRegistrationChallenge(dto);
|
||||
}
|
||||
|
||||
@Post('webauthn/login/challenge')
|
||||
@ApiOperation({ summary: 'Challenge входа WebAuthn', description: 'Создает challenge для входа по лицу или отпечатку.' })
|
||||
@ApiBody({ type: WebAuthnDto })
|
||||
@ApiResponse({ status: 201, description: 'Challenge создан' })
|
||||
webAuthnLogin(@Body() dto: WebAuthnDto) {
|
||||
return this.core.advancedAuth.CreateWebAuthnLoginChallenge(dto);
|
||||
}
|
||||
|
||||
@Post('qr/session')
|
||||
@ApiOperation({ summary: 'Создать QR-сессию', description: 'Создает временную QR-сессию для входа с другого устройства.' })
|
||||
@ApiBody({ type: QrSessionDto })
|
||||
@ApiResponse({ status: 201, description: 'QR-сессия создана' })
|
||||
createQr(@Body() dto: QrSessionDto) {
|
||||
return this.core.advancedAuth.CreateQrSession(dto);
|
||||
}
|
||||
|
||||
@Get('qr/session/:sessionId')
|
||||
@ApiOperation({ summary: 'Проверить QR-сессию', description: 'Возвращает текущий статус QR-сессии: PENDING/CONFIRMED/EXPIRED.' })
|
||||
@ApiParam({ name: 'sessionId', description: 'ID QR-сессии' })
|
||||
@ApiResponse({ status: 200, description: 'Статус QR-сессии получен' })
|
||||
pollQr(@Param('sessionId') sessionId: string) {
|
||||
return this.core.advancedAuth.PollQrSession({ sessionId });
|
||||
}
|
||||
}
|
||||
129
apps/api-gateway/src/controllers/auth.controller.ts
Normal file
129
apps/api-gateway/src/controllers/auth.controller.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import { Body, Controller, Get, Headers, Post } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { IdentifyDto, LdapLoginDto, LoginDto, PasswordlessOtpDto, PasswordlessVerifyDto, PasswordLoginDto, RefreshSessionDto, RegisterDto, VerifyPinDto } from '../dto/auth.dto';
|
||||
import { resolveAuthorizedPayload, verifyAccessToken } from '../session-auth';
|
||||
|
||||
@ApiTags('Аутентификация')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
private readonly jwt: JwtService
|
||||
) {}
|
||||
|
||||
@Post('register')
|
||||
@ApiOperation({ summary: 'Регистрация пользователя', description: 'Создает пользователя. Первый пользователь безопасно получает права super admin.' })
|
||||
@ApiBody({ type: RegisterDto })
|
||||
register(@Body() dto: RegisterDto) {
|
||||
return this.core.auth.Register(dto);
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
@ApiOperation({ summary: 'Вход по почте, телефону или логину', description: 'Возвращает JWT и refresh token. Если PIN включен, сессия создается в ограниченном режиме.' })
|
||||
@ApiBody({ type: LoginDto })
|
||||
login(@Body() dto: LoginDto) {
|
||||
return this.core.auth.Login(dto);
|
||||
}
|
||||
|
||||
@Post('identify')
|
||||
@ApiOperation({ summary: 'Проверить способ входа', description: 'Identifier-first шаг: проверяет, существует ли пользователь, задан ли пароль и включен ли PIN.' })
|
||||
@ApiBody({ type: IdentifyDto })
|
||||
identify(@Body() dto: IdentifyDto) {
|
||||
return this.core.auth.Identify(dto);
|
||||
}
|
||||
|
||||
@Post('otp/send')
|
||||
@ApiOperation({ summary: 'Отправить OTP для входа', description: 'Passwordless-first вход: пользователь вводит почту или телефон, сервер создает 6-значный код и пишет его в console.log.' })
|
||||
@ApiBody({ type: PasswordlessOtpDto })
|
||||
sendOtp(@Body() dto: PasswordlessOtpDto) {
|
||||
return this.core.auth.SendOtp({ recipient: dto.recipient, channel: dto.channel });
|
||||
}
|
||||
|
||||
@Post('otp/verify')
|
||||
@ApiOperation({ summary: 'Проверить OTP для входа', description: 'Если пользователь не существует, создает его. Если пароль не задан, сразу возвращает JWT. Если пароль задан, возвращает requiresPassword=true и tempAuthToken.' })
|
||||
@ApiBody({ type: PasswordlessVerifyDto })
|
||||
verifyOtp(@Body() dto: PasswordlessVerifyDto) {
|
||||
return this.core.auth.VerifyOtp(dto);
|
||||
}
|
||||
|
||||
@Post('login/password')
|
||||
@ApiOperation({ summary: 'Войти по паролю', description: 'Identifier-first парольный шаг. Принимает login+password, либо tempAuthToken+password для совместимости, затем выдает JWT.' })
|
||||
@ApiBody({ type: PasswordLoginDto })
|
||||
loginWithPassword(@Body() dto: PasswordLoginDto) {
|
||||
return this.core.auth.LoginWithPassword(dto);
|
||||
}
|
||||
|
||||
@Post('ldap/login')
|
||||
@ApiOperation({ summary: 'Войти через LDAP/LDAPS', description: 'Аутентификация через корпоративный LDAP-сервер. Требует включённой настройки LDAP_ENABLED.' })
|
||||
@ApiBody({ type: LdapLoginDto })
|
||||
loginWithLdap(@Body() dto: LdapLoginDto) {
|
||||
return this.core.auth.LoginWithLdap(dto);
|
||||
}
|
||||
|
||||
@Post('pin/verify')
|
||||
@ApiOperation({ summary: 'Подтвердить PIN-код', description: 'Разблокирует временную сессию и выдает JWT с pinVerified=true.' })
|
||||
@ApiBody({ type: VerifyPinDto })
|
||||
verifyPin(@Body() dto: VerifyPinDto) {
|
||||
return this.core.auth.VerifyPin(dto);
|
||||
}
|
||||
|
||||
@Post('refresh')
|
||||
@ApiOperation({ summary: 'Обновить access token', description: 'Обновляет JWT по refresh token. Если сессия заблокирована PIN-кодом, возвращает requiresPin=true без выхода из аккаунта.' })
|
||||
@ApiBody({ type: RefreshSessionDto })
|
||||
refresh(@Body() dto: RefreshSessionDto) {
|
||||
return this.core.auth.RefreshSession(dto);
|
||||
}
|
||||
|
||||
@Get('session')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({
|
||||
summary: 'Состояние текущей сессии',
|
||||
description: 'Возвращает профиль и флаг PIN-блокировки. Не выбрасывает пользователя из аккаунта при заблокированном PIN.'
|
||||
})
|
||||
async session(@Headers('authorization') authorization?: string) {
|
||||
const payload = await verifyAccessToken(this.jwt, authorization);
|
||||
|
||||
if (!payload.sessionId) {
|
||||
const user = await firstValueFrom(this.core.auth.GetMe({ userId: payload.sub }));
|
||||
return { requiresPin: false, sessionId: null, pinVerified: true, user };
|
||||
}
|
||||
|
||||
const validation = (await firstValueFrom(
|
||||
this.core.auth.ValidateSession({
|
||||
userId: payload.sub,
|
||||
sessionId: payload.sessionId,
|
||||
touchActivity: false
|
||||
})
|
||||
)) as { requiresPin: boolean; sessionId: string; pinVerified: boolean };
|
||||
|
||||
const user = await firstValueFrom(this.core.auth.GetMe({ userId: payload.sub }));
|
||||
|
||||
if (!validation.requiresPin) {
|
||||
await firstValueFrom(
|
||||
this.core.auth.ValidateSession({
|
||||
userId: payload.sub,
|
||||
sessionId: payload.sessionId,
|
||||
touchActivity: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
requiresPin: validation.requiresPin,
|
||||
sessionId: validation.sessionId,
|
||||
pinVerified: validation.pinVerified,
|
||||
user
|
||||
};
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Текущий пользователь', description: 'Возвращает профиль пользователя по access token.' })
|
||||
async me(@Headers('authorization') authorization?: string) {
|
||||
const payload = await resolveAuthorizedPayload(this.jwt, this.core, authorization);
|
||||
return firstValueFrom(this.core.auth.GetMe({ userId: payload.sub }));
|
||||
}
|
||||
}
|
||||
142
apps/api-gateway/src/controllers/chat.controller.ts
Normal file
142
apps/api-gateway/src/controllers/chat.controller.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { Body, Controller, Get, Headers, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { getAuthorizedUserId } from '../document-access';
|
||||
import {
|
||||
CreateChatRoomDto,
|
||||
SendChatMessageDto,
|
||||
SetRoomNotificationsMutedDto,
|
||||
UpdateChatRoomDto,
|
||||
VotePollDto
|
||||
} from '../dto/chat.dto';
|
||||
|
||||
@ApiTags('Чат')
|
||||
@ApiBearerAuth()
|
||||
@Controller('chat')
|
||||
export class ChatController {
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
private readonly jwt: JwtService
|
||||
) {}
|
||||
|
||||
private async auth(authorization?: string) {
|
||||
return getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
}
|
||||
|
||||
@Get('groups/:groupId/rooms')
|
||||
@ApiOperation({ summary: 'Список чатов семьи' })
|
||||
async listRooms(@Headers('authorization') authorization: string | undefined, @Param('groupId') groupId: string) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.chat.ListRooms({ userId, groupId }).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { rooms?: unknown[] };
|
||||
return { rooms: payload.rooms ?? [] };
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Post('groups/:groupId/rooms')
|
||||
@ApiOperation({ summary: 'Создать групповой чат' })
|
||||
async createRoom(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('groupId') groupId: string,
|
||||
@Body() dto: CreateChatRoomDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.chat.CreateRoom({ userId, groupId, name: dto.name, memberUserIds: dto.memberUserIds ?? [] })
|
||||
);
|
||||
}
|
||||
|
||||
@Patch('rooms/:roomId')
|
||||
@ApiOperation({ summary: 'Настройки чата' })
|
||||
async updateRoom(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: UpdateChatRoomDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.chat.UpdateRoomSettings({
|
||||
userId,
|
||||
roomId,
|
||||
name: dto.name,
|
||||
notificationsMuted: dto.notificationsMuted
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get('rooms/:roomId/messages')
|
||||
@ApiOperation({ summary: 'Сообщения чата' })
|
||||
async listMessages(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Query('beforeMessageId') beforeMessageId?: string,
|
||||
@Query('limit') limit?: string
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.chat.ListMessages({
|
||||
userId,
|
||||
roomId,
|
||||
beforeMessageId,
|
||||
limit: limit ? Number(limit) : 50
|
||||
}).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { messages?: unknown[] };
|
||||
return { messages: payload.messages ?? [] };
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Post('rooms/:roomId/messages')
|
||||
@ApiOperation({ summary: 'Отправить сообщение' })
|
||||
async sendMessage(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: SendChatMessageDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.chat.SendMessage({
|
||||
userId,
|
||||
roomId,
|
||||
type: dto.type,
|
||||
content: dto.content,
|
||||
replyToId: dto.replyToId,
|
||||
storageKey: dto.storageKey,
|
||||
mimeType: dto.mimeType,
|
||||
metadataJson: dto.metadataJson,
|
||||
poll: dto.poll
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Post('messages/:messageId/vote')
|
||||
@ApiOperation({ summary: 'Голос в опросе' })
|
||||
async votePoll(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('messageId') messageId: string,
|
||||
@Body() dto: VotePollDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.chat.VotePoll({ userId, messageId, optionIds: dto.optionIds }));
|
||||
}
|
||||
|
||||
@Post('rooms/:roomId/mute')
|
||||
@ApiOperation({ summary: 'Выключить/включить уведомления чата' })
|
||||
async setMuted(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: SetRoomNotificationsMutedDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.chat.SetRoomNotificationsMuted({ userId, roomId, muted: dto.muted }));
|
||||
}
|
||||
}
|
||||
97
apps/api-gateway/src/controllers/documents.controller.ts
Normal file
97
apps/api-gateway/src/controllers/documents.controller.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { Body, Controller, Delete, Get, Headers, Param, Patch, Post } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { map } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { assertDocumentsReadAccess, assertDocumentsWriteAccess } from '../document-access';
|
||||
import { CreateDocumentDto, UpdateDocumentDto } from '../dto/documents.dto';
|
||||
|
||||
@ApiTags('Хранилище данных и документы')
|
||||
@ApiBearerAuth()
|
||||
@Controller('documents/users/:userId')
|
||||
export class DocumentsController {
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
private readonly jwt: JwtService
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'Создать документ', description: 'Создает документ пользователя с данными формы. Поля шифруются в SSO Core.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: CreateDocumentDto })
|
||||
async create(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('userId') userId: string,
|
||||
@Body() dto: CreateDocumentDto
|
||||
) {
|
||||
await assertDocumentsWriteAccess(this.jwt, this.core, authorization, userId);
|
||||
return firstValueFrom(
|
||||
this.core.documents.CreateDocument({
|
||||
userId,
|
||||
type: dto.type,
|
||||
number: dto.number ?? '—',
|
||||
issuedAt: dto.issuedAt,
|
||||
expiresAt: dto.expiresAt,
|
||||
metadataJson: dto.metadataJson
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Список документов', description: 'Возвращает все документы пользователя.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
async list(@Headers('authorization') authorization: string | undefined, @Param('userId') userId: string) {
|
||||
await assertDocumentsReadAccess(this.jwt, this.core, authorization, userId);
|
||||
return firstValueFrom(
|
||||
this.core.documents.ListDocuments({ userId }).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { documents?: unknown[] };
|
||||
return { documents: payload.documents ?? [] };
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':documentId')
|
||||
@ApiOperation({ summary: 'Получить документ', description: 'Возвращает один документ пользователя с расшифрованными полями.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'documentId', description: 'ID документа' })
|
||||
async get(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('userId') userId: string,
|
||||
@Param('documentId') documentId: string
|
||||
) {
|
||||
await assertDocumentsReadAccess(this.jwt, this.core, authorization, userId);
|
||||
return firstValueFrom(this.core.documents.GetDocument({ userId, documentId }));
|
||||
}
|
||||
|
||||
@Patch(':documentId')
|
||||
@ApiOperation({ summary: 'Обновить документ', description: 'Обновляет данные формы документа.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'documentId', description: 'ID документа' })
|
||||
@ApiBody({ type: UpdateDocumentDto })
|
||||
async update(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('userId') userId: string,
|
||||
@Param('documentId') documentId: string,
|
||||
@Body() dto: UpdateDocumentDto
|
||||
) {
|
||||
await assertDocumentsWriteAccess(this.jwt, this.core, authorization, userId);
|
||||
return firstValueFrom(this.core.documents.UpdateDocument({ userId, documentId, ...dto }));
|
||||
}
|
||||
|
||||
@Delete(':documentId')
|
||||
@ApiOperation({ summary: 'Удалить документ', description: 'Удаляет документ пользователя.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'documentId', description: 'ID документа' })
|
||||
@ApiResponse({ status: 200, description: 'Документ удалён' })
|
||||
async delete(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('userId') userId: string,
|
||||
@Param('documentId') documentId: string
|
||||
) {
|
||||
await assertDocumentsWriteAccess(this.jwt, this.core, authorization, userId);
|
||||
return firstValueFrom(this.core.documents.DeleteDocument({ userId, documentId }));
|
||||
}
|
||||
}
|
||||
130
apps/api-gateway/src/controllers/family.controller.ts
Normal file
130
apps/api-gateway/src/controllers/family.controller.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { Body, Controller, Delete, ForbiddenException, Get, Headers, Param, Patch, Post } from '@nestjs/common';
|
||||
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
|
||||
import { getAuthorizedUserId } from '../document-access';
|
||||
|
||||
import { AddFamilyMemberDto, CreateFamilyGroupDto, RespondFamilyInviteDto, SendFamilyInviteDto, UpdateFamilyGroupDto } from '../dto/identity.dto';
|
||||
|
||||
|
||||
|
||||
@ApiTags('Семья')
|
||||
|
||||
@ApiBearerAuth()
|
||||
|
||||
@Controller('family')
|
||||
|
||||
export class FamilyController {
|
||||
|
||||
constructor(
|
||||
|
||||
private readonly core: CoreGrpcService,
|
||||
|
||||
private readonly jwt: JwtService
|
||||
|
||||
) {}
|
||||
|
||||
|
||||
|
||||
private async auth(authorization?: string) {
|
||||
|
||||
return getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Post('groups')
|
||||
|
||||
@ApiOperation({ summary: 'Создать семейную группу' })
|
||||
|
||||
@ApiBody({ type: CreateFamilyGroupDto })
|
||||
|
||||
async createGroup(@Headers('authorization') authorization: string | undefined, @Body() dto: CreateFamilyGroupDto) {
|
||||
|
||||
const userId = await this.auth(authorization);
|
||||
|
||||
if (dto.ownerId !== userId) {
|
||||
|
||||
throw new ForbiddenException('Можно создавать семью только от своего имени');
|
||||
|
||||
}
|
||||
|
||||
return firstValueFrom(this.core.family.CreateFamilyGroup(dto));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Get('users/:userId/groups')
|
||||
|
||||
@ApiOperation({ summary: 'Список семей пользователя' })
|
||||
|
||||
async listGroups(@Headers('authorization') authorization: string | undefined, @Param('userId') userId: string) {
|
||||
|
||||
const requesterId = await this.auth(authorization);
|
||||
|
||||
if (requesterId !== userId) {
|
||||
|
||||
throw new ForbiddenException('Можно просматривать только свои семьи');
|
||||
|
||||
}
|
||||
|
||||
return firstValueFrom(
|
||||
|
||||
this.core.family.ListFamilyGroups({ userId }).pipe(
|
||||
|
||||
map((response) => {
|
||||
|
||||
const payload = response as { groups?: unknown[] };
|
||||
|
||||
return { groups: payload.groups ?? [] };
|
||||
|
||||
})
|
||||
|
||||
)
|
||||
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Get('groups/:groupId')
|
||||
|
||||
@ApiOperation({ summary: 'Получить семейную группу' })
|
||||
|
||||
async getGroup(@Headers('authorization') authorization: string | undefined, @Param('groupId') groupId: string) {
|
||||
|
||||
const requesterId = await this.auth(authorization);
|
||||
|
||||
return firstValueFrom(this.core.family.GetFamilyGroup({ requesterId, groupId }));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Patch('groups/:groupId')
|
||||
|
||||
@ApiOperation({ summary: 'Обновить семейную группу' })
|
||||
|
||||
async updateGroup(
|
||||
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
|
||||
@Param('groupId') groupId: string,
|
||||
|
||||
@Body() dto: UpdateFamilyGroupDto
|
||||
|
||||
) {
|
||||
|
||||
const requesterId = await this.auth(authorization);
|
||||
|
||||
9
apps/api-gateway/src/controllers/health.controller.ts
Normal file
9
apps/api-gateway/src/controllers/health.controller.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
@Get()
|
||||
check() {
|
||||
return { status: 'ok', service: 'api-gateway' };
|
||||
}
|
||||
}
|
||||
215
apps/api-gateway/src/controllers/media.controller.ts
Normal file
215
apps/api-gateway/src/controllers/media.controller.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
import { Body, Controller, Get, Headers, Param, Post, Query, Res } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { getAuthorizedUserId } from '../document-access';
|
||||
import { AvatarUploadDto, ChatMediaUploadDto, ConfirmAvatarDto, DocumentPhotoUploadDto } from '../dto/media.dto';
|
||||
import { buildContentDisposition } from '../media-content-disposition';
|
||||
|
||||
type StreamResponse = {
|
||||
setHeader: (key: string, value: string) => void;
|
||||
status: (code: number) => { json: (body: unknown) => void };
|
||||
} & NodeJS.WritableStream;
|
||||
|
||||
@ApiTags('Медиа')
|
||||
@Controller('media')
|
||||
export class MediaController {
|
||||
private s3Client: S3Client | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
private readonly jwt: JwtService
|
||||
) {}
|
||||
|
||||
private getS3Client() {
|
||||
if (!this.s3Client) {
|
||||
const endpoint = process.env.MINIO_ENDPOINT ?? 'localhost:9000';
|
||||
const useSsl = process.env.MINIO_USE_SSL === 'true';
|
||||
this.s3Client = new S3Client({
|
||||
endpoint: `${useSsl ? 'https' : 'http'}://${endpoint}`,
|
||||
region: process.env.MINIO_REGION ?? 'us-east-1',
|
||||
credentials: {
|
||||
accessKeyId: process.env.MINIO_ACCESS_KEY ?? 'minioadmin',
|
||||
secretAccessKey: process.env.MINIO_SECRET_KEY ?? 'minioadmin'
|
||||
},
|
||||
forcePathStyle: true
|
||||
});
|
||||
}
|
||||
return this.s3Client;
|
||||
}
|
||||
|
||||
private async authUserId(authorization?: string) {
|
||||
return getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
}
|
||||
|
||||
@Post('avatars/upload-url')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Получить URL для загрузки аватара', description: 'Возвращает presigned URL MinIO для загрузки изображения аватара.' })
|
||||
@ApiBody({ type: AvatarUploadDto })
|
||||
async createAvatarUploadUrl(@Headers('authorization') authorization: string | undefined, @Body() dto: AvatarUploadDto) {
|
||||
const userId = await this.authUserId(authorization);
|
||||
return firstValueFrom(this.core.media.CreateAvatarUploadUrl({ userId, contentType: dto.contentType }));
|
||||
}
|
||||
|
||||
@Post('avatars/confirm')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Подтвердить загрузку аватара', description: 'Сохраняет ключ объекта MinIO как аватар пользователя.' })
|
||||
@ApiBody({ type: ConfirmAvatarDto })
|
||||
async confirmAvatar(@Headers('authorization') authorization: string | undefined, @Body() dto: ConfirmAvatarDto) {
|
||||
const userId = await this.authUserId(authorization);
|
||||
return firstValueFrom(this.core.media.ConfirmAvatar({ userId, storageKey: dto.storageKey }));
|
||||
}
|
||||
|
||||
@Get('avatars/:userId/url')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Получить временную ссылку на аватар', description: 'Возвращает ссылку, действующую 15 минут. Без авторизации ссылка не выдаётся.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
async getAvatarUrl(@Headers('authorization') authorization: string | undefined, @Param('userId') userId: string) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(this.core.media.GetAvatarAccessUrl({ requesterId, targetUserId: userId }));
|
||||
}
|
||||
|
||||
@Post('documents/:documentId/photo/upload-url')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Получить URL для фото документа', description: 'Presigned URL для загрузки скана/фото документа в MinIO.' })
|
||||
@ApiBody({ type: DocumentPhotoUploadDto })
|
||||
async createDocumentPhotoUploadUrl(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('documentId') documentId: string,
|
||||
@Body() dto: DocumentPhotoUploadDto
|
||||
) {
|
||||
const userId = await this.authUserId(authorization);
|
||||
return firstValueFrom(this.core.media.CreateDocumentPhotoUploadUrl({ userId, documentId, contentType: dto.contentType }));
|
||||
}
|
||||
|
||||
@Get('users/:userId/documents/photo-url')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Получить ссылку на фото документа', description: 'Временная ссылка на просмотр фото документа (15 минут).' })
|
||||
@ApiParam({ name: 'userId', description: 'ID владельца документа' })
|
||||
@ApiQuery({ name: 'storageKey', description: 'Ключ объекта в MinIO' })
|
||||
async getDocumentPhotoUrl(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('userId') userId: string,
|
||||
@Query('storageKey') storageKey: string
|
||||
) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.media.GetDocumentPhotoAccessUrl({ requesterId, targetUserId: userId, storageKey })
|
||||
);
|
||||
}
|
||||
|
||||
@Get('stream/:token')
|
||||
@ApiOperation({ summary: 'Потоковая выдача медиа', description: 'Отдаёт файл по временному токену. Для файлов чата требуется Authorization. Токен действует 15 минут.' })
|
||||
@ApiParam({ name: 'token', description: 'Временный JWT-токен доступа' })
|
||||
@ApiResponse({ status: 403, description: 'Ссылка недействительна или истекла' })
|
||||
async stream(
|
||||
@Param('token') token: string,
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Query('download') download: string | undefined,
|
||||
@Res({ passthrough: false }) response: StreamResponse
|
||||
) {
|
||||
let requesterId: string | undefined;
|
||||
if (authorization) {
|
||||
try {
|
||||
requesterId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
} catch {
|
||||
requesterId = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const resolved = await firstValueFrom(this.core.media.ResolveStreamToken({ token, requesterId }));
|
||||
const payload = resolved as { storageKey: string; contentType: string; fileName?: string };
|
||||
const bucket = process.env.MINIO_BUCKET ?? 'lendry-id';
|
||||
const object = await this.getS3Client().send(
|
||||
new GetObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: payload.storageKey
|
||||
})
|
||||
);
|
||||
|
||||
response.setHeader('Content-Type', payload.contentType);
|
||||
response.setHeader('Cache-Control', 'private, no-store');
|
||||
if (payload.fileName) {
|
||||
const asAttachment = download === '1' || download === 'true';
|
||||
response.setHeader(
|
||||
'Content-Disposition',
|
||||
buildContentDisposition(asAttachment ? 'attachment' : 'inline', payload.fileName)
|
||||
);
|
||||
}
|
||||
const body = object.Body;
|
||||
if (!body) {
|
||||
response.status(404).json({ message: 'Файл не найден' });
|
||||
return;
|
||||
}
|
||||
|
||||
const stream = body as NodeJS.ReadableStream;
|
||||
stream.pipe(response);
|
||||
}
|
||||
|
||||
@Post('families/:groupId/avatar/upload-url')
|
||||
@ApiBearerAuth()
|
||||
async createFamilyAvatarUploadUrl(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('groupId') groupId: string,
|
||||
@Body() dto: AvatarUploadDto
|
||||
) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.media.CreateFamilyAvatarUploadUrl({ requesterId, groupId, contentType: dto.contentType })
|
||||
);
|
||||
}
|
||||
|
||||
@Post('families/:groupId/avatar/confirm')
|
||||
@ApiBearerAuth()
|
||||
async confirmFamilyAvatar(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('groupId') groupId: string,
|
||||
@Body() dto: ConfirmAvatarDto
|
||||
) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.media.ConfirmFamilyAvatar({ requesterId, groupId, storageKey: dto.storageKey })
|
||||
);
|
||||
}
|
||||
|
||||
@Get('families/:groupId/avatar/url')
|
||||
@ApiBearerAuth()
|
||||
async getFamilyAvatarUrl(@Headers('authorization') authorization: string | undefined, @Param('groupId') groupId: string) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(this.core.media.GetFamilyAvatarAccessUrl({ requesterId, groupId }));
|
||||
}
|
||||
|
||||
@Post('chat/:roomId/media/upload-url')
|
||||
@ApiBearerAuth()
|
||||
async createChatMediaUploadUrl(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: ChatMediaUploadDto
|
||||
) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.media.CreateChatMediaUploadUrl({
|
||||
requesterId,
|
||||
roomId,
|
||||
contentType: dto.contentType,
|
||||
fileName: dto.fileName
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get('chat/:roomId/media/url')
|
||||
@ApiBearerAuth()
|
||||
async getChatMediaUrl(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Query('storageKey') storageKey: string,
|
||||
@Query('fileName') fileName?: string
|
||||
) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.media.GetChatMediaAccessUrl({ requesterId, roomId, storageKey, fileName })
|
||||
);
|
||||
}
|
||||
}
|
||||
82
apps/api-gateway/src/controllers/notifications.controller.ts
Normal file
82
apps/api-gateway/src/controllers/notifications.controller.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { Body, Controller, Delete, Get, Headers, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { getAuthorizedUserId } from '../document-access';
|
||||
import { MarkNotificationReadDto } from '../dto/notifications.dto';
|
||||
|
||||
@ApiTags('Уведомления')
|
||||
@ApiBearerAuth()
|
||||
@Controller('notifications')
|
||||
export class NotificationsController {
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
private readonly jwt: JwtService
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Список уведомлений' })
|
||||
async list(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('unreadOnly') unreadOnly?: string
|
||||
) {
|
||||
const userId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
return firstValueFrom(
|
||||
this.core.notifications.ListNotifications({
|
||||
userId,
|
||||
limit: limit ? Number(limit) : 30,
|
||||
unreadOnly: unreadOnly === 'true'
|
||||
}).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { notifications?: unknown[] };
|
||||
return { notifications: payload.notifications ?? [] };
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Get('unread-count')
|
||||
@ApiOperation({ summary: 'Количество непрочитанных уведомлений' })
|
||||
async unreadCount(@Headers('authorization') authorization: string | undefined) {
|
||||
const userId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
return firstValueFrom(this.core.notifications.GetUnreadCount({ userId }));
|
||||
}
|
||||
|
||||
@Patch(':notificationId/read')
|
||||
@ApiOperation({ summary: 'Удалить просмотренное уведомление' })
|
||||
async markRead(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('notificationId') notificationId: string,
|
||||
@Body() _dto: MarkNotificationReadDto
|
||||
) {
|
||||
const userId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
return firstValueFrom(this.core.notifications.DeleteNotification({ userId, notificationId }));
|
||||
}
|
||||
|
||||
@Delete(':notificationId')
|
||||
@ApiOperation({ summary: 'Удалить уведомление' })
|
||||
async deleteNotification(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('notificationId') notificationId: string
|
||||
) {
|
||||
const userId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
return firstValueFrom(this.core.notifications.DeleteNotification({ userId, notificationId }));
|
||||
}
|
||||
|
||||
@Post('read-all')
|
||||
@ApiOperation({ summary: 'Удалить все уведомления' })
|
||||
async markAllRead(@Headers('authorization') authorization: string | undefined) {
|
||||
const userId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
return firstValueFrom(this.core.notifications.DeleteAllNotifications({ userId }));
|
||||
}
|
||||
|
||||
@Delete()
|
||||
@ApiOperation({ summary: 'Удалить все уведомления' })
|
||||
async deleteAll(@Headers('authorization') authorization: string | undefined) {
|
||||
const userId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
return firstValueFrom(this.core.notifications.DeleteAllNotifications({ userId }));
|
||||
}
|
||||
}
|
||||
38
apps/api-gateway/src/controllers/oauth.controller.ts
Normal file
38
apps/api-gateway/src/controllers/oauth.controller.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Body, Controller, Get, Headers, Post, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { OAuthAuthorizeQueryDto, OAuthTokenDto } from '../dto/identity.dto';
|
||||
import { extractBearerToken } from '../auth-token';
|
||||
|
||||
@ApiTags('OAuth 2.0')
|
||||
@Controller('oauth')
|
||||
export class OAuthController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Get('authorize')
|
||||
@ApiOperation({ summary: 'OAuth авторизация', description: 'Создает authorization_code и возвращает redirectUrl для OAuth клиента. Consent считается подтвержденным для переданного userId.' })
|
||||
@ApiQuery({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiQuery({ name: 'clientId', description: 'OAuth client_id' })
|
||||
@ApiQuery({ name: 'redirectUri', description: 'redirect_uri' })
|
||||
@ApiQuery({ name: 'scope', description: 'Scopes через пробел' })
|
||||
@ApiResponse({ status: 200, description: 'Authorization code создан' })
|
||||
authorize(@Query() query: OAuthAuthorizeQueryDto) {
|
||||
return this.core.oauth.Authorize(query);
|
||||
}
|
||||
|
||||
@Post('token')
|
||||
@ApiOperation({ summary: 'Выдать OAuth токены', description: 'Поддерживает grant_type=authorization_code и grant_type=refresh_token.' })
|
||||
@ApiBody({ type: OAuthTokenDto })
|
||||
@ApiResponse({ status: 201, description: 'OAuth токены выданы' })
|
||||
token(@Body() dto: OAuthTokenDto) {
|
||||
return this.core.oauth.Token(dto);
|
||||
}
|
||||
|
||||
@Get('userinfo')
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'OAuth userinfo', description: 'Возвращает профиль пользователя по OAuth access token.' })
|
||||
@ApiResponse({ status: 200, description: 'Профиль пользователя получен' })
|
||||
userInfo(@Headers('authorization') authorization?: string) {
|
||||
return this.core.oauth.UserInfo({ accessToken: extractBearerToken(authorization) });
|
||||
}
|
||||
}
|
||||
26
apps/api-gateway/src/controllers/otp.controller.ts
Normal file
26
apps/api-gateway/src/controllers/otp.controller.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { SendOtpDto, VerifyOtpDto } from '../dto/identity.dto';
|
||||
|
||||
@ApiTags('OTP и 2FA')
|
||||
@Controller('auth/otp')
|
||||
export class OtpController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Post('send')
|
||||
@ApiOperation({ summary: 'Отправить OTP код', description: 'Создает одноразовый код в AuthCode. Fallback-доставка пишет код в console.log.' })
|
||||
@ApiBody({ type: SendOtpDto })
|
||||
@ApiResponse({ status: 201, description: 'Код создан и отправлен' })
|
||||
send(@Body() dto: SendOtpDto) {
|
||||
return this.core.otp.SendOtp(dto);
|
||||
}
|
||||
|
||||
@Post('verify')
|
||||
@ApiOperation({ summary: 'Проверить OTP код', description: 'Проверяет одноразовый код, срок жизни и помечает его использованным.' })
|
||||
@ApiBody({ type: VerifyOtpDto })
|
||||
@ApiResponse({ status: 201, description: 'Код подтвержден' })
|
||||
verify(@Body() dto: VerifyOtpDto) {
|
||||
return this.core.otp.VerifyOtp(dto);
|
||||
}
|
||||
}
|
||||
83
apps/api-gateway/src/controllers/profile.controller.ts
Normal file
83
apps/api-gateway/src/controllers/profile.controller.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { Body, Controller, ForbiddenException, Get, Headers, Param, Patch, Post } from '@nestjs/common';
|
||||
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
|
||||
import { getAuthorizedUserId } from '../document-access';
|
||||
|
||||
import { SetPasswordDto, UpdateAvatarDto, UpdateContactsDto, UpdateProfileDto } from '../dto/profile.dto';
|
||||
|
||||
|
||||
|
||||
@ApiTags('Профиль и биометрия')
|
||||
|
||||
@ApiBearerAuth()
|
||||
|
||||
@Controller('profile/users/:userId')
|
||||
|
||||
export class ProfileController {
|
||||
|
||||
constructor(
|
||||
|
||||
private readonly core: CoreGrpcService,
|
||||
|
||||
private readonly jwt: JwtService
|
||||
|
||||
) {}
|
||||
|
||||
|
||||
|
||||
private async assertSelfAccess(authorization: string | undefined, userId: string) {
|
||||
|
||||
const requesterId = await getAuthorizedUserId(this.jwt, this.core, authorization);
|
||||
|
||||
if (requesterId !== userId) {
|
||||
|
||||
throw new ForbiddenException('Можно изменять только свой профиль');
|
||||
|
||||
}
|
||||
|
||||
return requesterId;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Get()
|
||||
|
||||
@ApiOperation({ summary: 'Получить профиль пользователя', description: 'Возвращает публичный профиль, аватар и основные/резервные контакты пользователя.' })
|
||||
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
|
||||
@ApiResponse({ status: 200, description: 'Профиль пользователя успешно получен' })
|
||||
|
||||
@ApiResponse({ status: 404, description: 'Пользователь не найден' })
|
||||
|
||||
getProfile(@Param('userId') userId: string) {
|
||||
|
||||
return this.core.profile.GetProfile({ userId });
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Patch('avatar')
|
||||
|
||||
@ApiOperation({ summary: 'Обновить аватар', description: 'Сохраняет URL или ключ объекта MinIO как аватар пользователя.' })
|
||||
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
|
||||
@ApiBody({ type: UpdateAvatarDto })
|
||||
|
||||
@ApiResponse({ status: 200, description: 'Аватар обновлен' })
|
||||
|
||||
updateAvatar(@Param('userId') userId: string, @Body() dto: UpdateAvatarDto) {
|
||||
|
||||
return this.core.profile.UpdateAvatar({ userId, avatarUrl: dto.avatarUrl, avatarStorageKey: dto.avatarStorageKey });
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { map } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
|
||||
@ApiTags('Публичные настройки')
|
||||
@Controller('settings')
|
||||
export class PublicSettingsController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Get('public')
|
||||
@ApiOperation({ summary: 'Публичные настройки', description: 'Возвращает несекретные настройки для интерфейса без авторизации.' })
|
||||
listPublic() {
|
||||
return this.core.settings.ListPublicSettings({}).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { settings?: Array<{ key: string; value: string }> };
|
||||
return { settings: payload.settings ?? [] };
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
103
apps/api-gateway/src/controllers/rbac.controller.ts
Normal file
103
apps/api-gateway/src/controllers/rbac.controller.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
|
||||
import { map } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { CurrentAdmin } from '../decorators/current-admin.decorator';
|
||||
import { AssignUserRoleDto, CreateOAuthClientDto, CreateRoleDto, UpdateOAuthClientDto } from '../dto/rbac.dto';
|
||||
import { AdminGuard, AdminRequestUser, assertAdminPermission, SuperAdminGuard } from '../guards/admin.guard';
|
||||
|
||||
@ApiTags('RBAC и OAuth')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminGuard)
|
||||
@Controller('admin/rbac')
|
||||
export class RbacController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Get('roles')
|
||||
@ApiOperation({ summary: 'Список ролей', description: 'Возвращает роли вместе с назначенными правами.' })
|
||||
listRoles() {
|
||||
return this.core.rbac.ListRoles({}).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { roles?: Array<{ permissions?: unknown[] }> };
|
||||
return {
|
||||
roles: (payload.roles ?? []).map((role) => ({
|
||||
...role,
|
||||
permissions: role.permissions ?? []
|
||||
}))
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get('permissions')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@ApiOperation({ summary: 'Список прав', description: 'Возвращает все доступные permissions.' })
|
||||
listPermissions() {
|
||||
return this.core.rbac.ListPermissions({});
|
||||
}
|
||||
|
||||
@Get('oauth-scopes')
|
||||
@ApiOperation({ summary: 'OAuth scopes', description: 'Возвращает доступные scopes для OAuth-приложений.' })
|
||||
listOAuthScopes(@CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageOAuth');
|
||||
return this.core.rbac.ListOAuthScopes({});
|
||||
}
|
||||
|
||||
@Get('oauth-clients')
|
||||
@ApiOperation({ summary: 'OAuth приложения', description: 'Возвращает OAuth-клиенты и доступные scopes.' })
|
||||
listOAuthClients(@CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageOAuth');
|
||||
return this.core.rbac.ListOAuthClients({});
|
||||
}
|
||||
|
||||
@Post('roles')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@ApiOperation({ summary: 'Создать роль', description: 'Создаёт новую роль с набором прав. Только супер-администратор.' })
|
||||
@ApiBody({ type: CreateRoleDto })
|
||||
createRole(@Body() dto: CreateRoleDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
return this.core.rbac.CreateRole({ actorUserId: admin.id, ...dto });
|
||||
}
|
||||
|
||||
@Post('users/:userId/roles')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@ApiOperation({ summary: 'Назначить роль пользователю', description: 'Только супер-администратор может назначать роли.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: AssignUserRoleDto })
|
||||
assignRole(@Param('userId') userId: string, @Body() dto: AssignUserRoleDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
return this.core.rbac.AssignUserRole({ actorUserId: admin.id, userId, roleSlug: dto.roleSlug });
|
||||
}
|
||||
|
||||
@Delete('users/:userId/roles/:roleSlug')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@ApiOperation({ summary: 'Снять роль с пользователя', description: 'Только супер-администратор может снимать роли.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'roleSlug', description: 'Slug роли' })
|
||||
removeRole(@Param('userId') userId: string, @Param('roleSlug') roleSlug: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
return this.core.rbac.RemoveUserRole({ actorUserId: admin.id, userId, roleSlug });
|
||||
}
|
||||
|
||||
@Post('oauth-clients')
|
||||
@ApiOperation({ summary: 'Создать OAuth-приложение', description: 'Создаёт OAuth2-клиент и возвращает client secret один раз.' })
|
||||
@ApiBody({ type: CreateOAuthClientDto })
|
||||
createOAuthClient(@Body() dto: CreateOAuthClientDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageOAuth');
|
||||
return this.core.rbac.CreateOAuthClient({ actorUserId: admin.id, ...dto });
|
||||
}
|
||||
|
||||
@Patch('oauth-clients/:clientId')
|
||||
@ApiOperation({ summary: 'Обновить OAuth-приложение', description: 'Изменяет redirect URI, scopes и статус приложения.' })
|
||||
@ApiParam({ name: 'clientId', description: 'Client ID приложения' })
|
||||
@ApiBody({ type: UpdateOAuthClientDto })
|
||||
updateOAuthClient(@Param('clientId') clientId: string, @Body() dto: UpdateOAuthClientDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageOAuth');
|
||||
return this.core.rbac.UpdateOAuthClient({ actorUserId: admin.id, clientId, ...dto });
|
||||
}
|
||||
|
||||
@Post('oauth-clients/:clientId/rotate-secret')
|
||||
@ApiOperation({ summary: 'Перевыпустить client secret', description: 'Генерирует новый secret для confidential-клиента.' })
|
||||
@ApiParam({ name: 'clientId', description: 'Client ID приложения' })
|
||||
rotateSecret(@Param('clientId') clientId: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageOAuth');
|
||||
return this.core.rbac.RotateOAuthSecret({ actorUserId: admin.id, clientId });
|
||||
}
|
||||
}
|
||||
111
apps/api-gateway/src/controllers/security.controller.ts
Normal file
111
apps/api-gateway/src/controllers/security.controller.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { OptionalPinDto, PinDto, VerifySecurityPinDto } from '../dto/security.dto';
|
||||
|
||||
@ApiTags('Безопасность')
|
||||
@ApiBearerAuth()
|
||||
@Controller('security')
|
||||
export class SecurityController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Get('users/:userId/devices')
|
||||
@ApiOperation({ summary: 'Активные устройства', description: 'Показывает устройства пользователя и связанные активные сессии.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiResponse({ status: 200, description: 'Список устройств получен' })
|
||||
listDevices(@Param('userId') userId: string) {
|
||||
return this.core.security.ListActiveDevices({ userId });
|
||||
}
|
||||
|
||||
@Get('users/:userId/sessions')
|
||||
@ApiOperation({ summary: 'Активные сессии', description: 'Возвращает ACTIVE и LOCKED сессии пользователя для управления устройствами.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiResponse({ status: 200, description: 'Список активных сессий получен' })
|
||||
listSessions(@Param('userId') userId: string) {
|
||||
return this.core.security.ListActiveSessions({ userId });
|
||||
}
|
||||
|
||||
@Get('users/:userId/sign-in-history')
|
||||
@ApiOperation({ summary: 'История входов', description: 'Показывает последние попытки входа и причины отказов.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiResponse({ status: 200, description: 'История входов получена' })
|
||||
listHistory(@Param('userId') userId: string) {
|
||||
return this.core.security.ListSignInHistory({ userId });
|
||||
}
|
||||
|
||||
@Post('users/:userId/pin/setup')
|
||||
@ApiOperation({ summary: 'Настроить PIN-код', description: 'Создает или включает PIN-код пользователя. PIN хранится только в виде bcrypt hash.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: PinDto })
|
||||
@ApiResponse({ status: 201, description: 'PIN-код настроен' })
|
||||
setupPin(@Param('userId') userId: string, @Body() dto: PinDto) {
|
||||
return this.core.security.SetupPin({ userId, pin: dto.pin });
|
||||
}
|
||||
|
||||
@Post('users/:userId/pin/update')
|
||||
@ApiOperation({ summary: 'Обновить PIN-код', description: 'Меняет PIN-код и переводит активные сессии пользователя в LOCKED до повторной проверки.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: PinDto })
|
||||
@ApiResponse({ status: 201, description: 'PIN-код обновлен' })
|
||||
updatePin(@Param('userId') userId: string, @Body() dto: PinDto) {
|
||||
return this.core.security.UpdatePin({ userId, pin: dto.pin });
|
||||
}
|
||||
|
||||
@Post('users/:userId/pin/delete-request')
|
||||
@ApiOperation({ summary: 'Запросить удаление PIN-кода', description: 'Запускает период ожидания перед отключением PIN-кода согласно SystemSetting.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: OptionalPinDto })
|
||||
requestPinDeletion(@Param('userId') userId: string, @Body() dto: OptionalPinDto) {
|
||||
return this.core.security.RequestPinDeletion({ userId, pin: dto.pin ?? '' });
|
||||
}
|
||||
|
||||
@Post('users/:userId/pin/delete-cancel')
|
||||
@ApiOperation({ summary: 'Отменить удаление PIN-кода', description: 'Отменяет запланированное удаление PIN-кода.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
cancelPinDeletion(@Param('userId') userId: string) {
|
||||
return this.core.security.CancelPinDeletion({ userId });
|
||||
}
|
||||
|
||||
@Post('pin/verify')
|
||||
@ApiOperation({ summary: 'Проверить PIN-код', description: 'Проверяет PIN-код и возвращает access token с pinVerified=true для указанной сессии.' })
|
||||
@ApiBody({ type: VerifySecurityPinDto })
|
||||
@ApiResponse({ status: 201, description: 'PIN-код проверен' })
|
||||
verifyPin(@Body() dto: VerifySecurityPinDto) {
|
||||
return this.core.security.VerifyPinCode(dto);
|
||||
}
|
||||
|
||||
@Post('users/:userId/sessions/:sessionId/lock')
|
||||
@ApiOperation({ summary: 'Заблокировать сессию', description: 'Переводит активную сессию в LOCKED и сбрасывает pinVerified=false.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'sessionId', description: 'ID сессии' })
|
||||
@ApiResponse({ status: 201, description: 'Сессия заблокирована' })
|
||||
lockSession(@Param('userId') userId: string, @Param('sessionId') sessionId: string) {
|
||||
return this.core.security.LockSession({ userId, sessionId });
|
||||
}
|
||||
|
||||
@Post('users/:userId/sessions/:sessionId/revoke')
|
||||
@ApiOperation({ summary: 'Выйти с устройства', description: 'Отзывает конкретную сессию пользователя и завершает доступ с выбранного устройства.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'sessionId', description: 'ID сессии' })
|
||||
@ApiResponse({ status: 201, description: 'Сессия отозвана' })
|
||||
revokeSession(@Param('userId') userId: string, @Param('sessionId') sessionId: string) {
|
||||
return this.core.security.RevokeSession({ userId, sessionId });
|
||||
}
|
||||
|
||||
@Post('users/:userId/devices/:deviceId/revoke')
|
||||
@ApiOperation({ summary: 'Завершить сессии устройства', description: 'Отзывает все активные сессии выбранного устройства пользователя.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'deviceId', description: 'ID устройства' })
|
||||
@ApiResponse({ status: 201, description: 'Сессии устройства завершены' })
|
||||
revokeDevice(@Param('userId') userId: string, @Param('deviceId') deviceId: string) {
|
||||
return this.core.security.RevokeDevice({ userId, deviceId });
|
||||
}
|
||||
|
||||
@Post('users/:userId/revoke-all-sessions')
|
||||
@ApiOperation({ summary: 'Выйти везде', description: 'Отзывает все активные и PIN-заблокированные сессии пользователя.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiResponse({ status: 201, description: 'Все сессии отозваны' })
|
||||
revokeAll(@Param('userId') userId: string) {
|
||||
return this.core.security.RevokeAllSessions({ userId });
|
||||
}
|
||||
}
|
||||
125
apps/api-gateway/src/controllers/settings.controller.ts
Normal file
125
apps/api-gateway/src/controllers/settings.controller.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { Body, Controller, Delete, Get, Param, Put, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { map } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { CurrentAdmin } from '../decorators/current-admin.decorator';
|
||||
import { ConnectLinkedAccountDto, UpsertSettingDto, UpsertSocialProviderDto } from '../dto/settings.dto';
|
||||
import { AdminGuard, AdminRequestUser, assertAdminPermission } from '../guards/admin.guard';
|
||||
|
||||
const settingsWritePipe = new ValidationPipe({
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
forbidNonWhitelisted: false
|
||||
});
|
||||
|
||||
@ApiTags('Глобальные настройки')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminGuard)
|
||||
@Controller('admin/settings')
|
||||
export class SettingsController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Список системных настроек', description: 'Возвращает динамические настройки, включая PIN timeout и OAuth providers.' })
|
||||
@ApiResponse({ status: 200, description: 'Список настроек получен' })
|
||||
list(@CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageSettings');
|
||||
return this.core.settings.ListSettings({}).pipe(
|
||||
map((response) => {
|
||||
const payload = response as { settings?: unknown[] };
|
||||
return { settings: payload.settings ?? [] };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Get('key/:key')
|
||||
@ApiOperation({ summary: 'Получить настройку', description: 'Возвращает SystemSetting по ключу.' })
|
||||
@ApiParam({ name: 'key', description: 'Ключ настройки', example: 'PIN_LOCK_TIMEOUT_MINUTES' })
|
||||
@ApiResponse({ status: 200, description: 'Настройка получена' })
|
||||
get(@Param('key') key: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageSettings');
|
||||
return this.core.settings.GetSetting({ key });
|
||||
}
|
||||
|
||||
@Put()
|
||||
@UsePipes(settingsWritePipe)
|
||||
@ApiOperation({ summary: 'Создать или обновить настройку', description: 'Меняет значение SystemSetting без изменения кода frontend.' })
|
||||
@ApiBody({ type: UpsertSettingDto })
|
||||
@ApiResponse({ status: 200, description: 'Настройка создана или обновлена' })
|
||||
upsert(@Body() dto: UpsertSettingDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageSettings');
|
||||
return this.core.settings.UpsertSetting({
|
||||
key: dto.key,
|
||||
value: dto.value,
|
||||
description: dto.description,
|
||||
isSecret: dto.isSecret
|
||||
});
|
||||
}
|
||||
|
||||
@Delete('key/:key')
|
||||
@ApiOperation({ summary: 'Удалить настройку', description: 'Удаляет SystemSetting по ключу.' })
|
||||
@ApiParam({ name: 'key', description: 'Ключ настройки' })
|
||||
@ApiResponse({ status: 200, description: 'Настройка удалена' })
|
||||
delete(@Param('key') key: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageSettings');
|
||||
return this.core.settings.DeleteSetting({ key });
|
||||
}
|
||||
|
||||
@Get('oauth/providers')
|
||||
@ApiOperation({ summary: 'Список OAuth провайдеров', description: 'Возвращает глобальные настройки Google/Yandex и других social login providers.' })
|
||||
@ApiResponse({ status: 200, description: 'Список провайдеров получен' })
|
||||
listProviders(@CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageSettings');
|
||||
return this.core.settings.ListSocialProviders({});
|
||||
}
|
||||
|
||||
@Put('oauth/providers')
|
||||
@UsePipes(settingsWritePipe)
|
||||
@ApiOperation({ summary: 'Создать или обновить OAuth провайдера', description: 'Управляет clientId/clientSecret и глобальным включением Google/Yandex входа.' })
|
||||
@ApiBody({ type: UpsertSocialProviderDto })
|
||||
@ApiResponse({ status: 200, description: 'Провайдер создан или обновлен' })
|
||||
upsertProvider(@Body() dto: UpsertSocialProviderDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageSettings');
|
||||
return this.core.settings.UpsertSocialProvider({
|
||||
providerName: dto.providerName,
|
||||
clientId: dto.clientId,
|
||||
clientSecret: dto.clientSecret,
|
||||
isEnabled: dto.isEnabled
|
||||
});
|
||||
}
|
||||
|
||||
@Delete('oauth/providers/:providerName')
|
||||
@ApiOperation({ summary: 'Удалить OAuth провайдера', description: 'Удаляет глобальную настройку social login provider.' })
|
||||
@ApiParam({ name: 'providerName', description: 'Название провайдера', example: 'google' })
|
||||
@ApiResponse({ status: 200, description: 'Провайдер удален' })
|
||||
deleteProvider(@Param('providerName') providerName: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
assertAdminPermission(admin, 'canManageSettings');
|
||||
return this.core.settings.DeleteSocialProvider({ providerName });
|
||||
}
|
||||
|
||||
@Get('linked-accounts/users/:userId')
|
||||
@ApiOperation({ summary: 'Связанные внешние аккаунты', description: 'Возвращает LinkedAccount записи пользователя для Google/Yandex и других провайдеров.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiResponse({ status: 200, description: 'Список внешних аккаунтов получен' })
|
||||
listLinkedAccounts(@Param('userId') userId: string) {
|
||||
return this.core.security.ListLinkedAccounts({ userId });
|
||||
}
|
||||
|
||||
@Put('linked-accounts/users/:userId')
|
||||
@ApiOperation({ summary: 'Подключить внешний аккаунт', description: 'Создает или обновляет LinkedAccount для social OAuth логина пользователя.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiBody({ type: ConnectLinkedAccountDto })
|
||||
@ApiResponse({ status: 200, description: 'Внешний аккаунт подключен' })
|
||||
connectLinkedAccount(@Param('userId') userId: string, @Body() dto: ConnectLinkedAccountDto) {
|
||||
return this.core.security.ConnectLinkedAccount({ userId, ...dto });
|
||||
}
|
||||
|
||||
@Delete('linked-accounts/users/:userId/:providerName')
|
||||
@ApiOperation({ summary: 'Отключить внешний аккаунт', description: 'Удаляет связь пользователя с Google/Yandex или другим social provider.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@ApiParam({ name: 'providerName', description: 'Название провайдера', example: 'google' })
|
||||
@ApiResponse({ status: 200, description: 'Внешний аккаунт отключен' })
|
||||
disconnectLinkedAccount(@Param('userId') userId: string, @Param('providerName') providerName: string) {
|
||||
return this.core.security.DisconnectLinkedAccount({ userId, providerName });
|
||||
}
|
||||
}
|
||||
44
apps/api-gateway/src/core-grpc.service.ts
Normal file
44
apps/api-gateway/src/core-grpc.service.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
type GrpcMethod<TRequest = unknown, TResponse = unknown> = (request: TRequest) => Observable<TResponse>;
|
||||
|
||||
@Injectable()
|
||||
export class CoreGrpcService implements OnModuleInit {
|
||||
auth!: Record<string, GrpcMethod>;
|
||||
admin!: Record<string, GrpcMethod>;
|
||||
rbac!: Record<string, GrpcMethod>;
|
||||
security!: Record<string, GrpcMethod>;
|
||||
settings!: Record<string, GrpcMethod>;
|
||||
profile!: Record<string, GrpcMethod>;
|
||||
documents!: Record<string, GrpcMethod>;
|
||||
addresses!: Record<string, GrpcMethod>;
|
||||
oauth!: Record<string, GrpcMethod>;
|
||||
otp!: Record<string, GrpcMethod>;
|
||||
advancedAuth!: Record<string, GrpcMethod>;
|
||||
notifications!: Record<string, GrpcMethod>;
|
||||
chat!: Record<string, GrpcMethod>;
|
||||
family!: Record<string, GrpcMethod>;
|
||||
media!: Record<string, GrpcMethod>;
|
||||
|
||||
constructor(@Inject('SSO_CORE') private readonly client: ClientGrpc) {}
|
||||
|
||||
onModuleInit() {
|
||||
this.auth = this.client.getService<Record<string, GrpcMethod>>('AuthService');
|
||||
this.admin = this.client.getService<Record<string, GrpcMethod>>('AdminService');
|
||||
this.rbac = this.client.getService<Record<string, GrpcMethod>>('RbacService');
|
||||
this.security = this.client.getService<Record<string, GrpcMethod>>('SecurityService');
|
||||
this.settings = this.client.getService<Record<string, GrpcMethod>>('SettingsService');
|
||||
this.profile = this.client.getService<Record<string, GrpcMethod>>('ProfileService');
|
||||
this.documents = this.client.getService<Record<string, GrpcMethod>>('DocumentsService');
|
||||
this.addresses = this.client.getService<Record<string, GrpcMethod>>('AddressesService');
|
||||
this.oauth = this.client.getService<Record<string, GrpcMethod>>('OAuthCoreService');
|
||||
this.otp = this.client.getService<Record<string, GrpcMethod>>('OtpService');
|
||||
this.advancedAuth = this.client.getService<Record<string, GrpcMethod>>('AdvancedAuthService');
|
||||
this.family = this.client.getService<Record<string, GrpcMethod>>('FamilyService');
|
||||
this.notifications = this.client.getService<Record<string, GrpcMethod>>('NotificationsService');
|
||||
this.chat = this.client.getService<Record<string, GrpcMethod>>('ChatService');
|
||||
this.media = this.client.getService<Record<string, GrpcMethod>>('MediaService');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { AdminRequestUser } from '../guards/admin.guard';
|
||||
|
||||
export const CurrentAdmin = createParamDecorator((_data: unknown, context: ExecutionContext): AdminRequestUser => {
|
||||
const request = context.switchToHttp().getRequest<{ adminUser: AdminRequestUser }>();
|
||||
return request.adminUser;
|
||||
});
|
||||
52
apps/api-gateway/src/document-access.ts
Normal file
52
apps/api-gateway/src/document-access.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { ForbiddenException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { CoreGrpcService } from './core-grpc.service';
|
||||
import { assertSessionUnlocked, verifyAccessToken } from './session-auth';
|
||||
|
||||
interface RequesterProfile {
|
||||
id: string;
|
||||
isSuperAdmin: boolean;
|
||||
canViewUserDocuments?: boolean;
|
||||
}
|
||||
|
||||
async function getRequesterProfile(jwt: JwtService, core: CoreGrpcService, authorization?: string): Promise<RequesterProfile> {
|
||||
const payload = await verifyAccessToken(jwt, authorization);
|
||||
await assertSessionUnlocked(core, payload);
|
||||
const profile = (await firstValueFrom(core.auth.GetMe({ userId: payload.sub }))) as RequesterProfile & { id: string };
|
||||
return { id: profile.id, isSuperAdmin: profile.isSuperAdmin, canViewUserDocuments: profile.canViewUserDocuments };
|
||||
}
|
||||
|
||||
export async function assertDocumentsReadAccess(
|
||||
jwt: JwtService,
|
||||
core: CoreGrpcService,
|
||||
authorization: string | undefined,
|
||||
targetUserId: string
|
||||
) {
|
||||
const requester = await getRequesterProfile(jwt, core, authorization);
|
||||
if (requester.id === targetUserId) {
|
||||
return requester.id;
|
||||
}
|
||||
if (!requester.canViewUserDocuments && !requester.isSuperAdmin) {
|
||||
throw new ForbiddenException('Нет доступа к документам пользователя');
|
||||
}
|
||||
return requester.id;
|
||||
}
|
||||
|
||||
export async function assertDocumentsWriteAccess(
|
||||
jwt: JwtService,
|
||||
core: CoreGrpcService,
|
||||
authorization: string | undefined,
|
||||
targetUserId: string
|
||||
) {
|
||||
const requester = await getRequesterProfile(jwt, core, authorization);
|
||||
if (requester.id !== targetUserId) {
|
||||
throw new ForbiddenException('Нельзя изменять документы другого пользователя');
|
||||
}
|
||||
return requester.id;
|
||||
}
|
||||
|
||||
export async function getAuthorizedUserId(jwt: JwtService, core: CoreGrpcService, authorization?: string) {
|
||||
const requester = await getRequesterProfile(jwt, core, authorization);
|
||||
return requester.id;
|
||||
}
|
||||
53
apps/api-gateway/src/dto/addresses.dto.ts
Normal file
53
apps/api-gateway/src/dto/addresses.dto.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { IsIn, IsNumber, IsOptional, IsString, IsUUID, MinLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpsertAddressDto {
|
||||
@ApiPropertyOptional({ description: 'ID адреса для обновления' })
|
||||
@IsOptional()
|
||||
@IsUUID('4', { message: 'ID адреса должен быть UUID' })
|
||||
addressId?: string;
|
||||
|
||||
@ApiProperty({ description: 'Тип адреса', enum: ['HOME', 'WORK', 'OTHER'] })
|
||||
@IsIn(['HOME', 'WORK', 'OTHER'], { message: 'Некорректный тип адреса' })
|
||||
label!: 'HOME' | 'WORK' | 'OTHER';
|
||||
|
||||
@ApiProperty({ description: 'Город' })
|
||||
@IsString({ message: 'Город должен быть строкой' })
|
||||
@MinLength(1, { message: 'Укажите город' })
|
||||
city!: string;
|
||||
|
||||
@ApiProperty({ description: 'Улица' })
|
||||
@IsString({ message: 'Улица должна быть строкой' })
|
||||
@MinLength(1, { message: 'Укажите улицу' })
|
||||
street!: string;
|
||||
|
||||
@ApiProperty({ description: 'Дом' })
|
||||
@IsString({ message: 'Дом должен быть строкой' })
|
||||
@MinLength(1, { message: 'Укажите дом' })
|
||||
house!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Квартира или офис' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Квартира должна быть строкой' })
|
||||
apartment?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Комментарий' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Комментарий должен быть строкой' })
|
||||
comment?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Широта' })
|
||||
@IsOptional()
|
||||
@IsNumber({}, { message: 'Широта должна быть числом' })
|
||||
latitude?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Долгота' })
|
||||
@IsOptional()
|
||||
@IsNumber({}, { message: 'Долгота должна быть числом' })
|
||||
longitude?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Полный адрес одной строкой' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Полный адрес должен быть строкой' })
|
||||
fullAddress?: string;
|
||||
}
|
||||
60
apps/api-gateway/src/dto/admin.dto.ts
Normal file
60
apps/api-gateway/src/dto/admin.dto.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsBoolean, IsEmail, IsEnum, IsOptional, IsString, Matches, MinLength } from 'class-validator';
|
||||
|
||||
export enum GatewayUserStatus {
|
||||
ACTIVE = 'ACTIVE',
|
||||
SUSPENDED = 'SUSPENDED',
|
||||
DELETED = 'DELETED'
|
||||
}
|
||||
|
||||
export class ListUsersQueryDto {
|
||||
@ApiPropertyOptional({ description: 'Поиск по почте, телефону, имени или логину' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Поисковая строка должна быть текстом' })
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export class UpdateUserDto {
|
||||
@ApiPropertyOptional({ description: 'Отображаемое имя' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Имя должно быть строкой' })
|
||||
displayName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Основная почта' })
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'Укажите корректную почту' })
|
||||
email?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Основной телефон' })
|
||||
@IsOptional()
|
||||
@Matches(/^\+?[1-9]\d{7,14}$/, { message: 'Укажите корректный телефон' })
|
||||
phone?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Резервная почта' })
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'Укажите корректную резервную почту' })
|
||||
backupEmail?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Резервный телефон' })
|
||||
@IsOptional()
|
||||
@Matches(/^\+?[1-9]\d{7,14}$/, { message: 'Укажите корректный резервный телефон' })
|
||||
backupPhone?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Статус пользователя', enum: GatewayUserStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(GatewayUserStatus, { message: 'Укажите корректный статус пользователя' })
|
||||
status?: GatewayUserStatus;
|
||||
}
|
||||
|
||||
export class ResetPasswordDto {
|
||||
@ApiProperty({ description: 'Новый пароль пользователя', minLength: 8 })
|
||||
@IsString({ message: 'Пароль должен быть строкой' })
|
||||
@MinLength(8, { message: 'Пароль должен содержать минимум 8 символов' })
|
||||
newPassword!: string;
|
||||
}
|
||||
|
||||
export class SetSuperAdminDto {
|
||||
@ApiProperty({ description: 'Выдать или снять права супер-администратора' })
|
||||
@IsBoolean({ message: 'isSuperAdmin должно быть boolean' })
|
||||
isSuperAdmin!: boolean;
|
||||
}
|
||||
189
apps/api-gateway/src/dto/auth.dto.ts
Normal file
189
apps/api-gateway/src/dto/auth.dto.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsEmail, IsNotEmpty, IsOptional, IsString, Length, Matches, MinLength } from 'class-validator';
|
||||
|
||||
const EMAIL_OR_PHONE_PATTERN = /^([^\s@]+@[^\s@]+\.[^\s@]+|\+?[1-9]\d{9,14})$/;
|
||||
|
||||
export class RegisterDto {
|
||||
@ApiPropertyOptional({ description: 'Основная почта пользователя', example: 'user@example.com' })
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'Укажите корректную почту' })
|
||||
email?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Основной телефон пользователя', example: '+79990000000' })
|
||||
@IsOptional()
|
||||
@Matches(/^\+?[1-9]\d{7,14}$/, { message: 'Укажите корректный номер телефона' })
|
||||
phone?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Пароль пользователя. Не требуется для passwordless-регистрации.', minLength: 8 })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Пароль должен быть строкой' })
|
||||
@MinLength(8, { message: 'Пароль должен содержать минимум 8 символов' })
|
||||
password?: string;
|
||||
|
||||
@ApiProperty({ description: 'Имя, которое отображается в профиле', example: 'Иван Петров' })
|
||||
@IsString({ message: 'Имя должно быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите имя профиля' })
|
||||
displayName!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Публичный логин пользователя', example: 'ivan' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Логин должен быть строкой' })
|
||||
username?: string;
|
||||
}
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ description: 'Почта, телефон или логин', example: 'user@example.com' })
|
||||
@IsString({ message: 'Логин должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите логин' })
|
||||
login!: string;
|
||||
|
||||
@ApiProperty({ description: 'Пароль пользователя' })
|
||||
@IsString({ message: 'Пароль должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите пароль' })
|
||||
password!: string;
|
||||
|
||||
@ApiProperty({ description: 'Уникальный отпечаток устройства' })
|
||||
@IsString({ message: 'Отпечаток устройства должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Передайте отпечаток устройства' })
|
||||
fingerprint!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Название устройства', example: 'Chrome на Windows' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Название устройства должно быть строкой' })
|
||||
deviceName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Тип устройства', example: 'WEB' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Тип устройства должен быть строкой' })
|
||||
deviceType?: string;
|
||||
}
|
||||
|
||||
export class IdentifyDto {
|
||||
@ApiProperty({ description: 'Почта или телефон пользователя', example: 'user@example.com' })
|
||||
@IsString({ message: 'Логин должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите почту или телефон' })
|
||||
@Matches(EMAIL_OR_PHONE_PATTERN, { message: 'Укажите корректную почту или телефон в формате +79991234567' })
|
||||
login!: string;
|
||||
}
|
||||
|
||||
export class PasswordlessOtpDto {
|
||||
@ApiProperty({ description: 'Почта или телефон для входа', example: 'user@example.com' })
|
||||
@IsString({ message: 'Получатель должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите почту или телефон' })
|
||||
@Matches(EMAIL_OR_PHONE_PATTERN, { message: 'Укажите корректную почту или телефон в формате +79991234567' })
|
||||
recipient!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Альтернативный канал доставки кода', enum: ['primary', 'email', 'phone', 'backupEmail', 'backupPhone'] })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Канал должен быть строкой' })
|
||||
channel?: string;
|
||||
}
|
||||
|
||||
export class PasswordlessVerifyDto {
|
||||
@ApiProperty({ description: 'Почта или телефон, на который отправлен код', example: 'user@example.com' })
|
||||
@IsString({ message: 'Получатель должен быть строкой' })
|
||||
@Matches(EMAIL_OR_PHONE_PATTERN, { message: 'Укажите корректную почту или телефон в формате +79991234567' })
|
||||
recipient!: string;
|
||||
|
||||
@ApiProperty({ description: 'OTP-код из 6 цифр', example: '123456' })
|
||||
@IsString({ message: 'Код должен быть строкой' })
|
||||
@Length(6, 6, { message: 'Код должен содержать 6 цифр' })
|
||||
@Matches(/^\d+$/, { message: 'Код должен содержать только цифры' })
|
||||
code!: string;
|
||||
|
||||
@ApiProperty({ description: 'Уникальный отпечаток устройства' })
|
||||
@IsString({ message: 'Отпечаток устройства должен быть строкой' })
|
||||
fingerprint!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Название устройства' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Название устройства должно быть строкой' })
|
||||
deviceName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Тип устройства', example: 'WEB' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Тип устройства должен быть строкой' })
|
||||
deviceType?: string;
|
||||
}
|
||||
|
||||
export class PasswordLoginDto {
|
||||
@ApiPropertyOptional({ description: 'Почта или телефон пользователя для identifier-first входа' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Логин должен быть строкой' })
|
||||
@Matches(EMAIL_OR_PHONE_PATTERN, { message: 'Укажите корректную почту или телефон в формате +79991234567' })
|
||||
login?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Временный auth_token после успешной OTP-проверки, если используется legacy challenge flow' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Временный токен должен быть строкой' })
|
||||
tempAuthToken?: string;
|
||||
|
||||
@ApiProperty({ description: 'Пароль пользователя' })
|
||||
@IsString({ message: 'Пароль должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите пароль' })
|
||||
password!: string;
|
||||
|
||||
@ApiProperty({ description: 'Уникальный отпечаток устройства' })
|
||||
@IsString({ message: 'Отпечаток устройства должен быть строкой' })
|
||||
fingerprint!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Название устройства' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Название устройства должно быть строкой' })
|
||||
deviceName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Тип устройства', example: 'WEB' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Тип устройства должен быть строкой' })
|
||||
deviceType?: string;
|
||||
}
|
||||
|
||||
export class VerifyPinDto {
|
||||
@ApiProperty({ description: 'ID временно заблокированной сессии' })
|
||||
@IsString({ message: 'ID сессии должен быть строкой' })
|
||||
sessionId!: string;
|
||||
|
||||
@ApiProperty({ description: 'PIN-код из 4-6 цифр', example: '1234' })
|
||||
@IsString({ message: 'PIN-код должен быть строкой' })
|
||||
@Length(4, 6, { message: 'PIN-код должен содержать от 4 до 6 символов' })
|
||||
@Matches(/^\d+$/, { message: 'PIN-код должен содержать только цифры' })
|
||||
pin!: string;
|
||||
}
|
||||
|
||||
export class RefreshSessionDto {
|
||||
@ApiProperty({ description: 'Refresh token текущей сессии' })
|
||||
@IsString({ message: 'Refresh token должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Передайте refresh token' })
|
||||
refreshToken!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'ID сессии для ускоренной проверки' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'ID сессии должен быть строкой' })
|
||||
sessionId?: string;
|
||||
}
|
||||
|
||||
export class LdapLoginDto {
|
||||
@ApiProperty({ description: 'Логин LDAP (sAMAccountName, uid, mail и т.д.)', example: 'ivan.petrov' })
|
||||
@IsString({ message: 'Логин должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите LDAP-логин' })
|
||||
username!: string;
|
||||
|
||||
@ApiProperty({ description: 'Пароль LDAP' })
|
||||
@IsString({ message: 'Пароль должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите пароль' })
|
||||
password!: string;
|
||||
|
||||
@ApiProperty({ description: 'Уникальный отпечаток устройства' })
|
||||
@IsString({ message: 'Отпечаток устройства должен быть строкой' })
|
||||
fingerprint!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Название устройства' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Название устройства должно быть строкой' })
|
||||
deviceName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Тип устройства', example: 'WEB' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Тип устройства должен быть строкой' })
|
||||
deviceType?: string;
|
||||
}
|
||||
68
apps/api-gateway/src/dto/chat.dto.ts
Normal file
68
apps/api-gateway/src/dto/chat.dto.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { IsArray, IsBoolean, IsIn, IsOptional, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class CreateChatRoomDto {
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
memberUserIds?: string[];
|
||||
}
|
||||
|
||||
export class UpdateChatRoomDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
notificationsMuted?: boolean;
|
||||
}
|
||||
|
||||
export class SendChatMessageDto {
|
||||
@IsString()
|
||||
@IsIn(['TEXT', 'IMAGE', 'AUDIO', 'VOICE', 'FILE', 'EMOJI', 'POLL'])
|
||||
type!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
content?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
replyToId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
storageKey?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
mimeType?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
metadataJson?: string;
|
||||
|
||||
@IsOptional()
|
||||
poll?: {
|
||||
question: string;
|
||||
options: string[];
|
||||
allowsMultiple?: boolean;
|
||||
isAnonymous?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export class VotePollDto {
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
optionIds!: string[];
|
||||
}
|
||||
|
||||
export class SetRoomNotificationsMutedDto {
|
||||
@IsBoolean()
|
||||
muted!: boolean;
|
||||
}
|
||||
62
apps/api-gateway/src/dto/documents.dto.ts
Normal file
62
apps/api-gateway/src/dto/documents.dto.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsDateString, IsEnum, IsJSON, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export enum DocumentTypeDto {
|
||||
PASSPORT_RF = 'PASSPORT_RF',
|
||||
FOREIGN_PASSPORT = 'FOREIGN_PASSPORT',
|
||||
BIRTH_CERTIFICATE = 'BIRTH_CERTIFICATE',
|
||||
DRIVER_LICENSE = 'DRIVER_LICENSE',
|
||||
VEHICLE_REGISTRATION = 'VEHICLE_REGISTRATION',
|
||||
OMS = 'OMS',
|
||||
DMS = 'DMS',
|
||||
INN = 'INN',
|
||||
SNILS = 'SNILS'
|
||||
}
|
||||
|
||||
export class CreateDocumentDto {
|
||||
@ApiProperty({ description: 'Тип документа', enum: DocumentTypeDto, example: DocumentTypeDto.PASSPORT_RF })
|
||||
@IsEnum(DocumentTypeDto, { message: 'Некорректный тип документа' })
|
||||
type!: DocumentTypeDto;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Номер документа. Перед сохранением будет зашифрован.', example: '4512 123456' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Номер документа должен быть строкой' })
|
||||
number?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Дата выдачи документа в ISO формате', example: '2020-01-10T00:00:00.000Z' })
|
||||
@IsOptional()
|
||||
@IsDateString({}, { message: 'Дата выдачи должна быть в ISO формате' })
|
||||
issuedAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Дата окончания действия документа в ISO формате', example: '2030-01-10T00:00:00.000Z' })
|
||||
@IsOptional()
|
||||
@IsDateString({}, { message: 'Дата окончания должна быть в ISO формате' })
|
||||
expiresAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Данные формы документа в JSON. Перед сохранением будут зашифрованы.' })
|
||||
@IsOptional()
|
||||
@IsJSON({ message: 'Дополнительные данные должны быть валидным JSON' })
|
||||
metadataJson?: string;
|
||||
}
|
||||
|
||||
export class UpdateDocumentDto {
|
||||
@ApiPropertyOptional({ description: 'Номер документа' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Номер документа должен быть строкой' })
|
||||
number?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Дата выдачи в ISO формате' })
|
||||
@IsOptional()
|
||||
@IsDateString({}, { message: 'Дата выдачи должна быть в ISO формате' })
|
||||
issuedAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Дата окончания в ISO формате' })
|
||||
@IsOptional()
|
||||
@IsDateString({}, { message: 'Дата окончания должна быть в ISO формате' })
|
||||
expiresAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Данные формы документа в JSON' })
|
||||
@IsOptional()
|
||||
@IsJSON({ message: 'Дополнительные данные должны быть валидным JSON' })
|
||||
metadataJson?: string;
|
||||
}
|
||||
140
apps/api-gateway/src/dto/identity.dto.ts
Normal file
140
apps/api-gateway/src/dto/identity.dto.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsBoolean, IsIn, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class OAuthAuthorizeQueryDto {
|
||||
@ApiProperty({ description: 'ID пользователя, который подтверждает OAuth доступ' })
|
||||
@IsString({ message: 'ID пользователя должен быть строкой' })
|
||||
userId!: string;
|
||||
|
||||
@ApiProperty({ description: 'OAuth client_id приложения' })
|
||||
@IsString({ message: 'client_id должен быть строкой' })
|
||||
clientId!: string;
|
||||
|
||||
@ApiProperty({ description: 'Разрешенный redirect_uri приложения' })
|
||||
@IsString({ message: 'redirect_uri должен быть строкой' })
|
||||
redirectUri!: string;
|
||||
|
||||
@ApiProperty({ description: 'Запрошенные scopes через пробел', example: 'openid profile email' })
|
||||
@IsString({ message: 'scope должен быть строкой' })
|
||||
scope!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'OAuth state для защиты клиента' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'state должен быть строкой' })
|
||||
state?: string;
|
||||
}
|
||||
|
||||
export class OAuthTokenDto {
|
||||
@ApiProperty({ description: 'Тип grant', enum: ['authorization_code', 'refresh_token'] })
|
||||
@IsIn(['authorization_code', 'refresh_token'], { message: 'grant_type должен быть authorization_code или refresh_token' })
|
||||
grantType!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Authorization code' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'code должен быть строкой' })
|
||||
code?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Refresh token' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'refresh_token должен быть строкой' })
|
||||
refreshToken?: string;
|
||||
|
||||
@ApiProperty({ description: 'OAuth client_id' })
|
||||
@IsString({ message: 'client_id должен быть строкой' })
|
||||
clientId!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'OAuth client_secret' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'client_secret должен быть строкой' })
|
||||
clientSecret?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'redirect_uri для authorization_code grant' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'redirect_uri должен быть строкой' })
|
||||
redirectUri?: string;
|
||||
}
|
||||
|
||||
export class SendOtpDto {
|
||||
@ApiProperty({ description: 'Почта или телефон получателя' })
|
||||
@IsString({ message: 'Получатель должен быть строкой' })
|
||||
target!: string;
|
||||
|
||||
@ApiProperty({ description: 'Канал доставки', enum: ['email', 'sms'] })
|
||||
@IsIn(['email', 'sms'], { message: 'Канал должен быть email или sms' })
|
||||
channel!: string;
|
||||
|
||||
@ApiProperty({ description: 'Назначение кода', example: 'login' })
|
||||
@IsString({ message: 'Назначение должно быть строкой' })
|
||||
purpose!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'ID пользователя, если код привязан к аккаунту' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'ID пользователя должен быть строкой' })
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export class VerifyOtpDto {
|
||||
@ApiProperty({ description: 'Почта или телефон получателя' })
|
||||
@IsString({ message: 'Получатель должен быть строкой' })
|
||||
target!: string;
|
||||
|
||||
@ApiProperty({ description: 'Код подтверждения' })
|
||||
@IsString({ message: 'Код должен быть строкой' })
|
||||
code!: string;
|
||||
|
||||
@ApiProperty({ description: 'Назначение кода', example: 'login' })
|
||||
@IsString({ message: 'Назначение должно быть строкой' })
|
||||
purpose!: string;
|
||||
}
|
||||
|
||||
export class WebAuthnDto {
|
||||
@ApiProperty({ description: 'ID пользователя' })
|
||||
@IsString({ message: 'ID пользователя должен быть строкой' })
|
||||
userId!: string;
|
||||
}
|
||||
|
||||
export class QrSessionDto {
|
||||
@ApiProperty({ description: 'Название устройства', example: 'Chrome на Windows' })
|
||||
@IsString({ message: 'Название устройства должно быть строкой' })
|
||||
deviceName!: string;
|
||||
}
|
||||
|
||||
export class CreateFamilyGroupDto {
|
||||
@ApiProperty({ description: 'ID владельца семьи' })
|
||||
@IsString({ message: 'ID владельца должен быть строкой' })
|
||||
ownerId!: string;
|
||||
|
||||
@ApiProperty({ description: 'Название семейной группы', example: 'Семья Мамедовых' })
|
||||
@IsString({ message: 'Название семьи должно быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите название семьи' })
|
||||
name!: string;
|
||||
}
|
||||
|
||||
export class UpdateFamilyGroupDto {
|
||||
@ApiProperty({ description: 'Новое название семейной группы' })
|
||||
@IsString({ message: 'Название семьи должно быть строкой' })
|
||||
name!: string;
|
||||
}
|
||||
|
||||
export class AddFamilyMemberDto {
|
||||
@ApiProperty({ description: 'ID пользователя, которого нужно добавить' })
|
||||
@IsString({ message: 'ID пользователя должен быть строкой' })
|
||||
userId!: string;
|
||||
|
||||
@ApiProperty({ description: 'Роль участника семьи', example: 'member' })
|
||||
@IsString({ message: 'Роль должна быть строкой' })
|
||||
role!: string;
|
||||
}
|
||||
|
||||
export class SendFamilyInviteDto {
|
||||
@ApiProperty({ description: 'Email, телефон или логин приглашаемого' })
|
||||
@IsString({ message: 'Укажите контакт приглашаемого' })
|
||||
@IsNotEmpty({ message: 'Укажите контакт приглашаемого' })
|
||||
target!: string;
|
||||
}
|
||||
|
||||
export class RespondFamilyInviteDto {
|
||||
@ApiProperty({ description: 'Принять приглашение' })
|
||||
@IsBoolean({ message: 'Укажите accept: true или false' })
|
||||
accept!: boolean;
|
||||
}
|
||||
40
apps/api-gateway/src/dto/media.dto.ts
Normal file
40
apps/api-gateway/src/dto/media.dto.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsIn, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'] as const;
|
||||
export class AvatarUploadDto {
|
||||
@ApiProperty({ description: 'MIME-тип изображения', example: 'image/jpeg', enum: IMAGE_TYPES })
|
||||
@IsString({ message: 'Укажите MIME-тип изображения' })
|
||||
@IsIn([...IMAGE_TYPES], { message: 'Допустимы только JPEG, PNG, WEBP или GIF' })
|
||||
contentType!: string;
|
||||
}
|
||||
|
||||
export class ConfirmAvatarDto {
|
||||
@ApiProperty({ description: 'Ключ объекта в MinIO после загрузки', example: 'avatars/uuid/photo.jpg' })
|
||||
@IsString({ message: 'Ключ хранилища должен быть строкой' })
|
||||
storageKey!: string;
|
||||
}
|
||||
|
||||
export class DocumentPhotoUploadDto {
|
||||
@ApiProperty({ description: 'MIME-тип изображения', example: 'image/jpeg', enum: IMAGE_TYPES })
|
||||
@IsString({ message: 'Укажите MIME-тип изображения' })
|
||||
@IsIn([...IMAGE_TYPES], { message: 'Допустимы только JPEG, PNG, WEBP или GIF' })
|
||||
contentType!: string;
|
||||
}
|
||||
|
||||
export class ChatMediaUploadDto {
|
||||
@ApiProperty({ description: 'MIME-тип файла', example: 'audio/webm' })
|
||||
@IsString({ message: 'Укажите MIME-тип файла' })
|
||||
contentType!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Имя файла для определения расширения', example: 'voice.webm' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Имя файла должно быть строкой' })
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
export class UpdateAvatarStorageDto {
|
||||
@ApiProperty({ description: 'Ключ объекта в MinIO', example: 'avatars/uuid/photo.jpg' })
|
||||
@IsString({ message: 'Ключ хранилища должен быть строкой' })
|
||||
storageKey!: string;
|
||||
}
|
||||
1
apps/api-gateway/src/dto/notifications.dto.ts
Normal file
1
apps/api-gateway/src/dto/notifications.dto.ts
Normal file
@@ -0,0 +1 @@
|
||||
export class MarkNotificationReadDto {}
|
||||
79
apps/api-gateway/src/dto/profile.dto.ts
Normal file
79
apps/api-gateway/src/dto/profile.dto.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsEmail, IsInt, IsNotEmpty, IsOptional, IsString, IsUrl, Matches, Max, Min, MinLength } from 'class-validator';
|
||||
|
||||
export class UpdateAvatarDto {
|
||||
@ApiPropertyOptional({ description: 'Публичная ссылка на аватар (legacy)', example: 'https://cdn.lendry.ru/avatars/user.png' })
|
||||
@IsOptional()
|
||||
@IsUrl({}, { message: 'Укажите корректную ссылку на аватар' })
|
||||
avatarUrl?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Ключ объекта в MinIO', example: 'avatars/uuid/photo.jpg' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Ключ хранилища должен быть строкой' })
|
||||
avatarStorageKey?: string;
|
||||
}
|
||||
|
||||
export class UpdateProfileDto {
|
||||
@ApiPropertyOptional({ description: 'Имя пользователя', example: 'Дмитрий' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Имя должно быть строкой' })
|
||||
firstName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Фамилия пользователя', example: 'Мамедов' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Фамилия должна быть строкой' })
|
||||
lastName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Краткое описание профиля', example: 'Разработчик и владелец аккаунта' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Описание должно быть строкой' })
|
||||
bio?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Возраст пользователя', minimum: 0, maximum: 130, example: 24 })
|
||||
@IsOptional()
|
||||
@IsInt({ message: 'Возраст должен быть целым числом' })
|
||||
@Min(0, { message: 'Возраст не может быть отрицательным' })
|
||||
@Max(130, { message: 'Возраст указан некорректно' })
|
||||
age?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Пол пользователя', example: 'male' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Пол должен быть строкой' })
|
||||
gender?: string;
|
||||
}
|
||||
|
||||
export class UpdateContactsDto {
|
||||
@ApiPropertyOptional({ description: 'Основная почта пользователя', example: 'user@example.com' })
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'Укажите корректную почту' })
|
||||
email?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Основной телефон пользователя', example: '+79990000000' })
|
||||
@IsOptional()
|
||||
@Matches(/^\+?[1-9]\d{7,14}$/, { message: 'Укажите корректный телефон' })
|
||||
phone?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Резервная почта пользователя', example: 'backup@example.com' })
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'Укажите корректную резервную почту' })
|
||||
backupEmail?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Резервный телефон пользователя', example: '+79991112233' })
|
||||
@IsOptional()
|
||||
@Matches(/^\+?[1-9]\d{7,14}$/, { message: 'Укажите корректный резервный телефон' })
|
||||
backupPhone?: string;
|
||||
}
|
||||
|
||||
export class SetPasswordDto {
|
||||
@ApiProperty({ description: 'Новый пароль для входа', minLength: 8 })
|
||||
@IsString({ message: 'Пароль должен быть строкой' })
|
||||
@MinLength(8, { message: 'Пароль должен содержать минимум 8 символов' })
|
||||
password!: string;
|
||||
}
|
||||
|
||||
export class UserIdParamDto {
|
||||
@ApiProperty({ description: 'ID пользователя' })
|
||||
@IsString({ message: 'ID пользователя должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Передайте ID пользователя' })
|
||||
userId!: string;
|
||||
}
|
||||
79
apps/api-gateway/src/dto/rbac.dto.ts
Normal file
79
apps/api-gateway/src/dto/rbac.dto.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsArray, IsBoolean, IsEnum, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export enum GatewayOAuthClientType {
|
||||
CONFIDENTIAL = 'CONFIDENTIAL',
|
||||
PUBLIC = 'PUBLIC'
|
||||
}
|
||||
|
||||
export class CreateRoleDto {
|
||||
@ApiProperty({ description: 'Уникальный slug роли', example: 'support' })
|
||||
@IsString({ message: 'Slug роли должен быть строкой' })
|
||||
slug!: string;
|
||||
|
||||
@ApiProperty({ description: 'Название роли', example: 'Поддержка' })
|
||||
@IsString({ message: 'Название роли должно быть строкой' })
|
||||
name!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Описание роли' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Описание должно быть строкой' })
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Список slug прав', type: [String] })
|
||||
@IsOptional()
|
||||
@IsArray({ message: 'Права должны быть массивом' })
|
||||
@IsString({ each: true, message: 'Каждое право должно быть строкой' })
|
||||
permissionSlugs?: string[];
|
||||
}
|
||||
|
||||
export class AssignUserRoleDto {
|
||||
@ApiProperty({ description: 'Slug роли', example: 'admin' })
|
||||
@IsString({ message: 'Slug роли должен быть строкой' })
|
||||
roleSlug!: string;
|
||||
}
|
||||
|
||||
export class CreateOAuthClientDto {
|
||||
@ApiProperty({ description: 'Название приложения', example: 'Lendry Docs' })
|
||||
@IsString({ message: 'Название должно быть строкой' })
|
||||
name!: string;
|
||||
|
||||
@ApiProperty({ description: 'Redirect URI', type: [String], example: ['https://app.example.com/oauth/callback'] })
|
||||
@IsArray({ message: 'Redirect URI должны быть массивом' })
|
||||
@IsString({ each: true, message: 'Каждый redirect URI должен быть строкой' })
|
||||
redirectUris!: string[];
|
||||
|
||||
@ApiProperty({ description: 'Scopes', type: [String], example: ['openid', 'profile', 'email'] })
|
||||
@IsArray({ message: 'Scopes должны быть массивом' })
|
||||
@IsString({ each: true, message: 'Каждый scope должен быть строкой' })
|
||||
scopes!: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: 'Тип клиента', enum: GatewayOAuthClientType })
|
||||
@IsOptional()
|
||||
@IsEnum(GatewayOAuthClientType, { message: 'Укажите корректный тип клиента' })
|
||||
type?: GatewayOAuthClientType;
|
||||
}
|
||||
|
||||
export class UpdateOAuthClientDto {
|
||||
@ApiPropertyOptional({ description: 'Название приложения' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Название должно быть строкой' })
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Redirect URI', type: [String] })
|
||||
@IsOptional()
|
||||
@IsArray({ message: 'Redirect URI должны быть массивом' })
|
||||
@IsString({ each: true, message: 'Каждый redirect URI должен быть строкой' })
|
||||
redirectUris?: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: 'Scopes', type: [String] })
|
||||
@IsOptional()
|
||||
@IsArray({ message: 'Scopes должны быть массивом' })
|
||||
@IsString({ each: true, message: 'Каждый scope должен быть строкой' })
|
||||
scopes?: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: 'Активность приложения' })
|
||||
@IsOptional()
|
||||
@IsBoolean({ message: 'isActive должно быть boolean' })
|
||||
isActive?: boolean;
|
||||
}
|
||||
25
apps/api-gateway/src/dto/security.dto.ts
Normal file
25
apps/api-gateway/src/dto/security.dto.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString, Length, Matches } from 'class-validator';
|
||||
|
||||
export class PinDto {
|
||||
@ApiProperty({ description: 'PIN-код из 4-6 цифр', example: '1234' })
|
||||
@IsString({ message: 'PIN-код должен быть строкой' })
|
||||
@Length(4, 6, { message: 'PIN-код должен содержать от 4 до 6 символов' })
|
||||
@Matches(/^\d+$/, { message: 'PIN-код должен содержать только цифры' })
|
||||
pin!: string;
|
||||
}
|
||||
|
||||
export class OptionalPinDto {
|
||||
@ApiPropertyOptional({ description: 'PIN-код для подтверждения действия' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'PIN-код должен быть строкой' })
|
||||
@Length(4, 6, { message: 'PIN-код должен содержать от 4 до 6 символов' })
|
||||
@Matches(/^\d+$/, { message: 'PIN-код должен содержать только цифры' })
|
||||
pin?: string;
|
||||
}
|
||||
|
||||
export class VerifySecurityPinDto extends PinDto {
|
||||
@ApiProperty({ description: 'ID сессии, которую нужно разблокировать PIN-кодом' })
|
||||
@IsString({ message: 'ID сессии должен быть строкой' })
|
||||
sessionId!: string;
|
||||
}
|
||||
69
apps/api-gateway/src/dto/settings.dto.ts
Normal file
69
apps/api-gateway/src/dto/settings.dto.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsBoolean, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class UpsertSettingDto {
|
||||
@ApiProperty({ description: 'Ключ настройки', example: 'PIN_LOCK_TIMEOUT_MINUTES' })
|
||||
@IsString({ message: 'Ключ настройки должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите ключ настройки' })
|
||||
key!: string;
|
||||
|
||||
@ApiProperty({ description: 'Значение настройки', example: '15' })
|
||||
@IsString({ message: 'Значение настройки должно быть строкой' })
|
||||
value!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Описание настройки для администраторов' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Описание должно быть строкой' })
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Скрывать ли значение в интерфейсе' })
|
||||
@IsOptional()
|
||||
@IsBoolean({ message: 'Признак секрета должен быть логическим значением' })
|
||||
isSecret?: boolean;
|
||||
}
|
||||
|
||||
export class UpsertSocialProviderDto {
|
||||
@ApiProperty({ description: 'Название OAuth провайдера', example: 'google' })
|
||||
@IsString({ message: 'Название провайдера должно быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите провайдера' })
|
||||
providerName!: string;
|
||||
|
||||
@ApiProperty({ description: 'OAuth Client ID провайдера' })
|
||||
@IsString({ message: 'Client ID должен быть строкой' })
|
||||
@IsNotEmpty({ message: 'Укажите Client ID' })
|
||||
clientId!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'OAuth Client Secret провайдера' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Client Secret должен быть строкой' })
|
||||
clientSecret?: string;
|
||||
|
||||
@ApiProperty({ description: 'Включен ли провайдер для входа' })
|
||||
@IsBoolean({ message: 'Статус провайдера должен быть логическим значением' })
|
||||
isEnabled!: boolean;
|
||||
}
|
||||
|
||||
export class ConnectLinkedAccountDto {
|
||||
@ApiProperty({ description: 'Название провайдера', example: 'google' })
|
||||
@IsString({ message: 'Название провайдера должно быть строкой' })
|
||||
providerName!: string;
|
||||
|
||||
@ApiProperty({ description: 'ID пользователя у внешнего провайдера', example: 'google-user-123' })
|
||||
@IsString({ message: 'ID провайдера должен быть строкой' })
|
||||
providerId!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Почта внешнего аккаунта' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Почта внешнего аккаунта должна быть строкой' })
|
||||
email?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Отображаемое имя внешнего аккаунта' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Имя внешнего аккаунта должно быть строкой' })
|
||||
displayName?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Аватар внешнего аккаунта' })
|
||||
@IsOptional()
|
||||
@IsString({ message: 'Аватар внешнего аккаунта должен быть строкой' })
|
||||
avatarUrl?: string;
|
||||
}
|
||||
44
apps/api-gateway/src/grpc-exception.filter.ts
Normal file
44
apps/api-gateway/src/grpc-exception.filter.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
|
||||
import { status as GrpcStatus } from '@grpc/grpc-js';
|
||||
|
||||
interface HttpResponseLike {
|
||||
status(code: number): { json(body: unknown): unknown };
|
||||
}
|
||||
|
||||
function grpcToHttp(code?: number): number {
|
||||
switch (code) {
|
||||
case GrpcStatus.INVALID_ARGUMENT:
|
||||
case GrpcStatus.FAILED_PRECONDITION:
|
||||
case GrpcStatus.OUT_OF_RANGE:
|
||||
return 400;
|
||||
case GrpcStatus.UNAUTHENTICATED:
|
||||
return 401;
|
||||
case GrpcStatus.PERMISSION_DENIED:
|
||||
return 403;
|
||||
case GrpcStatus.NOT_FOUND:
|
||||
return 404;
|
||||
case GrpcStatus.ALREADY_EXISTS:
|
||||
return 409;
|
||||
default:
|
||||
return 500;
|
||||
}
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class AllExceptionsFilter implements ExceptionFilter {
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const response = host.switchToHttp().getResponse<HttpResponseLike>();
|
||||
|
||||
if (exception instanceof HttpException) {
|
||||
const statusCode = exception.getStatus();
|
||||
const payload = exception.getResponse();
|
||||
response.status(statusCode).json(typeof payload === 'string' ? { statusCode, message: payload } : payload);
|
||||
return;
|
||||
}
|
||||
|
||||
const grpcError = exception as { code?: number; details?: string; message?: string };
|
||||
const statusCode = grpcToHttp(grpcError?.code);
|
||||
const message = grpcError?.details || grpcError?.message || 'Ошибка сервиса';
|
||||
response.status(statusCode).json({ statusCode, message });
|
||||
}
|
||||
}
|
||||
78
apps/api-gateway/src/guards/admin.guard.ts
Normal file
78
apps/api-gateway/src/guards/admin.guard.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { assertSessionUnlocked, verifyAccessToken } from '../session-auth';
|
||||
|
||||
export interface AdminRequestUser {
|
||||
id: string;
|
||||
isSuperAdmin: boolean;
|
||||
canAccessAdmin: boolean;
|
||||
canManageRoles: boolean;
|
||||
canManageOAuth: boolean;
|
||||
canManageUsers: boolean;
|
||||
canViewUsers: boolean;
|
||||
canManageSettings: boolean;
|
||||
roles: string[];
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwt: JwtService,
|
||||
private readonly core: CoreGrpcService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<{ headers: { authorization?: string }; adminUser?: AdminRequestUser }>();
|
||||
|
||||
let payload;
|
||||
try {
|
||||
payload = await verifyAccessToken(this.jwt, request.headers.authorization);
|
||||
await assertSessionUnlocked(this.core, payload);
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException || error instanceof ForbiddenException) {
|
||||
throw error;
|
||||
}
|
||||
throw new UnauthorizedException('Недействительный токен доступа');
|
||||
}
|
||||
|
||||
const profile = (await firstValueFrom(this.core.auth.GetMe({ userId: payload.sub }))) as AdminRequestUser & { id: string };
|
||||
if (!profile.canAccessAdmin) {
|
||||
throw new ForbiddenException('Доступ к админ-панели запрещён');
|
||||
}
|
||||
|
||||
request.adminUser = {
|
||||
id: profile.id,
|
||||
isSuperAdmin: profile.isSuperAdmin,
|
||||
canAccessAdmin: Boolean(profile.canAccessAdmin),
|
||||
canManageRoles: Boolean(profile.canManageRoles),
|
||||
canManageOAuth: Boolean(profile.canManageOAuth),
|
||||
canManageUsers: Boolean(profile.canManageUsers),
|
||||
canManageSettings: Boolean(profile.canManageSettings),
|
||||
canViewUsers: Boolean(profile.canViewUsers),
|
||||
roles: profile.roles ?? [],
|
||||
permissions: profile.permissions ?? []
|
||||
};
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SuperAdminGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest<{ adminUser?: AdminRequestUser }>();
|
||||
if (!request.adminUser?.isSuperAdmin) {
|
||||
throw new ForbiddenException('Только супер-администратор может выполнять это действие');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function assertAdminPermission(user: AdminRequestUser | undefined, permission: keyof Pick<AdminRequestUser, 'canManageOAuth' | 'canManageUsers' | 'canManageSettings'>) {
|
||||
if (!user?.[permission]) {
|
||||
throw new ForbiddenException('Недостаточно прав для выполнения действия');
|
||||
}
|
||||
}
|
||||
34
apps/api-gateway/src/main.ts
Normal file
34
apps/api-gateway/src/main.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { AppModule } from './app.module';
|
||||
import { AllExceptionsFilter } from './grpc-exception.filter';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.enableCors({ origin: true, credentials: true });
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
forbidNonWhitelisted: true
|
||||
})
|
||||
);
|
||||
app.useGlobalFilters(new AllExceptionsFilter());
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('Lendry ID API')
|
||||
.setDescription('REST API для единого входа, безопасности, RBAC и администрирования Lendry ID.')
|
||||
.setVersion('0.1.0')
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('docs', app, document, {
|
||||
swaggerOptions: { persistAuthorization: true },
|
||||
customSiteTitle: 'Документация Lendry ID API'
|
||||
});
|
||||
|
||||
await app.listen(process.env.PORT ? Number(process.env.PORT) : 3000);
|
||||
}
|
||||
|
||||
void bootstrap();
|
||||
5
apps/api-gateway/src/media-content-disposition.ts
Normal file
5
apps/api-gateway/src/media-content-disposition.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export function buildContentDisposition(type: 'inline' | 'attachment', fileName: string) {
|
||||
const asciiFallback = fileName.replace(/[^\x20-\x7E]+/g, '_').replace(/["\\]/g, '_') || 'file';
|
||||
const encoded = encodeURIComponent(fileName);
|
||||
return `${type}; filename="${asciiFallback}"; filename*=UTF-8''${encoded}`;
|
||||
}
|
||||
62
apps/api-gateway/src/session-auth.ts
Normal file
62
apps/api-gateway/src/session-auth.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { ForbiddenException, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { extractBearerToken } from './auth-token';
|
||||
import { CoreGrpcService } from './core-grpc.service';
|
||||
|
||||
export interface AccessTokenPayload {
|
||||
sub: string;
|
||||
sessionId?: string;
|
||||
pinVerified?: boolean;
|
||||
isSuperAdmin?: boolean;
|
||||
}
|
||||
|
||||
export async function verifyAccessToken(jwt: JwtService, authorization?: string): Promise<AccessTokenPayload> {
|
||||
const token = extractBearerToken(authorization);
|
||||
|
||||
try {
|
||||
return await jwt.verifyAsync<AccessTokenPayload>(token, {
|
||||
secret: process.env.JWT_ACCESS_SECRET ?? 'docker-access-secret',
|
||||
issuer: 'id.lendry.ru'
|
||||
});
|
||||
} catch {
|
||||
throw new UnauthorizedException({
|
||||
statusCode: 401,
|
||||
message: 'Токен доступа недействителен или истёк',
|
||||
code: 'TOKEN_EXPIRED'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function assertSessionUnlocked(core: CoreGrpcService, payload: AccessTokenPayload) {
|
||||
if (!payload.sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const validation = (await firstValueFrom(
|
||||
core.auth.ValidateSession({
|
||||
userId: payload.sub,
|
||||
sessionId: payload.sessionId,
|
||||
touchActivity: true
|
||||
})
|
||||
)) as { requiresPin: boolean; sessionId: string };
|
||||
|
||||
if (validation.requiresPin) {
|
||||
throw new ForbiddenException({
|
||||
statusCode: 403,
|
||||
message: 'Требуется подтверждение PIN-кода',
|
||||
code: 'PIN_REQUIRED',
|
||||
sessionId: validation.sessionId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveAuthorizedPayload(
|
||||
jwt: JwtService,
|
||||
core: CoreGrpcService,
|
||||
authorization?: string
|
||||
): Promise<AccessTokenPayload> {
|
||||
const payload = await verifyAccessToken(jwt, authorization);
|
||||
await assertSessionUnlocked(core, payload);
|
||||
return payload;
|
||||
}
|
||||
10
apps/api-gateway/tsconfig.json
Normal file
10
apps/api-gateway/tsconfig.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
40
apps/docs/Dockerfile
Normal file
40
apps/docs/Dockerfile
Normal file
@@ -0,0 +1,40 @@
|
||||
# syntax=docker/dockerfile:1.4
|
||||
|
||||
FROM node:24-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ARG NPM_REGISTRY=https://registry.npmjs.org
|
||||
ARG NEXT_PUBLIC_API_URL=http://localhost:3000
|
||||
|
||||
COPY package.json package-lock.json .npmrc ./
|
||||
COPY apps/sso-core/package.json ./apps/sso-core/
|
||||
COPY apps/api-gateway/package.json ./apps/api-gateway/
|
||||
COPY apps/frontend/package.json ./apps/frontend/
|
||||
COPY apps/docs/package.json ./apps/docs/
|
||||
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm config set registry "${NPM_REGISTRY}" && \
|
||||
for i in 1 2 3 4 5; do \
|
||||
echo "npm ci: попытка $i/5" && \
|
||||
npm ci --no-audit --no-fund && exit 0; \
|
||||
echo "npm ci: ошибка сети, повтор через $((i * 15)) сек..."; \
|
||||
sleep $((i * 15)); \
|
||||
done; \
|
||||
echo "npm ci: все попытки исчерпаны"; \
|
||||
exit 1
|
||||
|
||||
COPY apps ./apps
|
||||
COPY shared ./shared
|
||||
COPY tsconfig.base.json ./
|
||||
|
||||
ENV NEXT_TELEMETRY_DISABLED="1"
|
||||
ENV PORT="3000"
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
ENV NEXT_PUBLIC_API_URL="${NEXT_PUBLIC_API_URL}"
|
||||
|
||||
RUN npm --workspace @lendry/docs run build
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["npm", "--workspace", "@lendry/docs", "run", "start"]
|
||||
17
apps/docs/app/api/public-settings/route.ts
Normal file
17
apps/docs/app/api/public-settings/route.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { fetchPublicSettings } from '@/lib/api';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET() {
|
||||
const settings = await fetchPublicSettings();
|
||||
return Response.json(
|
||||
{
|
||||
settings: Object.entries(settings).map(([key, value]) => ({ key, value }))
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Cache-Control': 'no-store, max-age=0'
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
45
apps/docs/app/docs/[slug]/page.tsx
Normal file
45
apps/docs/app/docs/[slug]/page.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { DocBlockRenderer } from '@/components/doc-block-renderer';
|
||||
import { DocsToc } from '@/components/docs-shell';
|
||||
import { getAllDocSlugs, getDocPage } from '@/lib/docs-pages';
|
||||
|
||||
export function generateStaticParams() {
|
||||
return getAllDocSlugs().map((slug) => ({ slug }));
|
||||
}
|
||||
|
||||
export default async function DocPage({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params;
|
||||
const page = getDocPage(slug);
|
||||
if (!page) notFound();
|
||||
|
||||
return (
|
||||
<>
|
||||
<main className="min-w-0 max-w-3xl prose-docs">
|
||||
<div className="mb-10 border-b border-zinc-200 pb-8 dark:border-zinc-800">
|
||||
<p className="text-sm font-medium text-zinc-500">Документация</p>
|
||||
<h1 className="mt-2 text-4xl font-bold tracking-tight text-zinc-950 dark:text-zinc-50">{page.title}</h1>
|
||||
<p className="mt-4 text-lg leading-relaxed text-zinc-600 dark:text-zinc-400">{page.description}</p>
|
||||
</div>
|
||||
|
||||
<article className="space-y-12 pb-16">
|
||||
{page.sections.map((section) => (
|
||||
<section id={section.id} key={section.id} className="scroll-mt-24">
|
||||
<h2 className="mb-4 text-2xl font-semibold tracking-tight text-zinc-950 dark:text-zinc-50">{section.title}</h2>
|
||||
<div className="space-y-4">
|
||||
{section.blocks.map((block, index) => (
|
||||
<DocBlockRenderer key={`${section.id}-${index}`} block={block} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</article>
|
||||
</main>
|
||||
|
||||
<aside className="hidden xl:block">
|
||||
<div className="sticky top-20">
|
||||
<DocsToc sections={page.sections.map((s) => ({ id: s.id, title: s.title }))} />
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
27
apps/docs/app/docs/layout.tsx
Normal file
27
apps/docs/app/docs/layout.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import { docNavigation, groupDocNavigation } from '@/lib/navigation';
|
||||
import { fetchPublicSettings } from '@/lib/api';
|
||||
import { PublicSettingsProvider } from '@/providers/public-settings-provider';
|
||||
import { DocsHeader, DocsSidebar } from '@/components/docs-shell';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function DocsLayout({ children }: { children: React.ReactNode }) {
|
||||
const initialSettings = await fetchPublicSettings();
|
||||
const groups = groupDocNavigation(docNavigation);
|
||||
|
||||
return (
|
||||
<PublicSettingsProvider initialSettings={initialSettings}>
|
||||
<div className="min-h-screen bg-white dark:bg-zinc-950">
|
||||
<DocsHeader />
|
||||
<div className="mx-auto grid max-w-screen-2xl grid-cols-1 gap-8 px-4 py-8 lg:grid-cols-[240px_minmax(0,1fr)] lg:px-8 xl:grid-cols-[240px_minmax(0,1fr)_200px]">
|
||||
<aside className="hidden lg:block">
|
||||
<div className="sticky top-20">
|
||||
<DocsSidebar groups={groups} />
|
||||
</div>
|
||||
</aside>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</PublicSettingsProvider>
|
||||
);
|
||||
}
|
||||
5
apps/docs/app/docs/page.tsx
Normal file
5
apps/docs/app/docs/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { DocsHomeContent } from '@/components/docs-home-content';
|
||||
|
||||
export default function DocsHomePage() {
|
||||
return <DocsHomeContent />;
|
||||
}
|
||||
46
apps/docs/app/globals.css
Normal file
46
apps/docs/app/globals.css
Normal file
@@ -0,0 +1,46 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #09090b;
|
||||
--muted: #f4f4f5;
|
||||
--border: #e4e4e7;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: #09090b;
|
||||
--foreground: #fafafa;
|
||||
--muted: #18181b;
|
||||
--border: #27272a;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
--font-mono: var(--font-geist-mono), ui-monospace, monospace;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: rgb(24 24 27 / 0.15);
|
||||
}
|
||||
|
||||
.dark ::selection {
|
||||
background: rgb(250 250 250 / 0.15);
|
||||
}
|
||||
|
||||
.prose-docs h2 {
|
||||
scroll-margin-top: 5rem;
|
||||
}
|
||||
37
apps/docs/app/layout.tsx
Normal file
37
apps/docs/app/layout.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { Geist, Geist_Mono } from 'next/font/google';
|
||||
import { ThemeProvider } from '@/providers/theme-provider';
|
||||
import './globals.css';
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: '--font-geist-sans',
|
||||
subsets: ['latin', 'cyrillic']
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: '--font-geist-mono',
|
||||
subsets: ['latin']
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: {
|
||||
default: 'Документация',
|
||||
template: '%s — Docs'
|
||||
},
|
||||
description: 'Документация по интеграции, OAuth 2.0, развёртыванию и REST API Identity Provider.'
|
||||
};
|
||||
|
||||
const themeScript = `(function(){try{var t=localStorage.getItem('docs-theme');var dark=t==='dark'||(t!=='light'&&window.matchMedia('(prefers-color-scheme: dark)').matches);document.documentElement.classList.toggle('dark',dark);}catch(e){}})();`;
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="ru" suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
|
||||
</head>
|
||||
<body className={`${geistSans.variable} ${geistMono.variable} min-h-screen antialiased`}>
|
||||
<ThemeProvider>{children}</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
5
apps/docs/app/page.tsx
Normal file
5
apps/docs/app/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function HomePage() {
|
||||
redirect('/docs');
|
||||
}
|
||||
45
apps/docs/components/api-endpoint-card.tsx
Normal file
45
apps/docs/components/api-endpoint-card.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { apiReference, type ApiEndpoint } from '@/lib/api-endpoints';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const methodColors: Record<ApiEndpoint['method'], string> = {
|
||||
GET: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300',
|
||||
POST: 'bg-blue-100 text-blue-800 dark:bg-blue-950 dark:text-blue-300',
|
||||
PUT: 'bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-300',
|
||||
PATCH: 'bg-violet-100 text-violet-800 dark:bg-violet-950 dark:text-violet-300',
|
||||
DELETE: 'bg-red-100 text-red-800 dark:bg-red-950 dark:text-red-300'
|
||||
};
|
||||
|
||||
export function ApiEndpointCard({ endpoint }: { endpoint: ApiEndpoint }) {
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="flex flex-col gap-2 p-4 sm:flex-row sm:items-start sm:gap-4">
|
||||
<Badge className={cn('w-fit shrink-0 font-mono', methodColors[endpoint.method])}>{endpoint.method}</Badge>
|
||||
<div className="min-w-0 flex-1">
|
||||
<code className="break-all text-sm font-medium">{endpoint.path}</code>
|
||||
<p className="mt-1 text-sm font-medium">{endpoint.summary}</p>
|
||||
{endpoint.description ? <p className="mt-1 text-sm text-zinc-500">{endpoint.description}</p> : null}
|
||||
{endpoint.auth ? <p className="mt-2 text-xs text-zinc-400">Требуется Authorization: Bearer JWT</p> : null}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function ApiReferenceSection() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{apiReference.map((group) => (
|
||||
<div key={group.tag}>
|
||||
<h3 className="mb-4 text-lg font-semibold">{group.tag}</h3>
|
||||
<div className="space-y-3">
|
||||
{group.endpoints.map((endpoint) => (
|
||||
<ApiEndpointCard key={`${endpoint.method}-${endpoint.path}`} endpoint={endpoint} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
8
apps/docs/components/auth-code-tabs.tsx
Normal file
8
apps/docs/components/auth-code-tabs.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { authLoginExamples } from '@/lib/auth-examples';
|
||||
import { CodeExampleTabs } from '@/components/code-example-tabs';
|
||||
|
||||
export function AuthLoginCodeTabs() {
|
||||
return <CodeExampleTabs examples={authLoginExamples} />;
|
||||
}
|
||||
8
apps/docs/components/auth-ldap-code-tabs.tsx
Normal file
8
apps/docs/components/auth-ldap-code-tabs.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { authLdapExamples } from '@/lib/auth-examples';
|
||||
import { CodeExampleTabs } from '@/components/code-example-tabs';
|
||||
|
||||
export function AuthLdapCodeTabs() {
|
||||
return <CodeExampleTabs examples={authLdapExamples} />;
|
||||
}
|
||||
43
apps/docs/components/code-block.tsx
Normal file
43
apps/docs/components/code-block.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Check, Copy } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function CodeBlock({ code, language, title }: { code: string; language?: string; title?: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
async function copy() {
|
||||
await navigator.clipboard.writeText(code);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group relative my-4 overflow-hidden rounded-xl border border-zinc-200 dark:border-zinc-800">
|
||||
{(title || language) && (
|
||||
<div className="flex items-center justify-between border-b border-zinc-200 bg-zinc-50 px-4 py-2 text-xs text-zinc-500 dark:border-zinc-800 dark:bg-zinc-900">
|
||||
<span>{title ?? language}</span>
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 opacity-0 group-hover:opacity-100" onClick={copy}>
|
||||
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
{copied ? 'Скопировано' : 'Копировать'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<pre className={cn('overflow-x-auto bg-zinc-950 p-4 text-sm leading-relaxed text-zinc-50', !title && !language && 'rounded-xl')}>
|
||||
<code>{code}</code>
|
||||
</pre>
|
||||
{!title && !language && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-2 top-2 h-7 bg-zinc-900/80 px-2 text-zinc-300 opacity-0 group-hover:opacity-100"
|
||||
onClick={copy}
|
||||
>
|
||||
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
26
apps/docs/components/code-example-tabs.tsx
Normal file
26
apps/docs/components/code-example-tabs.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import type { CodeExample } from '@/lib/code-example';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { CodeBlock } from '@/components/code-block';
|
||||
|
||||
export function CodeExampleTabs({ examples }: { examples: CodeExample[] }) {
|
||||
if (examples.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Tabs defaultValue={examples[0].id} className="my-6">
|
||||
<TabsList className="mb-2 flex h-auto max-w-full flex-wrap gap-1">
|
||||
{examples.map((example) => (
|
||||
<TabsTrigger key={example.id} value={example.id} className="text-xs sm:text-sm">
|
||||
{example.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
{examples.map((example) => (
|
||||
<TabsContent key={example.id} value={example.id}>
|
||||
<CodeBlock code={example.code} language={example.language} title={example.label} />
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
78
apps/docs/components/doc-block-renderer.tsx
Normal file
78
apps/docs/components/doc-block-renderer.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import type { DocBlock } from '@/lib/docs-pages';
|
||||
import { OAuthCodeTabs } from '@/components/oauth-code-tabs';
|
||||
import { AuthLoginCodeTabs } from '@/components/auth-code-tabs';
|
||||
import { AuthLdapCodeTabs } from '@/components/auth-ldap-code-tabs';
|
||||
import { ApiReferenceSection } from '@/components/api-endpoint-card';
|
||||
import { CodeBlock } from '@/components/code-block';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function Callout({ variant, title, text }: { variant: 'info' | 'warning' | 'tip'; title: string; text: string }) {
|
||||
const styles = {
|
||||
info: 'border-blue-200 bg-blue-50 dark:border-blue-900 dark:bg-blue-950/40',
|
||||
warning: 'border-amber-200 bg-amber-50 dark:border-amber-900 dark:bg-amber-950/40',
|
||||
tip: 'border-emerald-200 bg-emerald-50 dark:border-emerald-900 dark:bg-emerald-950/40'
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn('my-4 rounded-xl border p-4', styles[variant])}>
|
||||
<p className="font-semibold">{title}</p>
|
||||
<p className="mt-1 text-sm leading-relaxed text-zinc-600 dark:text-zinc-300">{text}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DocBlockRenderer({ block }: { block: DocBlock }) {
|
||||
switch (block.type) {
|
||||
case 'paragraph':
|
||||
return <p className="leading-7 text-zinc-600 dark:text-zinc-300">{block.text}</p>;
|
||||
case 'list':
|
||||
return (
|
||||
<ul className="my-4 list-disc space-y-2 pl-6 leading-7 text-zinc-600 dark:text-zinc-300">
|
||||
{block.items.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
case 'code':
|
||||
return <CodeBlock code={block.code} language={block.language} title={block.title} />;
|
||||
case 'callout':
|
||||
return <Callout variant={block.variant} title={block.title} text={block.text} />;
|
||||
case 'table':
|
||||
return (
|
||||
<div className="my-4 overflow-x-auto rounded-xl border border-zinc-200 dark:border-zinc-800">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-200 bg-zinc-50 dark:border-zinc-800 dark:bg-zinc-900">
|
||||
{block.headers.map((header) => (
|
||||
<th key={header} className="px-4 py-3 text-left font-semibold">
|
||||
{header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{block.rows.map((row, index) => (
|
||||
<tr key={index} className="border-b border-zinc-100 last:border-0 dark:border-zinc-800">
|
||||
{row.map((cell, cellIndex) => (
|
||||
<td key={cellIndex} className="px-4 py-3 align-top text-zinc-600 dark:text-zinc-300">
|
||||
{cell}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
case 'oauth-examples':
|
||||
return <OAuthCodeTabs />;
|
||||
case 'auth-login-examples':
|
||||
return <AuthLoginCodeTabs />;
|
||||
case 'auth-ldap-examples':
|
||||
return <AuthLdapCodeTabs />;
|
||||
case 'api-reference':
|
||||
return <ApiReferenceSection />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
103
apps/docs/components/docs-home-content.tsx
Normal file
103
apps/docs/components/docs-home-content.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { ArrowRight, BookOpen, Code2, Rocket, Shield } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { docNavigation, groupDocNavigation } from '@/lib/navigation';
|
||||
import { usePublicSettings } from '@/providers/public-settings-provider';
|
||||
|
||||
const highlights = [
|
||||
{
|
||||
icon: Rocket,
|
||||
title: 'Быстрый старт',
|
||||
description: 'Локальный запуск через Docker Compose за несколько минут.',
|
||||
href: '/docs/getting-started'
|
||||
},
|
||||
{
|
||||
icon: Code2,
|
||||
title: 'OAuth 2.0',
|
||||
description: 'Примеры интеграции на JavaScript, Python, PHP, Go и других языках.',
|
||||
href: '/docs/oauth'
|
||||
},
|
||||
{
|
||||
icon: Shield,
|
||||
title: 'Безопасность',
|
||||
description: 'PIN-код, сессии, LDAP/LDAPS и управление устройствами.',
|
||||
href: '/docs/sessions'
|
||||
},
|
||||
{
|
||||
icon: BookOpen,
|
||||
title: 'Справочник API',
|
||||
description: 'Полный список REST endpoints и ссылка на Swagger.',
|
||||
href: '/docs/api-reference'
|
||||
}
|
||||
];
|
||||
|
||||
export function DocsHomeContent() {
|
||||
const { projectName, projectTagline } = usePublicSettings();
|
||||
const groups = groupDocNavigation(docNavigation);
|
||||
|
||||
return (
|
||||
<main className="min-w-0 pb-16 xl:col-span-1">
|
||||
<section className="relative overflow-hidden rounded-2xl border border-zinc-200 bg-zinc-50 px-6 py-12 dark:border-zinc-800 dark:bg-zinc-900/50 sm:px-10 sm:py-16">
|
||||
<p className="text-sm font-medium text-zinc-500">Документация</p>
|
||||
<h1 className="mt-3 max-w-2xl text-4xl font-bold tracking-tight text-zinc-950 dark:text-zinc-50 sm:text-5xl">{projectName}</h1>
|
||||
<p className="mt-4 max-w-2xl text-lg leading-relaxed text-zinc-600 dark:text-zinc-400">{projectTagline}</p>
|
||||
<p className="mt-4 max-w-2xl text-zinc-600 dark:text-zinc-400">
|
||||
Enterprise Identity Provider: единый вход, OAuth 2.0, корпоративный LDAP, семейные группы, чат и админ-панель.
|
||||
</p>
|
||||
<div className="mt-8 flex flex-wrap gap-3">
|
||||
<Button asChild size="lg">
|
||||
<Link href="/docs/getting-started">
|
||||
Начать
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild variant="outline" size="lg">
|
||||
<Link href="/docs/deployment">Развёртывание</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mt-10 grid gap-4 sm:grid-cols-2">
|
||||
{highlights.map((item) => (
|
||||
<Link key={item.href} href={item.href}>
|
||||
<Card className="h-full transition-colors hover:border-zinc-300 dark:hover:border-zinc-700">
|
||||
<CardHeader>
|
||||
<div className="mb-2 flex h-10 w-10 items-center justify-center rounded-lg bg-zinc-100 dark:bg-zinc-800">
|
||||
<item.icon className="h-5 w-5" />
|
||||
</div>
|
||||
<CardTitle>{item.title}</CardTitle>
|
||||
<CardDescription>{item.description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<span className="text-sm font-medium text-zinc-500">Читать →</span>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<section className="mt-12">
|
||||
<h2 className="text-xl font-semibold">Все разделы</h2>
|
||||
<div className="mt-4 grid gap-6 sm:grid-cols-2">
|
||||
{groups.map(([group, items]) => (
|
||||
<div key={group}>
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wider text-zinc-500">{group}</p>
|
||||
<ul className="space-y-2">
|
||||
{items.map((item) => (
|
||||
<li key={item.slug}>
|
||||
<Link href={`/docs/${item.slug}`} className="text-sm text-zinc-600 hover:text-zinc-950 dark:text-zinc-400 dark:hover:text-zinc-50">
|
||||
{item.title}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
109
apps/docs/components/docs-shell.tsx
Normal file
109
apps/docs/components/docs-shell.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { BookOpen, ExternalLink, Moon, Sun } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { usePublicSettings } from '@/providers/public-settings-provider';
|
||||
import { useTheme } from '@/providers/theme-provider';
|
||||
import { getApiBaseUrl } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function DocsHeader() {
|
||||
const { projectName } = usePublicSettings();
|
||||
const { resolvedTheme, setTheme } = useTheme();
|
||||
const apiUrl = getApiBaseUrl();
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 w-full border-b border-zinc-200 bg-white/80 backdrop-blur dark:border-zinc-800 dark:bg-zinc-950/80">
|
||||
<div className="mx-auto flex h-14 max-w-screen-2xl items-center justify-between gap-4 px-4 lg:px-8">
|
||||
<Link href="/docs" className="flex items-center gap-2 font-semibold tracking-tight">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-zinc-900 text-white dark:bg-zinc-50 dark:text-zinc-900">
|
||||
<BookOpen className="h-4 w-4" />
|
||||
</div>
|
||||
<span className="hidden sm:inline">{projectName}</span>
|
||||
<span className="text-zinc-400 font-normal hidden sm:inline">Docs</span>
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="sm" asChild className="hidden md:inline-flex">
|
||||
<a href={`${apiUrl}/api`} target="_blank" rel="noreferrer">
|
||||
Swagger
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
aria-label="Переключить тему"
|
||||
onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}
|
||||
>
|
||||
{resolvedTheme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export function DocsSidebar({ groups }: { groups: Array<[string, Array<{ slug: string; title: string }>]> }) {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<nav className="space-y-6">
|
||||
<Link
|
||||
href="/docs"
|
||||
className={cn(
|
||||
'block rounded-lg px-3 py-2 text-sm font-medium transition-colors',
|
||||
pathname === '/docs'
|
||||
? 'bg-zinc-100 text-zinc-900 dark:bg-zinc-800 dark:text-zinc-50'
|
||||
: 'text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-zinc-50'
|
||||
)}
|
||||
>
|
||||
Главная
|
||||
</Link>
|
||||
{groups.map(([group, items]) => (
|
||||
<div key={group}>
|
||||
<p className="mb-2 px-2 text-xs font-semibold uppercase tracking-wider text-zinc-500">{group}</p>
|
||||
<div className="space-y-1">
|
||||
{items.map((item) => {
|
||||
const href = `/docs/${item.slug}`;
|
||||
const active = pathname === href;
|
||||
return (
|
||||
<Link
|
||||
key={item.slug}
|
||||
href={href}
|
||||
className={cn(
|
||||
'block rounded-lg px-3 py-2 text-sm transition-colors',
|
||||
active
|
||||
? 'bg-zinc-100 font-medium text-zinc-900 dark:bg-zinc-800 dark:text-zinc-50'
|
||||
: 'text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-zinc-50'
|
||||
)}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
export function DocsToc({ sections }: { sections: Array<{ id: string; title: string }> }) {
|
||||
return (
|
||||
<nav className="space-y-2 text-sm">
|
||||
<p className="mb-3 font-semibold">На этой странице</p>
|
||||
{sections.map((section) => (
|
||||
<a
|
||||
key={section.id}
|
||||
href={`#${section.id}`}
|
||||
className="block text-zinc-500 transition-colors hover:text-zinc-900 dark:hover:text-zinc-50"
|
||||
>
|
||||
{section.title}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
8
apps/docs/components/oauth-code-tabs.tsx
Normal file
8
apps/docs/components/oauth-code-tabs.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { oauthExamples } from '@/lib/oauth-examples';
|
||||
import { CodeExampleTabs } from '@/components/code-example-tabs';
|
||||
|
||||
export function OAuthCodeTabs() {
|
||||
return <CodeExampleTabs examples={oauthExamples} />;
|
||||
}
|
||||
14
apps/docs/components/ui/badge.tsx
Normal file
14
apps/docs/components/ui/badge.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function Badge({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'inline-flex items-center rounded-md border border-zinc-200 px-2.5 py-0.5 text-xs font-semibold transition-colors dark:border-zinc-800',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
41
apps/docs/components/ui/button.tsx
Normal file
41
apps/docs/components/ui/button.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
'border border-transparent bg-zinc-900 text-zinc-50 shadow hover:bg-zinc-800 dark:border-zinc-700 dark:bg-zinc-100 dark:text-zinc-900 dark:shadow-none dark:hover:bg-zinc-200',
|
||||
secondary:
|
||||
'bg-zinc-100 text-zinc-900 hover:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-100 dark:hover:bg-zinc-700',
|
||||
outline:
|
||||
'border border-zinc-300 bg-transparent text-zinc-900 hover:bg-zinc-100 dark:border-zinc-600 dark:bg-transparent dark:text-zinc-100 dark:hover:bg-zinc-800',
|
||||
ghost: 'text-zinc-900 hover:bg-zinc-100 dark:text-zinc-100 dark:hover:bg-zinc-800',
|
||||
link: 'text-zinc-900 underline-offset-4 hover:underline dark:text-zinc-100'
|
||||
},
|
||||
size: {
|
||||
default: 'h-9 px-4 py-2',
|
||||
sm: 'h-8 rounded-lg px-3 text-xs',
|
||||
lg: 'h-11 rounded-xl px-8 text-base',
|
||||
icon: 'h-9 w-9'
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
export function Button({ className, variant, size, asChild = false, ...props }: ButtonProps) {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return <Comp className={cn(buttonVariants({ variant, size, className }))} {...props} />;
|
||||
}
|
||||
22
apps/docs/components/ui/card.tsx
Normal file
22
apps/docs/components/ui/card.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function Card({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn('rounded-xl border border-zinc-200 bg-white text-zinc-950 shadow-sm dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50', className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardTitle({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) {
|
||||
return <h3 className={cn('text-lg font-semibold leading-none tracking-tight', className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardDescription({ className, ...props }: React.HTMLAttributes<HTMLParagraphElement>) {
|
||||
return <p className={cn('text-sm text-zinc-500 dark:text-zinc-400', className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardContent({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn('p-6 pt-0', className)} {...props} />;
|
||||
}
|
||||
31
apps/docs/components/ui/scroll-area.tsx
Normal file
31
apps/docs/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client';
|
||||
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function ScrollArea({ className, children, ...props }: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root className={cn('relative overflow-hidden', className)} {...props}>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({ className, orientation = 'vertical', ...props }: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'flex touch-none select-none transition-colors',
|
||||
orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent p-[1px]',
|
||||
orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent p-[1px]',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-zinc-200 dark:bg-zinc-800" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
);
|
||||
}
|
||||
31
apps/docs/components/ui/tabs.tsx
Normal file
31
apps/docs/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client';
|
||||
|
||||
import * as TabsPrimitive from '@radix-ui/react-tabs';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export const Tabs = TabsPrimitive.Root;
|
||||
|
||||
export function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
className={cn('inline-flex h-10 items-center justify-center rounded-lg bg-zinc-100 p-1 text-zinc-500 dark:bg-zinc-900', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-zinc-950 data-[state=active]:shadow dark:ring-offset-zinc-950 dark:data-[state=active]:bg-zinc-800 dark:data-[state=active]:text-zinc-50',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return <TabsPrimitive.Content className={cn('mt-4 focus-visible:outline-none', className)} {...props} />;
|
||||
}
|
||||
116
apps/docs/lib/api-endpoints.ts
Normal file
116
apps/docs/lib/api-endpoints.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
export interface ApiEndpoint {
|
||||
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
path: string;
|
||||
summary: string;
|
||||
description?: string;
|
||||
auth?: boolean;
|
||||
}
|
||||
|
||||
export interface ApiTagGroup {
|
||||
tag: string;
|
||||
endpoints: ApiEndpoint[];
|
||||
}
|
||||
|
||||
export const apiReference: ApiTagGroup[] = [
|
||||
{
|
||||
tag: 'Аутентификация',
|
||||
endpoints: [
|
||||
{ method: 'POST', path: '/auth/register', summary: 'Регистрация пользователя', description: 'Первый пользователь получает isSuperAdmin.' },
|
||||
{ method: 'POST', path: '/auth/login', summary: 'Вход по почте, телефону или логину' },
|
||||
{ method: 'POST', path: '/auth/identify', summary: 'Проверить способ входа (identifier-first)' },
|
||||
{ method: 'POST', path: '/auth/otp/send', summary: 'Отправить OTP для passwordless-входа' },
|
||||
{ method: 'POST', path: '/auth/otp/verify', summary: 'Проверить OTP' },
|
||||
{ method: 'POST', path: '/auth/login/password', summary: 'Войти по паролю' },
|
||||
{ method: 'POST', path: '/auth/ldap/login', summary: 'Войти через LDAP/LDAPS' },
|
||||
{ method: 'POST', path: '/auth/pin/verify', summary: 'Подтвердить PIN-код' },
|
||||
{ method: 'POST', path: '/auth/refresh', summary: 'Обновить access token' },
|
||||
{ method: 'GET', path: '/auth/session', summary: 'Состояние текущей сессии', auth: true },
|
||||
{ method: 'GET', path: '/auth/me', summary: 'Текущий пользователь', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'OAuth 2.0',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/oauth/authorize', summary: 'Создать authorization code' },
|
||||
{ method: 'POST', path: '/oauth/token', summary: 'Выдать OAuth токены (code / refresh_token)' },
|
||||
{ method: 'GET', path: '/oauth/userinfo', summary: 'Профиль по OAuth access token', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Профиль и биометрия',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/profile/users/{userId}', summary: 'Получить профиль', auth: true },
|
||||
{ method: 'PATCH', path: '/profile/users/{userId}', summary: 'Обновить профиль', auth: true },
|
||||
{ method: 'PATCH', path: '/profile/users/{userId}/avatar', summary: 'Обновить аватар', auth: true },
|
||||
{ method: 'PATCH', path: '/profile/users/{userId}/contacts', summary: 'Обновить контакты', auth: true },
|
||||
{ method: 'POST', path: '/profile/users/{userId}/password', summary: 'Установить пароль', auth: true },
|
||||
{ method: 'POST', path: '/profile/users/{userId}/self-delete', summary: 'Удалить свой профиль', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Безопасность',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/security/users/{userId}/devices', summary: 'Активные устройства', auth: true },
|
||||
{ method: 'GET', path: '/security/users/{userId}/sessions', summary: 'Активные сессии', auth: true },
|
||||
{ method: 'POST', path: '/security/users/{userId}/pin/setup', summary: 'Настроить PIN', auth: true },
|
||||
{ method: 'POST', path: '/security/users/{userId}/revoke-all-sessions', summary: 'Выйти везде', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Администрирование',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/admin/users', summary: 'Список пользователей', auth: true },
|
||||
{ method: 'PATCH', path: '/admin/users/{userId}', summary: 'Обновить пользователя', auth: true },
|
||||
{ method: 'POST', path: '/admin/users/{userId}/reset-password', summary: 'Сбросить пароль', auth: true },
|
||||
{ method: 'PATCH', path: '/admin/users/{userId}/super-admin', summary: 'Права супер-администратора', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'RBAC и OAuth',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/admin/rbac/roles', summary: 'Список ролей', auth: true },
|
||||
{ method: 'POST', path: '/admin/rbac/oauth-clients', summary: 'Создать OAuth-приложение', auth: true },
|
||||
{ method: 'GET', path: '/admin/rbac/oauth-scopes', summary: 'OAuth scopes', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Глобальные настройки',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/admin/settings', summary: 'Список системных настроек', auth: true },
|
||||
{ method: 'PUT', path: '/admin/settings', summary: 'Создать или обновить настройку', auth: true },
|
||||
{ method: 'GET', path: '/settings/public', summary: 'Публичные настройки (без авторизации)' }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Семья',
|
||||
endpoints: [
|
||||
{ method: 'POST', path: '/family/groups', summary: 'Создать семейную группу', auth: true },
|
||||
{ method: 'GET', path: '/family/users/{userId}/groups', summary: 'Список семей пользователя', auth: true },
|
||||
{ method: 'POST', path: '/family/groups/{groupId}/invites', summary: 'Пригласить участника', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Чат',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/chat/groups/{groupId}/rooms', summary: 'Список чатов семьи', auth: true },
|
||||
{ method: 'POST', path: '/chat/rooms/{roomId}/messages', summary: 'Отправить сообщение', auth: true },
|
||||
{ method: 'GET', path: '/chat/rooms/{roomId}/messages', summary: 'Сообщения чата', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Медиа',
|
||||
endpoints: [
|
||||
{ method: 'POST', path: '/media/avatars/upload-url', summary: 'URL для загрузки аватара', auth: true },
|
||||
{ method: 'GET', path: '/media/stream/{token}', summary: 'Потоковая выдача медиа' },
|
||||
{ method: 'POST', path: '/media/chat/{roomId}/media/upload-url', summary: 'URL для медиа чата', auth: true }
|
||||
]
|
||||
},
|
||||
{
|
||||
tag: 'Уведомления',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/notifications', summary: 'Список уведомлений', auth: true },
|
||||
{ method: 'PATCH', path: '/notifications/{notificationId}/read', summary: 'Удалить просмотренное', auth: true },
|
||||
{ method: 'DELETE', path: '/notifications', summary: 'Удалить все уведомления', auth: true }
|
||||
]
|
||||
}
|
||||
];
|
||||
59
apps/docs/lib/api.ts
Normal file
59
apps/docs/lib/api.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
const clientApiUrl = (process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000').replace(/\/$/, '');
|
||||
|
||||
function getServerApiUrl() {
|
||||
return (process.env.INTERNAL_API_URL ?? process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3000').replace(/\/$/, '');
|
||||
}
|
||||
|
||||
export interface PublicSetting {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(url: string, init: RequestInit & { timeoutMs?: number } = {}) {
|
||||
const { timeoutMs = 3000, ...rest } = init;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
return await fetch(url, { ...rest, signal: controller.signal });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function mapSettings(payload: { settings?: PublicSetting[] }) {
|
||||
return Object.fromEntries((payload.settings ?? []).map((item) => [item.key, item.value]));
|
||||
}
|
||||
|
||||
export async function fetchPublicSettings(): Promise<Record<string, string>> {
|
||||
try {
|
||||
const response = await fetchWithTimeout(`${getServerApiUrl()}/settings/public`, {
|
||||
cache: 'no-store'
|
||||
});
|
||||
if (!response.ok) {
|
||||
return {};
|
||||
}
|
||||
return mapSettings((await response.json()) as { settings?: PublicSetting[] });
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchPublicSettingsClient(): Promise<Record<string, string>> {
|
||||
const response = await fetchWithTimeout('/api/public-settings', { cache: 'no-store' });
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось загрузить публичные настройки');
|
||||
}
|
||||
return mapSettings((await response.json()) as { settings?: PublicSetting[] });
|
||||
}
|
||||
|
||||
export function getApiBaseUrl() {
|
||||
return clientApiUrl;
|
||||
}
|
||||
|
||||
export function getDefaultProjectName() {
|
||||
return 'Lendry ID';
|
||||
}
|
||||
|
||||
export function getDefaultProjectTagline() {
|
||||
return 'Единый аккаунт для сервисов Lendry';
|
||||
}
|
||||
494
apps/docs/lib/auth-examples.ts
Normal file
494
apps/docs/lib/auth-examples.ts
Normal file
@@ -0,0 +1,494 @@
|
||||
import type { CodeExample } from '@/lib/code-example';
|
||||
|
||||
const API_BASE = 'https://id.lendry.ru';
|
||||
|
||||
const loginBody = `{
|
||||
"login": "user@example.com",
|
||||
"password": "SecurePass123",
|
||||
"fingerprint": "device-fp-uuid",
|
||||
"deviceName": "Chrome на Windows",
|
||||
"deviceType": "WEB"
|
||||
}`;
|
||||
|
||||
export const authLoginExamples: CodeExample[] = [
|
||||
{
|
||||
id: 'curl',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `curl -X POST ${API_BASE}/auth/login/password \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '${loginBody.replace(/\n/g, '\n ')}'`
|
||||
},
|
||||
{
|
||||
id: 'javascript',
|
||||
label: 'JavaScript',
|
||||
language: 'javascript',
|
||||
code: `const response = await fetch('${API_BASE}/auth/login/password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
login: 'user@example.com',
|
||||
password: 'SecurePass123',
|
||||
fingerprint: crypto.randomUUID(),
|
||||
deviceName: 'Chrome на Windows',
|
||||
deviceType: 'WEB'
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text());
|
||||
}
|
||||
|
||||
const session = await response.json();
|
||||
// session.accessToken, session.refreshToken, session.requiresPin`
|
||||
},
|
||||
{
|
||||
id: 'typescript',
|
||||
label: 'TypeScript',
|
||||
language: 'typescript',
|
||||
code: `interface LoginPayload {
|
||||
login: string;
|
||||
password: string;
|
||||
fingerprint: string;
|
||||
deviceName: string;
|
||||
deviceType: 'WEB' | 'MOBILE' | 'DESKTOP';
|
||||
}
|
||||
|
||||
interface AuthTokens {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
requiresPin?: boolean;
|
||||
}
|
||||
|
||||
export async function login(payload: LoginPayload): Promise<AuthTokens> {
|
||||
const response = await fetch('${API_BASE}/auth/login/password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
if (!response.ok) throw new Error(await response.text());
|
||||
return response.json();
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'python',
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import requests
|
||||
|
||||
response = requests.post(
|
||||
'${API_BASE}/auth/login/password',
|
||||
json={
|
||||
'login': 'user@example.com',
|
||||
'password': 'SecurePass123',
|
||||
'fingerprint': 'device-fp-uuid',
|
||||
'deviceName': 'Chrome на Windows',
|
||||
'deviceType': 'WEB',
|
||||
},
|
||||
timeout=15,
|
||||
)
|
||||
response.raise_for_status()
|
||||
session = response.json()
|
||||
print(session['accessToken'])`
|
||||
},
|
||||
{
|
||||
id: 'php',
|
||||
label: 'PHP',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
$payload = json_encode([
|
||||
'login' => 'user@example.com',
|
||||
'password' => 'SecurePass123',
|
||||
'fingerprint' => bin2hex(random_bytes(16)),
|
||||
'deviceName' => 'Chrome на Windows',
|
||||
'deviceType' => 'WEB',
|
||||
]);
|
||||
|
||||
$ch = curl_init('${API_BASE}/auth/login/password');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_POSTFIELDS => $payload,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
]);
|
||||
$response = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($status >= 400) {
|
||||
throw new RuntimeException($response);
|
||||
}
|
||||
|
||||
$session = json_decode($response, true);`
|
||||
},
|
||||
{
|
||||
id: 'go',
|
||||
label: 'Go',
|
||||
language: 'go',
|
||||
code: `package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
Login string \`json:"login"\`
|
||||
Password string \`json:"password"\`
|
||||
Fingerprint string \`json:"fingerprint"\`
|
||||
DeviceName string \`json:"deviceName"\`
|
||||
DeviceType string \`json:"deviceType"\`
|
||||
}
|
||||
|
||||
func login() (map[string]any, error) {
|
||||
body, _ := json.Marshal(LoginRequest{
|
||||
Login: "user@example.com", Password: "SecurePass123",
|
||||
Fingerprint: "device-fp-uuid", DeviceName: "Chrome на Windows", DeviceType: "WEB",
|
||||
})
|
||||
resp, err := http.Post("${API_BASE}/auth/login/password", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var session map[string]any
|
||||
return session, json.NewDecoder(resp.Body).Decode(&session)
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'rust',
|
||||
label: 'Rust',
|
||||
language: 'rust',
|
||||
code: `use reqwest::Client;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), reqwest::Error> {
|
||||
let client = Client::new();
|
||||
let response = client
|
||||
.post("${API_BASE}/auth/login/password")
|
||||
.json(&json!({
|
||||
"login": "user@example.com",
|
||||
"password": "SecurePass123",
|
||||
"fingerprint": "device-fp-uuid",
|
||||
"deviceName": "Chrome на Windows",
|
||||
"deviceType": "WEB"
|
||||
}))
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
|
||||
let session: serde_json::Value = response.json().await?;
|
||||
println!("{}", session["accessToken"]);
|
||||
Ok(())
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'ruby',
|
||||
label: 'Ruby',
|
||||
language: 'ruby',
|
||||
code: `require 'net/http'
|
||||
require 'json'
|
||||
require 'uri'
|
||||
|
||||
uri = URI('${API_BASE}/auth/login/password')
|
||||
request = Net::HTTP::Post.new(uri)
|
||||
request['Content-Type'] = 'application/json'
|
||||
request.body = {
|
||||
login: 'user@example.com',
|
||||
password: 'SecurePass123',
|
||||
fingerprint: SecureRandom.uuid,
|
||||
deviceName: 'Chrome на Windows',
|
||||
deviceType: 'WEB'
|
||||
}.to_json
|
||||
|
||||
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
|
||||
http.request(request)
|
||||
end
|
||||
|
||||
raise response.body unless response.is_a?(Net::HTTPSuccess)
|
||||
session = JSON.parse(response.body)`
|
||||
},
|
||||
{
|
||||
id: 'java',
|
||||
label: 'Java',
|
||||
language: 'java',
|
||||
code: `import java.net.URI;
|
||||
import java.net.http.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
var body = """
|
||||
{
|
||||
"login": "user@example.com",
|
||||
"password": "SecurePass123",
|
||||
"fingerprint": "device-fp-uuid",
|
||||
"deviceName": "Chrome на Windows",
|
||||
"deviceType": "WEB"
|
||||
}
|
||||
""";
|
||||
|
||||
var request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("${API_BASE}/auth/login/password"))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
var response = HttpClient.newHttpClient()
|
||||
.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() >= 400) {
|
||||
throw new RuntimeException(response.body());
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'csharp',
|
||||
label: 'C#',
|
||||
language: 'csharp',
|
||||
code: `using System.Net.Http.Json;
|
||||
|
||||
using var http = new HttpClient();
|
||||
|
||||
var payload = new {
|
||||
login = "user@example.com",
|
||||
password = "SecurePass123",
|
||||
fingerprint = Guid.NewGuid().ToString(),
|
||||
deviceName = "Chrome на Windows",
|
||||
deviceType = "WEB"
|
||||
};
|
||||
|
||||
var response = await http.PostAsJsonAsync("${API_BASE}/auth/login/password", payload);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var session = await response.Content.ReadFromJsonAsync<Dictionary<string, object>>();`
|
||||
},
|
||||
{
|
||||
id: 'kotlin',
|
||||
label: 'Kotlin',
|
||||
language: 'kotlin',
|
||||
code: `import io.ktor.client.*
|
||||
import io.ktor.client.request.*
|
||||
import io.ktor.client.statement.*
|
||||
import io.ktor.http.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class LoginRequest(
|
||||
val login: String,
|
||||
val password: String,
|
||||
val fingerprint: String,
|
||||
val deviceName: String,
|
||||
val deviceType: String
|
||||
)
|
||||
|
||||
suspend fun login(client: HttpClient): String {
|
||||
val response = client.post("${API_BASE}/auth/login/password") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(LoginRequest(
|
||||
login = "user@example.com",
|
||||
password = "SecurePass123",
|
||||
fingerprint = "device-fp-uuid",
|
||||
deviceName = "Chrome на Windows",
|
||||
deviceType = "WEB"
|
||||
))
|
||||
}
|
||||
if (!response.status.isSuccess()) error(response.bodyAsText())
|
||||
return response.bodyAsText()
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'swift',
|
||||
label: 'Swift',
|
||||
language: 'swift',
|
||||
code: `import Foundation
|
||||
|
||||
struct LoginRequest: Encodable {
|
||||
let login: String
|
||||
let password: String
|
||||
let fingerprint: String
|
||||
let deviceName: String
|
||||
let deviceType: String
|
||||
}
|
||||
|
||||
var request = URLRequest(url: URL(string: "${API_BASE}/auth/login/password")!)
|
||||
request.httpMethod = "POST"
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
request.httpBody = try JSONEncoder().encode(LoginRequest(
|
||||
login: "user@example.com",
|
||||
password: "SecurePass123",
|
||||
fingerprint: UUID().uuidString,
|
||||
deviceName: "Chrome на Windows",
|
||||
deviceType: "WEB"
|
||||
))
|
||||
|
||||
let (data, response) = try await URLSession.shared.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
|
||||
throw URLError(.badServerResponse)
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'dart',
|
||||
label: 'Dart',
|
||||
language: 'dart',
|
||||
code: `import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
Future<Map<String, dynamic>> login() async {
|
||||
final response = await http.post(
|
||||
Uri.parse('${API_BASE}/auth/login/password'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'login': 'user@example.com',
|
||||
'password': 'SecurePass123',
|
||||
'fingerprint': 'device-fp-uuid',
|
||||
'deviceName': 'Chrome на Windows',
|
||||
'deviceType': 'WEB',
|
||||
}),
|
||||
);
|
||||
|
||||
if (response.statusCode >= 400) {
|
||||
throw Exception(response.body);
|
||||
}
|
||||
return jsonDecode(response.body) as Map<String, dynamic>;
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'elixir',
|
||||
label: 'Elixir',
|
||||
language: 'elixir',
|
||||
code: `payload = Jason.encode!(%{
|
||||
login: "user@example.com",
|
||||
password: "SecurePass123",
|
||||
fingerprint: Ecto.UUID.generate(),
|
||||
deviceName: "Chrome на Windows",
|
||||
deviceType: "WEB"
|
||||
})
|
||||
|
||||
{:ok, %{status: status, body: body}} =
|
||||
Req.post("${API_BASE}/auth/login/password",
|
||||
headers: [{"content-type", "application/json"}],
|
||||
body: payload
|
||||
)
|
||||
|
||||
if status >= 400, do: raise(body)
|
||||
session = Jason.decode!(body)`
|
||||
},
|
||||
{
|
||||
id: 'powershell',
|
||||
label: 'PowerShell',
|
||||
language: 'powershell',
|
||||
code: [
|
||||
'$body = @{',
|
||||
" login = 'user@example.com'",
|
||||
" password = 'SecurePass123'",
|
||||
' fingerprint = [guid]::NewGuid().ToString()',
|
||||
" deviceName = 'Chrome на Windows'",
|
||||
" deviceType = 'WEB'",
|
||||
'} | ConvertTo-Json',
|
||||
'',
|
||||
'$response = Invoke-RestMethod `',
|
||||
' -Method Post `',
|
||||
` -Uri '${API_BASE}/auth/login/password' \``,
|
||||
" -ContentType 'application/json' `",
|
||||
' -Body $body',
|
||||
'',
|
||||
'$response.accessToken'
|
||||
].join('\n')
|
||||
}
|
||||
];
|
||||
|
||||
export const authLdapExamples: CodeExample[] = [
|
||||
{
|
||||
id: 'curl-ldap',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `curl -X POST ${API_BASE}/auth/ldap/login \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"username": "ivan.petrov",
|
||||
"password": "ldap-password",
|
||||
"fingerprint": "device-fp-uuid",
|
||||
"deviceName": "Chrome",
|
||||
"deviceType": "WEB"
|
||||
}'`
|
||||
},
|
||||
{
|
||||
id: 'javascript-ldap',
|
||||
label: 'JavaScript',
|
||||
language: 'javascript',
|
||||
code: `const response = await fetch('${API_BASE}/auth/ldap/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: 'ivan.petrov',
|
||||
password: 'ldap-password',
|
||||
fingerprint: crypto.randomUUID(),
|
||||
deviceName: 'Chrome',
|
||||
deviceType: 'WEB'
|
||||
})
|
||||
});
|
||||
const session = await response.json();`
|
||||
},
|
||||
{
|
||||
id: 'python-ldap',
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import requests
|
||||
|
||||
session = requests.post('${API_BASE}/auth/ldap/login', json={
|
||||
'username': 'ivan.petrov',
|
||||
'password': 'ldap-password',
|
||||
'fingerprint': 'device-fp-uuid',
|
||||
'deviceName': 'Chrome',
|
||||
'deviceType': 'WEB',
|
||||
}, timeout=15).json()`
|
||||
},
|
||||
{
|
||||
id: 'php-ldap',
|
||||
label: 'PHP',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
$ch = curl_init('${API_BASE}/auth/ldap/login');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_POSTFIELDS => json_encode([
|
||||
'username' => 'ivan.petrov',
|
||||
'password' => 'ldap-password',
|
||||
'fingerprint' => bin2hex(random_bytes(16)),
|
||||
'deviceName' => 'Chrome',
|
||||
'deviceType' => 'WEB',
|
||||
]),
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
]);
|
||||
$session = json_decode(curl_exec($ch), true);
|
||||
curl_close($ch);`
|
||||
},
|
||||
{
|
||||
id: 'go-ldap',
|
||||
label: 'Go',
|
||||
language: 'go',
|
||||
code: `body, _ := json.Marshal(map[string]string{
|
||||
"username": "ivan.petrov", "password": "ldap-password",
|
||||
"fingerprint": "device-fp-uuid", "deviceName": "Chrome", "deviceType": "WEB",
|
||||
})
|
||||
resp, _ := http.Post("${API_BASE}/auth/ldap/login", "application/json", bytes.NewReader(body))
|
||||
defer resp.Body.Close()
|
||||
json.NewDecoder(resp.Body).Decode(&session)`
|
||||
},
|
||||
{
|
||||
id: 'rust-ldap',
|
||||
label: 'Rust',
|
||||
language: 'rust',
|
||||
code: `let session = reqwest::Client::new()
|
||||
.post("${API_BASE}/auth/ldap/login")
|
||||
.json(&serde_json::json!({
|
||||
"username": "ivan.petrov",
|
||||
"password": "ldap-password",
|
||||
"fingerprint": "device-fp-uuid",
|
||||
"deviceName": "Chrome",
|
||||
"deviceType": "WEB"
|
||||
}))
|
||||
.send().await?
|
||||
.json::<serde_json::Value>().await?;`
|
||||
}
|
||||
];
|
||||
6
apps/docs/lib/code-example.ts
Normal file
6
apps/docs/lib/code-example.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export interface CodeExample {
|
||||
id: string;
|
||||
label: string;
|
||||
language: string;
|
||||
code: string;
|
||||
}
|
||||
615
apps/docs/lib/docs-pages.ts
Normal file
615
apps/docs/lib/docs-pages.ts
Normal file
@@ -0,0 +1,615 @@
|
||||
export type DocBlock =
|
||||
| { type: 'paragraph'; text: string }
|
||||
| { type: 'list'; items: string[] }
|
||||
| { type: 'code'; language: string; code: string; title?: string }
|
||||
| { type: 'callout'; variant: 'info' | 'warning' | 'tip'; title: string; text: string }
|
||||
| { type: 'table'; headers: string[]; rows: string[][] }
|
||||
| { type: 'oauth-examples' }
|
||||
| { type: 'auth-login-examples' }
|
||||
| { type: 'auth-ldap-examples' }
|
||||
| { type: 'api-reference' };
|
||||
|
||||
export interface DocSection {
|
||||
id: string;
|
||||
title: string;
|
||||
blocks: DocBlock[];
|
||||
}
|
||||
|
||||
export interface DocPage {
|
||||
slug: string;
|
||||
title: string;
|
||||
description: string;
|
||||
sections: DocSection[];
|
||||
}
|
||||
|
||||
export const docPages: DocPage[] = [
|
||||
{
|
||||
slug: 'getting-started',
|
||||
title: 'Начало работы',
|
||||
description: 'Обзор экосистемы Identity Provider, порты сервисов и быстрый локальный запуск.',
|
||||
sections: [
|
||||
{
|
||||
id: 'overview',
|
||||
title: 'Обзор',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Lendry ID — enterprise Identity Provider в стиле Yandex ID: единый аккаунт, OAuth 2.0, LDAP/LDAPS, семейные группы, чат, PIN-блокировка сессий и админ-панель. Монорепозиторий состоит из NestJS-микросервисов, Go-сервисов и Next.js-приложений.'
|
||||
},
|
||||
{
|
||||
type: 'callout',
|
||||
variant: 'info',
|
||||
title: 'Домен',
|
||||
text: 'Production-домен: id.lendry.ru. Локально API доступен на порту 3000, frontend — 3002, документация — 3003.'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'requirements',
|
||||
title: 'Требования',
|
||||
blocks: [
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'Node.js 20.19+ и npm 10+',
|
||||
'Docker и Docker Compose',
|
||||
'PostgreSQL 16, Redis 7, RabbitMQ 3.13, MinIO',
|
||||
'Go 1.23+ (для локальной сборки media-ws и ldap-auth)'
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'quick-start',
|
||||
title: 'Быстрый запуск',
|
||||
blocks: [
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
title: 'Локально через Docker',
|
||||
code: `git clone <repository-url> lendry-id
|
||||
cd lendry-id
|
||||
docker compose up -d --build
|
||||
|
||||
# Проверка
|
||||
curl http://localhost:3000/health
|
||||
curl http://localhost:3003/docs/getting-started`
|
||||
},
|
||||
{
|
||||
type: 'table',
|
||||
headers: ['Сервис', 'Порт', 'Назначение'],
|
||||
rows: [
|
||||
['api-gateway', '3000', 'REST API, Swagger'],
|
||||
['sso-core', '3001 / 50051', 'Бизнес-логика, gRPC'],
|
||||
['frontend', '3002', 'UI входа и профиля'],
|
||||
['docs', '3003', 'Документация'],
|
||||
['media-ws', '8085', 'WebSocket уведомлений и чата'],
|
||||
['ldap-auth', '8086', 'LDAP/LDAPS аутентификация'],
|
||||
['MinIO', '9000 / 9001', 'Хранилище медиа'],
|
||||
['RabbitMQ', '5672 / 15672', 'Очереди событий']
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'first-user',
|
||||
title: 'Первый пользователь',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Первый зарегистрированный пользователь автоматически получает права супер-администратора (isSuperAdmin). Race condition защищена Redis-lock и Serializable-транзакцией PostgreSQL.'
|
||||
},
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
title: 'Регистрация через API',
|
||||
code: `curl -X POST http://localhost:3000/auth/register \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"displayName":"Администратор","email":"admin@example.com","password":"SecurePass123"}'`
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'architecture',
|
||||
title: 'Архитектура',
|
||||
description: 'Схема микросервисов, потоки данных и технологический стек.',
|
||||
sections: [
|
||||
{
|
||||
id: 'stack',
|
||||
title: 'Технологический стек',
|
||||
blocks: [
|
||||
{
|
||||
type: 'table',
|
||||
headers: ['Компонент', 'Технологии'],
|
||||
rows: [
|
||||
['sso-core', 'NestJS, Prisma 7+, PostgreSQL, gRPC'],
|
||||
['api-gateway', 'NestJS, REST, Swagger'],
|
||||
['frontend / docs', 'Next.js App Router, React, Tailwind, shadcn/ui'],
|
||||
['media-ws', 'Go, Gorilla WebSocket, Redis, RabbitMQ'],
|
||||
['ldap-auth', 'Go, go-ldap'],
|
||||
['Инфраструктура', 'Docker, Redis, RabbitMQ, MinIO']
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'flow',
|
||||
title: 'Поток запросов',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Клиент (браузер или стороннее приложение) обращается к api-gateway по REST. Gateway проксирует вызовы в sso-core через gRPC. Медиафайлы загружаются в MinIO через presigned URL. Realtime-события (уведомления, чат) доставляются через media-ws по WebSocket с JWT-авторизацией.'
|
||||
},
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'JWT access + refresh tokens для сессий',
|
||||
'PIN-код: при включении сессия создаётся с pinVerified=false',
|
||||
'SystemSetting — динамические бизнес-правила без хардкода во frontend',
|
||||
'LinkedAccount — привязка LDAP, Google, Yandex и других провайдеров'
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'deployment',
|
||||
title: 'Развёртывание на сервере',
|
||||
description: 'Пошаговый гайд по production-развёртыванию на Linux-сервере с Docker, Nginx и TLS.',
|
||||
sections: [
|
||||
{
|
||||
id: 'server-requirements',
|
||||
title: '1. Требования к серверу',
|
||||
blocks: [
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'Ubuntu 22.04+ / Debian 12+ / аналогичный Linux',
|
||||
'Минимум 4 GB RAM, 2 vCPU, 40 GB SSD',
|
||||
'Домен с DNS A-записью (например id.lendry.ru)',
|
||||
'Открытые порты 80 и 443 (остальное — только localhost / internal network)'
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'install-docker',
|
||||
title: '2. Установка Docker',
|
||||
blocks: [
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
code: `sudo apt update && sudo apt install -y ca-certificates curl gnupg
|
||||
curl -fsSL https://get.docker.com | sudo sh
|
||||
sudo usermod -aG docker $USER
|
||||
docker compose version`
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'clone-config',
|
||||
title: '3. Клонирование и переменные окружения',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Создайте файл .env в корне проекта с production-секретами. Никогда не коммитьте его в git.'
|
||||
},
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
title: '.env (пример)',
|
||||
code: `# Секреты JWT и шифрования — сгенерируйте: openssl rand -base64 48
|
||||
JWT_ACCESS_SECRET=your-long-access-secret
|
||||
JWT_REFRESH_SECRET=your-long-refresh-secret
|
||||
DATA_ENCRYPTION_KEY=your-32-byte-encryption-key-change-me
|
||||
|
||||
# PostgreSQL (можно оставить docker internal)
|
||||
POSTGRES_USER=lendry
|
||||
POSTGRES_PASSWORD=strong-db-password
|
||||
POSTGRES_DB=lendry_id
|
||||
|
||||
# RabbitMQ
|
||||
RABBITMQ_DEFAULT_USER=lendry
|
||||
RABBITMQ_DEFAULT_PASS=strong-rmq-password
|
||||
|
||||
# MinIO
|
||||
MINIO_ROOT_USER=minioadmin
|
||||
MINIO_ROOT_PASSWORD=strong-minio-password`
|
||||
},
|
||||
{
|
||||
type: 'callout',
|
||||
variant: 'warning',
|
||||
title: 'PUBLIC_API_URL',
|
||||
text: 'В production задайте PUBLIC_API_URL=https://id.lendry.ru для sso-core и api-gateway, а также MINIO_PUBLIC_ENDPOINT=id.lendry.ru (или CDN-домен для MinIO).'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'docker-compose-prod',
|
||||
title: '4. Production docker-compose',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Для production рекомендуется не публиковать PostgreSQL, Redis и RabbitMQ наружу — оставьте только api-gateway (3000), frontend (3002) и docs (3003) за reverse proxy.'
|
||||
},
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
code: `export DOCKER_BUILDKIT=1
|
||||
docker compose up -d --build
|
||||
|
||||
# Проверка health всех сервисов
|
||||
docker compose ps
|
||||
docker compose logs -f sso-core api-gateway`
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'nginx',
|
||||
title: '5. Nginx + TLS (Let\'s Encrypt)',
|
||||
blocks: [
|
||||
{
|
||||
type: 'code',
|
||||
language: 'nginx',
|
||||
title: '/etc/nginx/sites-available/id.lendry.ru',
|
||||
code: `server {
|
||||
listen 443 ssl http2;
|
||||
server_name id.lendry.ru;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/id.lendry.ru/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/id.lendry.ru/privkey.pem;
|
||||
|
||||
# REST API + Swagger
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Frontend UI
|
||||
location /app/ {
|
||||
proxy_pass http://127.0.0.1:3002/;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
# WebSocket
|
||||
location /ws {
|
||||
proxy_pass http://127.0.0.1:8085;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
}
|
||||
|
||||
# Документация на docs.id.lendry.ru или /docs-proxy
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name docs.id.lendry.ru;
|
||||
ssl_certificate /etc/letsencrypt/live/docs.id.lendry.ru/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/docs.id.lendry.ru/privkey.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3003;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
}`
|
||||
},
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
code: `sudo certbot --nginx -d id.lendry.ru -d docs.id.lendry.ru
|
||||
sudo nginx -t && sudo systemctl reload nginx`
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'env-services',
|
||||
title: '6. Переменные окружения сервисов',
|
||||
blocks: [
|
||||
{
|
||||
type: 'table',
|
||||
headers: ['Сервис', 'Ключевые переменные'],
|
||||
rows: [
|
||||
['sso-core', 'DATABASE_URL, JWT_*_SECRET, DATA_ENCRYPTION_KEY, REDIS_URL, RABBITMQ_URL, MINIO_*, LDAP_AUTH_URL, PUBLIC_API_URL'],
|
||||
['api-gateway', 'SSO_CORE_GRPC_URL, JWT_ACCESS_SECRET, PUBLIC_API_URL, MINIO_*'],
|
||||
['frontend', 'NEXT_PUBLIC_API_URL, NEXT_PUBLIC_WS_URL'],
|
||||
['docs', 'NEXT_PUBLIC_API_URL'],
|
||||
['media-ws', 'REDIS_ADDR, RABBITMQ_URL, JWT_ACCESS_SECRET'],
|
||||
['ldap-auth', 'PORT=8086']
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'migrations',
|
||||
title: '7. Миграции и seed',
|
||||
blocks: [
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
code: `# Prisma migrate внутри контейнера sso-core
|
||||
docker compose exec sso-core npx prisma migrate deploy
|
||||
|
||||
# Seed системных настроек (PROJECT_NAME, LDAP_*, PIN_*)
|
||||
docker compose restart sso-core`
|
||||
},
|
||||
{
|
||||
type: 'callout',
|
||||
variant: 'tip',
|
||||
title: 'SystemSetting',
|
||||
text: 'Название проекта (PROJECT_NAME), tagline и LDAP-параметры настраиваются в админке: /admin/settings. Frontend и docs подтягивают PROJECT_NAME через GET /settings/public.'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'backup',
|
||||
title: '8. Резервное копирование',
|
||||
blocks: [
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'PostgreSQL: pg_dump lendry_id ежедневно',
|
||||
'MinIO: mc mirror или snapshot volume minio_data',
|
||||
'Redis: RDB/AOF snapshots при необходимости сохранения сессий',
|
||||
'Секреты .env — хранить в vault, не в репозитории'
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'code',
|
||||
language: 'bash',
|
||||
code: `docker compose exec postgres pg_dump -U lendry lendry_id > backup-$(date +%F).sql`
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'monitoring',
|
||||
title: '9. Мониторинг и обновления',
|
||||
blocks: [
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'Health: GET /health на api-gateway и sso-core',
|
||||
'Логи: docker compose logs -f --tail=200',
|
||||
'Обновление: git pull && docker compose up -d --build',
|
||||
'Zero-downtime: blue-green или rolling update через orchestrator (K8s / Swarm)'
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'authentication',
|
||||
title: 'Аутентификация',
|
||||
description: 'Способы входа: пароль, OTP, LDAP, PIN и refresh-сессии.',
|
||||
sections: [
|
||||
{
|
||||
id: 'flows',
|
||||
title: 'Сценарии входа',
|
||||
blocks: [
|
||||
{
|
||||
type: 'table',
|
||||
headers: ['Сценарий', 'Endpoint', 'Описание'],
|
||||
rows: [
|
||||
['Identifier-first', 'POST /auth/identify', 'Проверка существования пользователя и способа входа'],
|
||||
['Passwordless OTP', 'POST /auth/otp/send + verify', '6-значный код на почту/телефон'],
|
||||
['Пароль', 'POST /auth/login/password', 'Логин + пароль или tempAuthToken после OTP'],
|
||||
['LDAP/LDAPS', 'POST /auth/ldap/login', 'Корпоративный вход (требует LDAP_ENABLED)'],
|
||||
['PIN', 'POST /auth/pin/verify', 'Разблокировка сессии после входа с PIN']
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'login-example',
|
||||
title: 'Примеры входа по паролю',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Endpoint POST /auth/login/password принимает login (почта, телефон или username), password и метаданные устройства. Ниже — готовые примеры на разных языках.'
|
||||
},
|
||||
{ type: 'auth-login-examples' },
|
||||
{
|
||||
type: 'callout',
|
||||
variant: 'info',
|
||||
title: 'PIN-блокировка',
|
||||
text: 'Если у пользователя включён PIN, ответ содержит requiresPin=true и ограниченную сессию. Полный JWT выдаётся после POST /auth/pin/verify.'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'oauth',
|
||||
title: 'OAuth 2.0',
|
||||
description: 'Регистрация приложения, Authorization Code Flow, scopes и примеры на разных языках.',
|
||||
sections: [
|
||||
{
|
||||
id: 'register-app',
|
||||
title: 'Регистрация OAuth-приложения',
|
||||
blocks: [
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'Войдите как супер-администратор в админ-панель',
|
||||
'Перейдите в RBAC → OAuth приложения',
|
||||
'Создайте клиент: name, redirectUris, scopes (openid, profile, email)',
|
||||
'Confidential-клиент получит client_secret один раз — сохраните его'
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'flow',
|
||||
title: 'Authorization Code Flow',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: '1) Пользователь авторизуется в Lendry ID. 2) Ваше приложение перенаправляет на GET /oauth/authorize с clientId, redirectUri, scope, userId. 3) IdP возвращает redirectUrl с authorization code. 4) Backend обменивает code на токены через POST /oauth/token. 5) GET /oauth/userinfo возвращает профиль.'
|
||||
},
|
||||
{
|
||||
type: 'callout',
|
||||
variant: 'warning',
|
||||
title: 'Безопасность',
|
||||
text: 'client_secret никогда не храните во frontend. Обмен code → token выполняйте только на сервере.'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'examples',
|
||||
title: 'Примеры интеграции',
|
||||
blocks: [{ type: 'oauth-examples' }]
|
||||
},
|
||||
{
|
||||
id: 'scopes',
|
||||
title: 'Scopes',
|
||||
blocks: [
|
||||
{
|
||||
type: 'table',
|
||||
headers: ['Scope', 'Доступ'],
|
||||
rows: [
|
||||
['openid', 'Идентификатор пользователя (sub)'],
|
||||
['profile', 'displayName, avatar, bio'],
|
||||
['email', 'Основная и резервная почта'],
|
||||
['phone', 'Телефоны пользователя']
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'ldap',
|
||||
title: 'LDAP / LDAPS',
|
||||
description: 'Корпоративный вход через Active Directory.',
|
||||
sections: [
|
||||
{
|
||||
id: 'setup',
|
||||
title: 'Настройка в админке',
|
||||
blocks: [
|
||||
{
|
||||
type: 'table',
|
||||
headers: ['Ключ SystemSetting', 'Описание'],
|
||||
rows: [
|
||||
['LDAP_ENABLED', 'Включить кнопку «Войти через LDAP»'],
|
||||
['LDAP_USE_LDAPS', 'LDAPS на порту 636'],
|
||||
['LDAP_HOST', 'DC-1.domain.local,DC-2.domain.local'],
|
||||
['LDAP_BIND_USERNAME', 'Логин сервисной УЗ (mvkadmin)'],
|
||||
['LDAP_BASE_DN', 'OU=Users,DC=domain,DC=local'],
|
||||
['LDAP_BIND_PASSWORD', 'Пароль сервисной УЗ']
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'login',
|
||||
title: 'Примеры LDAP-входа',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Endpoint POST /auth/ldap/login доступен при включённой настройке LDAP_ENABLED.'
|
||||
},
|
||||
{ type: 'auth-ldap-examples' }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'sessions',
|
||||
title: 'Сессии и PIN',
|
||||
description: 'Управление устройствами, PIN-блокировка и отзыв сессий.',
|
||||
sections: [
|
||||
{
|
||||
id: 'pin',
|
||||
title: 'PIN-код',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'PIN хранится как bcrypt hash. Таймаут блокировки читается из SystemSetting PIN_LOCK_TIMEOUT_MINUTES — значение не захардкожено во frontend.'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'devices',
|
||||
title: 'Устройства и сессии',
|
||||
blocks: [
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'GET /security/users/{userId}/devices — список устройств',
|
||||
'POST /security/users/{userId}/sessions/{sessionId}/revoke — выход с устройства',
|
||||
'POST /security/users/{userId}/revoke-all-sessions — выход везде'
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'family-chat',
|
||||
title: 'Семья и чат',
|
||||
description: 'Семейные группы, приглашения, чат и realtime через WebSocket.',
|
||||
sections: [
|
||||
{
|
||||
id: 'family',
|
||||
title: 'Семейные группы',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Пользователь создаёт семью, приглашает участников по email/телефону/логину. Лимиты (max family members) берутся из SystemSetting.'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'chat',
|
||||
title: 'Чат и WebSocket',
|
||||
blocks: [
|
||||
{
|
||||
type: 'list',
|
||||
items: [
|
||||
'REST: /chat/groups/{groupId}/rooms, /chat/rooms/{roomId}/messages',
|
||||
'WebSocket: ws://localhost:8085/ws с JWT в query или заголовке',
|
||||
'Медиа чата: presigned upload + защищённый stream с Authorization'
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
slug: 'api-reference',
|
||||
title: 'Справочник API',
|
||||
description: 'Полный список REST endpoints Lendry ID API. Swagger: /api на api-gateway.',
|
||||
sections: [
|
||||
{
|
||||
id: 'endpoints',
|
||||
title: 'Endpoints',
|
||||
blocks: [{ type: 'api-reference' }]
|
||||
},
|
||||
{
|
||||
id: 'swagger',
|
||||
title: 'OpenAPI / Swagger',
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: 'Интерактивная документация доступна по адресу http://localhost:3000/api (Swagger UI). Все DTO и схемы генерируются автоматически из NestJS decorators.'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
export function getDocPage(slug: string): DocPage | undefined {
|
||||
return docPages.find((page) => page.slug === slug);
|
||||
}
|
||||
|
||||
export function getAllDocSlugs() {
|
||||
return docPages.map((page) => page.slug);
|
||||
}
|
||||
31
apps/docs/lib/navigation.ts
Normal file
31
apps/docs/lib/navigation.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
export interface DocNavItem {
|
||||
slug: string;
|
||||
title: string;
|
||||
group: string;
|
||||
}
|
||||
|
||||
export const docNavigation: DocNavItem[] = [
|
||||
{ slug: 'getting-started', title: 'Начало работы', group: 'Введение' },
|
||||
{ slug: 'architecture', title: 'Архитектура', group: 'Введение' },
|
||||
{ slug: 'deployment', title: 'Развёртывание на сервере', group: 'Введение' },
|
||||
{ slug: 'authentication', title: 'Аутентификация', group: 'Интеграция' },
|
||||
{ slug: 'oauth', title: 'OAuth 2.0', group: 'Интеграция' },
|
||||
{ slug: 'ldap', title: 'LDAP / LDAPS', group: 'Интеграция' },
|
||||
{ slug: 'sessions', title: 'Сессии и PIN', group: 'Безопасность' },
|
||||
{ slug: 'family-chat', title: 'Семья и чат', group: 'Функции' },
|
||||
{ slug: 'api-reference', title: 'Справочник API', group: 'Справочник' }
|
||||
];
|
||||
|
||||
export function getDocNavItem(slug: string) {
|
||||
return docNavigation.find((item) => item.slug === slug);
|
||||
}
|
||||
|
||||
export function groupDocNavigation(items: DocNavItem[]) {
|
||||
const groups = new Map<string, DocNavItem[]>();
|
||||
for (const item of items) {
|
||||
const list = groups.get(item.group) ?? [];
|
||||
list.push(item);
|
||||
groups.set(item.group, list);
|
||||
}
|
||||
return Array.from(groups.entries());
|
||||
}
|
||||
273
apps/docs/lib/oauth-examples.ts
Normal file
273
apps/docs/lib/oauth-examples.ts
Normal file
@@ -0,0 +1,273 @@
|
||||
export interface OAuthExample {
|
||||
id: string;
|
||||
label: string;
|
||||
language: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
const API_BASE = 'https://id.lendry.ru';
|
||||
|
||||
export const oauthExamples: OAuthExample[] = [
|
||||
{
|
||||
id: 'javascript',
|
||||
label: 'JavaScript',
|
||||
language: 'javascript',
|
||||
code: `// Authorization Code Flow (Node.js / браузер)
|
||||
const clientId = 'YOUR_CLIENT_ID';
|
||||
const redirectUri = 'https://app.example.com/oauth/callback';
|
||||
const scope = 'openid profile email';
|
||||
const state = crypto.randomUUID();
|
||||
|
||||
// Шаг 1: перенаправить пользователя на IdP
|
||||
const authorizeUrl = new URL('${API_BASE}/oauth/authorize');
|
||||
authorizeUrl.searchParams.set('userId', 'USER_ID_AFTER_LOGIN');
|
||||
authorizeUrl.searchParams.set('clientId', clientId);
|
||||
authorizeUrl.searchParams.set('redirectUri', redirectUri);
|
||||
authorizeUrl.searchParams.set('scope', scope);
|
||||
authorizeUrl.searchParams.set('state', state);
|
||||
window.location.href = authorizeUrl.toString();
|
||||
|
||||
// Шаг 2: обменять code на токены (на backend!)
|
||||
const tokenResponse = await fetch('${API_BASE}/oauth/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
grantType: 'authorization_code',
|
||||
code: 'AUTHORIZATION_CODE',
|
||||
clientId,
|
||||
clientSecret: 'YOUR_CLIENT_SECRET',
|
||||
redirectUri
|
||||
})
|
||||
});
|
||||
const tokens = await tokenResponse.json();
|
||||
|
||||
// Шаг 3: получить профиль
|
||||
const profile = await fetch('${API_BASE}/oauth/userinfo', {
|
||||
headers: { Authorization: \`Bearer \${tokens.accessToken}\` }
|
||||
}).then((r) => r.json());`
|
||||
},
|
||||
{
|
||||
id: 'typescript-next',
|
||||
label: 'Next.js',
|
||||
language: 'typescript',
|
||||
code: `// app/api/oauth/callback/route.ts
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const code = request.nextUrl.searchParams.get('code');
|
||||
const state = request.nextUrl.searchParams.get('state');
|
||||
if (!code) return NextResponse.redirect('/login?error=oauth');
|
||||
|
||||
const tokenRes = await fetch('${API_BASE}/oauth/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
grantType: 'authorization_code',
|
||||
code,
|
||||
clientId: process.env.OAUTH_CLIENT_ID,
|
||||
clientSecret: process.env.OAUTH_CLIENT_SECRET,
|
||||
redirectUri: process.env.OAUTH_REDIRECT_URI
|
||||
})
|
||||
});
|
||||
|
||||
const tokens = await tokenRes.json();
|
||||
const response = NextResponse.redirect('/dashboard');
|
||||
response.cookies.set('access_token', tokens.accessToken, { httpOnly: true, secure: true });
|
||||
return response;
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'python',
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import requests
|
||||
from urllib.parse import urlencode
|
||||
|
||||
API_BASE = '${API_BASE}'
|
||||
CLIENT_ID = 'YOUR_CLIENT_ID'
|
||||
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
|
||||
REDIRECT_URI = 'https://app.example.com/oauth/callback'
|
||||
|
||||
# Ссылка для входа пользователя
|
||||
params = urlencode({
|
||||
'userId': 'USER_ID',
|
||||
'clientId': CLIENT_ID,
|
||||
'redirectUri': REDIRECT_URI,
|
||||
'scope': 'openid profile email',
|
||||
'state': 'random-state'
|
||||
})
|
||||
authorize_url = f'{API_BASE}/oauth/authorize?{params}'
|
||||
|
||||
# Обмен authorization code на токены
|
||||
token_response = requests.post(f'{API_BASE}/oauth/token', json={
|
||||
'grantType': 'authorization_code',
|
||||
'code': 'AUTHORIZATION_CODE',
|
||||
'clientId': CLIENT_ID,
|
||||
'clientSecret': CLIENT_SECRET,
|
||||
'redirectUri': REDIRECT_URI
|
||||
}, timeout=15)
|
||||
tokens = token_response.json()
|
||||
|
||||
# UserInfo
|
||||
profile = requests.get(
|
||||
f'{API_BASE}/oauth/userinfo',
|
||||
headers={'Authorization': f"Bearer {tokens['accessToken']}"},
|
||||
timeout=15
|
||||
).json()`
|
||||
},
|
||||
{
|
||||
id: 'php',
|
||||
label: 'PHP',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
$apiBase = '${API_BASE}';
|
||||
$clientId = getenv('OAUTH_CLIENT_ID');
|
||||
$clientSecret = getenv('OAUTH_CLIENT_SECRET');
|
||||
$redirectUri = 'https://app.example.com/oauth/callback';
|
||||
|
||||
// Redirect пользователя
|
||||
$params = http_build_query([
|
||||
'userId' => 'USER_ID',
|
||||
'clientId' => $clientId,
|
||||
'redirectUri' => $redirectUri,
|
||||
'scope' => 'openid profile email',
|
||||
'state' => bin2hex(random_bytes(16)),
|
||||
]);
|
||||
header('Location: ' . $apiBase . '/oauth/authorize?' . $params);
|
||||
exit;
|
||||
|
||||
// Callback: обмен code -> token
|
||||
$payload = json_encode([
|
||||
'grantType' => 'authorization_code',
|
||||
'code' => $_GET['code'],
|
||||
'clientId' => $clientId,
|
||||
'clientSecret' => $clientSecret,
|
||||
'redirectUri' => $redirectUri,
|
||||
]);
|
||||
|
||||
$ch = curl_init($apiBase . '/oauth/token');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_POSTFIELDS => $payload,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
]);
|
||||
$tokens = json_decode(curl_exec($ch), true);
|
||||
curl_close($ch);
|
||||
|
||||
// UserInfo
|
||||
$ch = curl_init($apiBase . '/oauth/userinfo');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $tokens['accessToken']],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
]);
|
||||
$profile = json_decode(curl_exec($ch), true);
|
||||
curl_close($ch);`
|
||||
},
|
||||
{
|
||||
id: 'go',
|
||||
label: 'Go',
|
||||
language: 'go',
|
||||
code: `package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const apiBase = "${API_BASE}"
|
||||
|
||||
func buildAuthorizeURL(userID, clientID, redirectURI, scope, state string) string {
|
||||
q := url.Values{}
|
||||
q.Set("userId", userID)
|
||||
q.Set("clientId", clientID)
|
||||
q.Set("redirectUri", redirectURI)
|
||||
q.Set("scope", scope)
|
||||
q.Set("state", state)
|
||||
return apiBase + "/oauth/authorize?" + q.Encode()
|
||||
}
|
||||
|
||||
func exchangeCode(code, clientID, clientSecret, redirectURI string) (map[string]any, error) {
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"grantType": "authorization_code",
|
||||
"code": code,
|
||||
"clientId": clientID,
|
||||
"clientSecret": clientSecret,
|
||||
"redirectUri": redirectURI,
|
||||
})
|
||||
resp, err := http.Post(apiBase+"/oauth/token", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var tokens map[string]any
|
||||
return tokens, json.NewDecoder(resp.Body).Decode(&tokens)
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'csharp',
|
||||
label: 'C#',
|
||||
language: 'csharp',
|
||||
code: `using System.Net.Http.Json;
|
||||
|
||||
var apiBase = "${API_BASE}";
|
||||
var clientId = Environment.GetEnvironmentVariable("OAUTH_CLIENT_ID");
|
||||
var clientSecret = Environment.GetEnvironmentVariable("OAUTH_CLIENT_SECRET");
|
||||
var redirectUri = "https://app.example.com/oauth/callback";
|
||||
|
||||
// Authorization URL
|
||||
var authorizeUrl =
|
||||
$"{apiBase}/oauth/authorize?userId=USER_ID&clientId={clientId}" +
|
||||
$"&redirectUri={Uri.EscapeDataString(redirectUri)}&scope=openid profile email&state=xyz";
|
||||
|
||||
using var http = new HttpClient();
|
||||
|
||||
// Token exchange
|
||||
var tokenResponse = await http.PostAsJsonAsync($"{apiBase}/oauth/token", new {
|
||||
grantType = "authorization_code",
|
||||
code = "AUTHORIZATION_CODE",
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri
|
||||
});
|
||||
var tokens = await tokenResponse.Content.ReadFromJsonAsync<Dictionary<string, object>>();
|
||||
|
||||
// UserInfo
|
||||
http.DefaultRequestHeaders.Authorization =
|
||||
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tokens!["accessToken"].ToString());
|
||||
var profile = await http.GetFromJsonAsync<object>($"{apiBase}/oauth/userinfo");`
|
||||
},
|
||||
{
|
||||
id: 'curl',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `# Authorization (браузер пользователя)
|
||||
open "${API_BASE}/oauth/authorize?userId=USER_ID&clientId=CLIENT_ID&redirectUri=https%3A%2F%2Fapp.example.com%2Fcallback&scope=openid%20profile%20email&state=xyz"
|
||||
|
||||
# Обмен code на токены
|
||||
curl -X POST ${API_BASE}/oauth/token \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"grantType": "authorization_code",
|
||||
"code": "AUTHORIZATION_CODE",
|
||||
"clientId": "CLIENT_ID",
|
||||
"clientSecret": "CLIENT_SECRET",
|
||||
"redirectUri": "https://app.example.com/callback"
|
||||
}'
|
||||
|
||||
# UserInfo
|
||||
curl ${API_BASE}/oauth/userinfo \\
|
||||
-H "Authorization: Bearer ACCESS_TOKEN"
|
||||
|
||||
# Refresh token
|
||||
curl -X POST ${API_BASE}/oauth/token \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"grantType": "refresh_token",
|
||||
"refreshToken": "REFRESH_TOKEN",
|
||||
"clientId": "CLIENT_ID"
|
||||
}'`
|
||||
}
|
||||
];
|
||||
32
apps/docs/lib/public-settings-cache.ts
Normal file
32
apps/docs/lib/public-settings-cache.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
const STORAGE_KEY = 'docs-public-settings';
|
||||
|
||||
export function readCachedPublicSettings(): Record<string, string> {
|
||||
if (typeof window === 'undefined') {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return {};
|
||||
}
|
||||
const parsed = JSON.parse(raw) as Record<string, string>;
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function writeCachedPublicSettings(settings: Record<string, string>) {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
} catch {
|
||||
// ignore quota errors
|
||||
}
|
||||
}
|
||||
|
||||
export function mergePublicSettings(...sources: Array<Record<string, string>>): Record<string, string> {
|
||||
return Object.assign({}, ...sources);
|
||||
}
|
||||
6
apps/docs/lib/utils.ts
Normal file
6
apps/docs/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
6
apps/docs/next-env.d.ts
vendored
Normal file
6
apps/docs/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/types/routes.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
5
apps/docs/next.config.ts
Normal file
5
apps/docs/next.config.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import type { NextConfig } from 'next';
|
||||
|
||||
const nextConfig: NextConfig = {};
|
||||
|
||||
export default nextConfig;
|
||||
31
apps/docs/package.json
Normal file
31
apps/docs/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@lendry/docs",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.561.0",
|
||||
"next": "^16.0.10",
|
||||
"react": "^19.2.1",
|
||||
"react-dom": "^19.2.1",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.1.18",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
7
apps/docs/postcss.config.mjs
Normal file
7
apps/docs/postcss.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {}
|
||||
}
|
||||
};
|
||||
|
||||
export default config;
|
||||
80
apps/docs/providers/public-settings-provider.tsx
Normal file
80
apps/docs/providers/public-settings-provider.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
|
||||
import { fetchPublicSettingsClient, getDefaultProjectName, getDefaultProjectTagline } from '@/lib/api';
|
||||
import { mergePublicSettings, readCachedPublicSettings, writeCachedPublicSettings } from '@/lib/public-settings-cache';
|
||||
|
||||
interface PublicSettingsContextValue {
|
||||
projectName: string;
|
||||
projectTagline: string;
|
||||
isLoading: boolean;
|
||||
refreshPublicSettings: () => Promise<void>;
|
||||
}
|
||||
|
||||
const PublicSettingsContext = createContext<PublicSettingsContextValue>({
|
||||
projectName: getDefaultProjectName(),
|
||||
projectTagline: getDefaultProjectTagline(),
|
||||
isLoading: true,
|
||||
refreshPublicSettings: async () => undefined
|
||||
});
|
||||
|
||||
export function PublicSettingsProvider({
|
||||
children,
|
||||
initialSettings
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
initialSettings: Record<string, string>;
|
||||
}) {
|
||||
const [settings, setSettings] = useState<Record<string, string>>(() =>
|
||||
mergePublicSettings(readCachedPublicSettings(), initialSettings)
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const refreshPublicSettings = useCallback(async () => {
|
||||
try {
|
||||
const next = await fetchPublicSettingsClient();
|
||||
setSettings((current) => mergePublicSettings(current, next));
|
||||
writeCachedPublicSettings(next);
|
||||
} catch {
|
||||
// Оставляем последние известные значения (кэш или SSR).
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const cached = readCachedPublicSettings();
|
||||
if (Object.keys(cached).length > 0) {
|
||||
setSettings((current) => mergePublicSettings(cached, initialSettings, current));
|
||||
}
|
||||
}, [initialSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshPublicSettings();
|
||||
const onFocus = () => void refreshPublicSettings();
|
||||
window.addEventListener('focus', onFocus);
|
||||
return () => window.removeEventListener('focus', onFocus);
|
||||
}, [refreshPublicSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
if (settings.PROJECT_NAME) {
|
||||
document.title = `Документация — ${settings.PROJECT_NAME}`;
|
||||
}
|
||||
}, [settings.PROJECT_NAME]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
projectName: settings.PROJECT_NAME || getDefaultProjectName(),
|
||||
projectTagline: settings.PROJECT_TAGLINE || getDefaultProjectTagline(),
|
||||
isLoading,
|
||||
refreshPublicSettings
|
||||
}),
|
||||
[isLoading, refreshPublicSettings, settings.PROJECT_NAME, settings.PROJECT_TAGLINE]
|
||||
);
|
||||
|
||||
return <PublicSettingsContext.Provider value={value}>{children}</PublicSettingsContext.Provider>;
|
||||
}
|
||||
|
||||
export function usePublicSettings() {
|
||||
return useContext(PublicSettingsContext);
|
||||
}
|
||||
51
apps/docs/providers/theme-provider.tsx
Normal file
51
apps/docs/providers/theme-provider.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
type Theme = 'light' | 'dark' | 'system';
|
||||
|
||||
interface ThemeContextValue {
|
||||
theme: Theme;
|
||||
resolvedTheme: 'light' | 'dark';
|
||||
setTheme: (theme: Theme) => void;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>('system');
|
||||
const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>('light');
|
||||
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem('docs-theme') as Theme | null;
|
||||
if (stored) setThemeState(stored);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const apply = () => {
|
||||
const next = theme === 'system' ? (media.matches ? 'dark' : 'light') : theme;
|
||||
setResolvedTheme(next);
|
||||
root.classList.toggle('dark', next === 'dark');
|
||||
};
|
||||
apply();
|
||||
media.addEventListener('change', apply);
|
||||
return () => media.removeEventListener('change', apply);
|
||||
}, [theme]);
|
||||
|
||||
const setTheme = (next: Theme) => {
|
||||
setThemeState(next);
|
||||
localStorage.setItem('docs-theme', next);
|
||||
};
|
||||
|
||||
const value = useMemo(() => ({ theme, resolvedTheme, setTheme }), [theme, resolvedTheme]);
|
||||
|
||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const ctx = useContext(ThemeContext);
|
||||
if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
|
||||
return ctx;
|
||||
}
|
||||
20
apps/docs/tsconfig.json
Normal file
20
apps/docs/tsconfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"noEmit": true,
|
||||
"isolatedModules": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
},
|
||||
"plugins": [{ "name": "next" }],
|
||||
"incremental": true
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
42
apps/frontend/Dockerfile
Normal file
42
apps/frontend/Dockerfile
Normal file
@@ -0,0 +1,42 @@
|
||||
# syntax=docker/dockerfile:1.4
|
||||
|
||||
FROM node:24-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ARG NPM_REGISTRY=https://registry.npmjs.org
|
||||
ARG NEXT_PUBLIC_API_URL=http://localhost:3000
|
||||
ARG NEXT_PUBLIC_WS_URL=ws://localhost:8085/ws
|
||||
|
||||
COPY package.json package-lock.json .npmrc ./
|
||||
COPY apps/sso-core/package.json ./apps/sso-core/
|
||||
COPY apps/api-gateway/package.json ./apps/api-gateway/
|
||||
COPY apps/frontend/package.json ./apps/frontend/
|
||||
COPY apps/docs/package.json ./apps/docs/
|
||||
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm config set registry "${NPM_REGISTRY}" && \
|
||||
for i in 1 2 3 4 5; do \
|
||||
echo "npm ci: попытка $i/5" && \
|
||||
npm ci --no-audit --no-fund && exit 0; \
|
||||
echo "npm ci: ошибка сети, повтор через $((i * 15)) сек..."; \
|
||||
sleep $((i * 15)); \
|
||||
done; \
|
||||
echo "npm ci: все попытки исчерпаны"; \
|
||||
exit 1
|
||||
|
||||
COPY apps ./apps
|
||||
COPY shared ./shared
|
||||
COPY tsconfig.base.json ./
|
||||
|
||||
ENV NEXT_TELEMETRY_DISABLED="1"
|
||||
ENV PORT="3000"
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
ENV NEXT_PUBLIC_API_URL="${NEXT_PUBLIC_API_URL}"
|
||||
ENV NEXT_PUBLIC_WS_URL="${NEXT_PUBLIC_WS_URL}"
|
||||
|
||||
RUN npm --workspace @lendry/frontend run build
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["npm", "--workspace", "@lendry/frontend", "run", "start"]
|
||||
23
apps/frontend/app/admin/layout.tsx
Normal file
23
apps/frontend/app/admin/layout.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
|
||||
export default function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const { user, isLoading, isPinLocked, hasStoredSession } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoading) return;
|
||||
if (!user && !isPinLocked && !hasStoredSession) {
|
||||
router.replace('/auth/login');
|
||||
return;
|
||||
}
|
||||
if (user && !user.canAccessAdmin) {
|
||||
router.replace('/');
|
||||
}
|
||||
}, [hasStoredSession, isLoading, isPinLocked, router, user]);
|
||||
|
||||
return children;
|
||||
}
|
||||
262
apps/frontend/app/admin/oauth/page.tsx
Normal file
262
apps/frontend/app/admin/oauth/page.tsx
Normal file
@@ -0,0 +1,262 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Copy, KeyRound, Loader2, LockKeyhole, Plus, RefreshCw } from 'lucide-react';
|
||||
import { AdminShell } from '@/components/id/admin-shell';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { OAuthClient, OAuthScope, apiFetch } from '@/lib/api';
|
||||
|
||||
export default function AdminOAuthPage() {
|
||||
const { token } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const [clients, setClients] = useState<OAuthClient[]>([]);
|
||||
const [scopes, setScopes] = useState<OAuthScope[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [secretDialog, setSecretDialog] = useState<{ clientId: string; clientSecret: string } | null>(null);
|
||||
const [form, setForm] = useState({ name: '', redirectUris: '', type: 'CONFIDENTIAL', selectedScopes: ['openid', 'profile', 'email'] as string[] });
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
if (!token) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [clientsResponse, scopesResponse] = await Promise.all([
|
||||
apiFetch<{ clients: OAuthClient[] }>('/admin/rbac/oauth-clients', {}, token),
|
||||
apiFetch<{ scopes: OAuthScope[] }>('/admin/rbac/oauth-scopes', {}, token)
|
||||
]);
|
||||
setClients(clientsResponse.clients ?? []);
|
||||
setScopes(scopesResponse.scopes ?? []);
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось загрузить OAuth-приложения');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [showToast, token]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadData();
|
||||
}, [loadData]);
|
||||
|
||||
async function handleCreate() {
|
||||
if (!token) return;
|
||||
const redirectUris = form.redirectUris
|
||||
.split('\n')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
if (!form.name.trim() || !redirectUris.length || !form.selectedScopes.length) {
|
||||
showToast('Заполните название, redirect URI и scopes');
|
||||
return;
|
||||
}
|
||||
|
||||
setCreating(true);
|
||||
try {
|
||||
const created = await apiFetch<OAuthClient>('/admin/rbac/oauth-clients', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name: form.name.trim(),
|
||||
redirectUris,
|
||||
scopes: form.selectedScopes,
|
||||
type: form.type
|
||||
})
|
||||
}, token);
|
||||
showToast('OAuth-приложение создано');
|
||||
setDialogOpen(false);
|
||||
setForm({ name: '', redirectUris: '', type: 'CONFIDENTIAL', selectedScopes: ['openid', 'profile', 'email'] });
|
||||
if (created.clientSecret) {
|
||||
setSecretDialog({ clientId: created.clientId, clientSecret: created.clientSecret });
|
||||
}
|
||||
await loadData();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось создать приложение');
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRotateSecret(clientId: string) {
|
||||
if (!token) return;
|
||||
try {
|
||||
const response = await apiFetch<{ clientId: string; clientSecret: string }>(`/admin/rbac/oauth-clients/${clientId}/rotate-secret`, { method: 'POST' }, token);
|
||||
setSecretDialog(response);
|
||||
showToast('Новый client secret сгенерирован');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось перевыпустить secret');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleActive(client: OAuthClient) {
|
||||
if (!token) return;
|
||||
try {
|
||||
await apiFetch(`/admin/rbac/oauth-clients/${client.clientId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ isActive: !client.isActive })
|
||||
}, token);
|
||||
showToast(client.isActive ? 'Приложение отключено' : 'Приложение включено');
|
||||
await loadData();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось обновить приложение');
|
||||
}
|
||||
}
|
||||
|
||||
function copyText(value: string, label: string) {
|
||||
void navigator.clipboard.writeText(value);
|
||||
showToast(`${label} скопирован`);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminShell active="/admin/oauth">
|
||||
<div className="mb-6 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-medium">OAuth-приложения</h2>
|
||||
<p className="text-sm text-[#667085]">Создание клиентов как на oauth.yandex.ru: client_id, secret, redirect URI и scopes</p>
|
||||
</div>
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4" />
|
||||
Новое приложение
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center gap-2 py-16 text-[#667085]">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
Загрузка...
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{clients.map((client) => (
|
||||
<Card key={client.id} className={client.isActive ? '' : 'opacity-70'}>
|
||||
<CardHeader>
|
||||
<LockKeyhole className="h-6 w-6" />
|
||||
<CardTitle>{client.name}</CardTitle>
|
||||
<CardDescription>{client.type === 'PUBLIC' ? 'Публичное приложение' : 'Confidential приложение'}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<span className="font-medium">Client ID</span>
|
||||
<Button variant="ghost" size="icon" aria-label="Скопировать client id" onClick={() => copyText(client.clientId, 'Client ID')}>
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<code className="break-all text-xs">{client.clientId}</code>
|
||||
</div>
|
||||
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
|
||||
<div className="mb-2 font-medium">Redirect URI</div>
|
||||
{client.redirectUris.map((uri) => (
|
||||
<div key={uri} className="break-all text-xs text-[#667085]">
|
||||
{uri}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
|
||||
<div className="mb-2 flex items-center gap-2 font-medium">
|
||||
<KeyRound className="h-4 w-4" />
|
||||
Scopes
|
||||
</div>
|
||||
<p>{client.scopes.join(', ')}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{client.type !== 'PUBLIC' ? (
|
||||
<Button variant="secondary" size="sm" onClick={() => void handleRotateSecret(client.clientId)}>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Новый secret
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="secondary" size="sm" onClick={() => void handleToggleActive(client)}>
|
||||
{client.isActive ? 'Отключить' : 'Включить'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
{!clients.length ? <p className="text-[#667085]">OAuth-приложения ещё не созданы</p> : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Новое OAuth-приложение</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium">Название</label>
|
||||
<Input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Lendry Docs" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium">Тип клиента</label>
|
||||
<select
|
||||
value={form.type}
|
||||
onChange={(event) => setForm((current) => ({ ...current, type: event.target.value }))}
|
||||
className="h-11 w-full rounded-xl border border-[#eceef4] bg-white px-3 text-sm"
|
||||
>
|
||||
<option value="CONFIDENTIAL">Confidential (с client secret)</option>
|
||||
<option value="PUBLIC">Public (без secret)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium">Redirect URI (по одному на строку)</label>
|
||||
<textarea
|
||||
value={form.redirectUris}
|
||||
onChange={(event) => setForm((current) => ({ ...current, redirectUris: event.target.value }))}
|
||||
placeholder="https://app.example.com/oauth/callback"
|
||||
className="min-h-[96px] w-full rounded-xl border border-[#eceef4] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium">Scopes</label>
|
||||
<div className="space-y-2">
|
||||
{scopes.map((scope) => (
|
||||
<label key={scope.id} className="flex items-center gap-2 rounded-xl bg-[#f4f5f8] px-3 py-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.selectedScopes.includes(scope.slug)}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
selectedScopes: event.target.checked
|
||||
? [...current.selectedScopes, scope.slug]
|
||||
: current.selectedScopes.filter((item) => item !== scope.slug)
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<span className="font-medium">{scope.name}</span>
|
||||
<span className="text-[#667085]">({scope.slug})</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Button className="w-full" disabled={creating} onClick={() => void handleCreate()}>
|
||||
{creating ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Создать приложение'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={Boolean(secretDialog)} onOpenChange={(open) => !open && setSecretDialog(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Client Secret</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-[#667085]">Сохраните secret сейчас — он больше не будет показан полностью.</p>
|
||||
<div className="rounded-2xl bg-[#f4f5f8] p-4">
|
||||
<p className="mb-1 text-xs text-[#667085]">Client ID</p>
|
||||
<code className="break-all text-sm">{secretDialog?.clientId}</code>
|
||||
<p className="mb-1 mt-4 text-xs text-[#667085]">Client Secret</p>
|
||||
<code className="break-all text-sm">{secretDialog?.clientSecret}</code>
|
||||
</div>
|
||||
<Button className="w-full" onClick={() => secretDialog && copyText(secretDialog.clientSecret, 'Client Secret')}>
|
||||
<Copy className="h-4 w-4" />
|
||||
Скопировать secret
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
5
apps/frontend/app/admin/page.tsx
Normal file
5
apps/frontend/app/admin/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function AdminIndexPage() {
|
||||
redirect('/admin/users');
|
||||
}
|
||||
143
apps/frontend/app/admin/rbac/page.tsx
Normal file
143
apps/frontend/app/admin/rbac/page.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Loader2, Plus, ShieldCheck } from 'lucide-react';
|
||||
import { AdminShell } from '@/components/id/admin-shell';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { AdminPermission, AdminRole, apiFetch } from '@/lib/api';
|
||||
|
||||
export default function AdminRbacPage() {
|
||||
const { token, user } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const [roles, setRoles] = useState<AdminRole[]>([]);
|
||||
const [permissions, setPermissions] = useState<AdminPermission[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [form, setForm] = useState({ slug: '', name: '', description: '', permissionSlugs: [] as string[] });
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !user?.canManageRoles) return;
|
||||
Promise.all([
|
||||
apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token),
|
||||
apiFetch<{ permissions: AdminPermission[] }>('/admin/rbac/permissions', {}, token)
|
||||
])
|
||||
.then(([rolesResponse, permissionsResponse]) => {
|
||||
setRoles(rolesResponse.roles ?? []);
|
||||
setPermissions(permissionsResponse.permissions ?? []);
|
||||
})
|
||||
.catch((error) => showToast(error instanceof Error ? error.message : 'Не удалось загрузить роли'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [showToast, token, user?.canManageRoles]);
|
||||
|
||||
async function handleCreateRole() {
|
||||
if (!token) return;
|
||||
setCreating(true);
|
||||
try {
|
||||
await apiFetch('/admin/rbac/roles', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(form)
|
||||
}, token);
|
||||
showToast('Роль создана');
|
||||
setDialogOpen(false);
|
||||
setForm({ slug: '', name: '', description: '', permissionSlugs: [] });
|
||||
const response = await apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token);
|
||||
setRoles(response.roles ?? []);
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось создать роль');
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!user?.canManageRoles) {
|
||||
return (
|
||||
<AdminShell active="/admin/rbac">
|
||||
<p className="text-[#667085]">Управление ролями доступно только супер-администратору.</p>
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminShell active="/admin/rbac">
|
||||
<div className="mb-6 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-medium">Роли и права</h2>
|
||||
<p className="text-sm text-[#667085]">Только супер-администратор может создавать роли и назначать их пользователям</p>
|
||||
</div>
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4" />
|
||||
Создать роль
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center gap-2 py-16 text-[#667085]">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
Загрузка...
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{roles.map((role) => (
|
||||
<Card key={role.id} className="bg-[#f8f9fb] shadow-none">
|
||||
<CardHeader>
|
||||
<ShieldCheck className="h-6 w-6" />
|
||||
<CardTitle>{role.name}</CardTitle>
|
||||
<CardDescription>{role.permissions.length} прав · {role.slug}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{role.permissions.map((permission) => (
|
||||
<div key={permission.id} className="rounded-xl bg-white px-3 py-2 text-sm">
|
||||
<div className="font-medium">{permission.name}</div>
|
||||
<div className="text-xs text-[#667085]">{permission.slug}</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Новая роль</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<Input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="slug, например support" />
|
||||
<Input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Название роли" />
|
||||
<Input value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} placeholder="Описание" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">Права</p>
|
||||
{permissions.map((permission) => (
|
||||
<label key={permission.id} className="flex items-center gap-2 rounded-xl bg-[#f4f5f8] px-3 py-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.permissionSlugs.includes(permission.slug)}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
permissionSlugs: event.target.checked
|
||||
? [...current.permissionSlugs, permission.slug]
|
||||
: current.permissionSlugs.filter((item) => item !== permission.slug)
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<span>{permission.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Button className="w-full" disabled={creating} onClick={() => void handleCreateRole()}>
|
||||
{creating ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Создать роль'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
219
apps/frontend/app/admin/settings/page.tsx
Normal file
219
apps/frontend/app/admin/settings/page.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Chrome, Loader2, Save, Settings2, ToggleLeft, ToggleRight } from 'lucide-react';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { AdminShell } from '@/components/id/admin-shell';
|
||||
import { usePublicSettings } from '@/components/id/public-settings-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { apiFetch, buildSystemSettingPayload, SocialProvider, SystemSetting } from '@/lib/api';
|
||||
import { getSettingMeta, sortSettingsByCatalog, SYSTEM_SETTING_GROUPS } from '@/lib/system-settings-catalog';
|
||||
|
||||
function parseBoolean(value: string) {
|
||||
return ['true', '1', 'yes'].includes(value.trim().toLowerCase());
|
||||
}
|
||||
|
||||
export default function AdminSettingsPage() {
|
||||
const { token, user } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const { refreshPublicSettings } = usePublicSettings();
|
||||
const [settings, setSettings] = useState<SystemSetting[]>([]);
|
||||
const [providers, setProviders] = useState<SocialProvider[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !user?.canManageSettings) return;
|
||||
Promise.all([
|
||||
apiFetch<{ settings: SystemSetting[] }>('/admin/settings', {}, token),
|
||||
apiFetch<{ providers: SocialProvider[] }>('/admin/settings/oauth/providers', {}, token)
|
||||
])
|
||||
.then(([settingsResponse, providersResponse]) => {
|
||||
setSettings(sortSettingsByCatalog(settingsResponse.settings ?? []));
|
||||
setProviders(providersResponse.providers ?? []);
|
||||
})
|
||||
.catch((error) => showToast(error instanceof Error ? error.message : 'Не удалось загрузить настройки'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [showToast, token, user?.canManageSettings]);
|
||||
|
||||
const groupedSettings = useMemo(() => {
|
||||
const groups = new Map<string, SystemSetting[]>();
|
||||
for (const setting of settings) {
|
||||
const meta = getSettingMeta(setting.key);
|
||||
const group = meta?.group ?? 'other';
|
||||
const list = groups.get(group) ?? [];
|
||||
list.push(setting);
|
||||
groups.set(group, list);
|
||||
}
|
||||
return groups;
|
||||
}, [settings]);
|
||||
|
||||
async function saveSetting(setting: SystemSetting) {
|
||||
if (!token) return;
|
||||
setSavingKey(setting.key);
|
||||
try {
|
||||
const updated = await apiFetch<SystemSetting>(
|
||||
'/admin/settings',
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(buildSystemSettingPayload(setting))
|
||||
},
|
||||
token
|
||||
);
|
||||
setSettings((current) => sortSettingsByCatalog(current.map((item) => (item.key === updated.key ? updated : item))));
|
||||
if (updated.key === 'PROJECT_NAME' || updated.key === 'PROJECT_TAGLINE' || updated.key === 'LDAP_ENABLED' || updated.key === 'LDAP_USE_LDAPS') {
|
||||
await refreshPublicSettings();
|
||||
}
|
||||
showToast('Настройка сохранена');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось сохранить настройку');
|
||||
} finally {
|
||||
setSavingKey(null);
|
||||
}
|
||||
}
|
||||
|
||||
function updateSettingValue(key: string, value: string) {
|
||||
setSettings((current) => current.map((item) => (item.key === key ? { ...item, value } : item)));
|
||||
}
|
||||
|
||||
function toProviderPayload(provider: SocialProvider) {
|
||||
return {
|
||||
providerName: provider.providerName,
|
||||
clientId: provider.clientId,
|
||||
isEnabled: provider.isEnabled
|
||||
};
|
||||
}
|
||||
|
||||
async function toggleProvider(provider: SocialProvider) {
|
||||
if (!token) return;
|
||||
try {
|
||||
const updated = await apiFetch<SocialProvider>('/admin/settings/oauth/providers', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ ...toProviderPayload(provider), isEnabled: !provider.isEnabled })
|
||||
}, token);
|
||||
setProviders((current) => current.map((item) => (item.providerName === updated.providerName ? updated : item)));
|
||||
showToast(updated.isEnabled ? 'Провайдер включён' : 'Провайдер отключён');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось обновить провайдера');
|
||||
}
|
||||
}
|
||||
|
||||
if (!user?.canManageSettings) {
|
||||
return (
|
||||
<AdminShell active="/admin/settings">
|
||||
<p className="text-[#667085]">У вас нет прав на изменение глобальных настроек.</p>
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminShell active="/admin/settings">
|
||||
<div className="mb-6">
|
||||
<h2 className="text-2xl font-medium">Глобальные настройки</h2>
|
||||
<p className="mt-2 text-[#667085]">Параметры хранятся в SystemSetting и применяются сервисами без релиза frontend.</p>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center gap-2 py-16 text-[#667085]">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
Загрузка...
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{[...groupedSettings.entries()].map(([groupKey, groupSettings]) => (
|
||||
<section key={groupKey} className="mb-10">
|
||||
<h3 className="mb-4 text-xl font-medium">{SYSTEM_SETTING_GROUPS[groupKey] ?? 'Прочие настройки'}</h3>
|
||||
<div className="space-y-3">
|
||||
{groupSettings.map((setting) => {
|
||||
const meta = getSettingMeta(setting.key);
|
||||
const label = meta?.label ?? setting.key;
|
||||
const type = meta?.type ?? 'text';
|
||||
|
||||
return (
|
||||
<div key={setting.key} className="rounded-[24px] bg-[#f4f5f8] p-5">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 font-semibold">
|
||||
<Settings2 className="h-4 w-4 shrink-0" />
|
||||
{label}
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-[#667085]">{meta?.hint ?? setting.description ?? setting.key}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{type === 'boolean' ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={label}
|
||||
onClick={() => {
|
||||
updateSettingValue(setting.key, parseBoolean(setting.value) ? 'false' : 'true');
|
||||
}}
|
||||
>
|
||||
{parseBoolean(setting.value) ? <ToggleRight className="h-9 w-9 text-green-600" /> : <ToggleLeft className="h-9 w-9 text-[#a8adbc]" />}
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type={setting.isSecret ? 'password' : type === 'number' ? 'number' : 'text'}
|
||||
value={setting.value}
|
||||
className={setting.isSecret ? 'w-[220px] bg-white' : 'w-[180px] bg-white'}
|
||||
onChange={(event) => updateSettingValue(setting.key, event.target.value)}
|
||||
/>
|
||||
{meta?.unit ? <span className="text-sm text-[#667085]">{meta.unit}</span> : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button disabled={savingKey === setting.key} onClick={() => void saveSetting(setting)}>
|
||||
{savingKey === setting.key ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
|
||||
Сохранить
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
<section className="mt-10">
|
||||
<h3 className="text-xl font-medium">OAuth Social Providers</h3>
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-2">
|
||||
{(providers.length ? providers : [{ id: 'google', providerName: 'google', clientId: '', isEnabled: false }, { id: 'yandex', providerName: 'yandex', clientId: '', isEnabled: false }]).map((provider) => (
|
||||
<div key={provider.providerName} className="rounded-[24px] bg-[#f4f5f8] p-5">
|
||||
<div className="flex items-center justify-between">
|
||||
{provider.providerName === 'google' ? <Chrome className="h-7 w-7" /> : <div className="flex h-8 w-8 items-center justify-center rounded-full bg-red-500 font-bold text-white">Я</div>}
|
||||
<button type="button" aria-label="Переключить провайдера" onClick={() => void toggleProvider(provider)}>
|
||||
{provider.isEnabled ? <ToggleRight className="h-8 w-8 text-green-600" /> : <ToggleLeft className="h-8 w-8 text-[#a8adbc]" />}
|
||||
</button>
|
||||
</div>
|
||||
<h4 className="mt-5 font-semibold capitalize">{provider.providerName}</h4>
|
||||
<p className="mt-1 text-sm text-[#667085]">{provider.isEnabled ? 'Провайдер включен глобально.' : 'Провайдер отключен.'}</p>
|
||||
<Input
|
||||
className="mt-4 bg-white"
|
||||
value={provider.clientId}
|
||||
placeholder="Client ID"
|
||||
onChange={(event) => setProviders((current) => current.map((item) => (item.providerName === provider.providerName ? { ...item, clientId: event.target.value } : item)))}
|
||||
/>
|
||||
<Button
|
||||
className="mt-3"
|
||||
variant="secondary"
|
||||
onClick={() =>
|
||||
void apiFetch('/admin/settings/oauth/providers', { method: 'PUT', body: JSON.stringify(toProviderPayload(provider)) }, token)
|
||||
.then(() => showToast('Провайдер сохранён'))
|
||||
.catch((error) => showToast(error instanceof Error ? error.message : 'Ошибка сохранения'))
|
||||
}
|
||||
>
|
||||
Сохранить провайдера
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
323
apps/frontend/app/admin/users/page.tsx
Normal file
323
apps/frontend/app/admin/users/page.tsx
Normal file
@@ -0,0 +1,323 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Ban, Crown, FileText, KeyRound, Loader2, Search, ShieldPlus, UserCog } from 'lucide-react';
|
||||
import { UserDocumentsDialog } from '@/components/documents/user-documents-dialog';
|
||||
import { AdminShell } from '@/components/id/admin-shell';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { AdminRole, AdminUser, apiFetch } from '@/lib/api';
|
||||
|
||||
const statusLabels: Record<string, string> = {
|
||||
ACTIVE: 'Активен',
|
||||
SUSPENDED: 'Заблокирован',
|
||||
DELETED: 'Удалён'
|
||||
};
|
||||
|
||||
const roleLabels: Record<string, string> = {
|
||||
admin: 'Администратор',
|
||||
moderator: 'Модератор',
|
||||
manager: 'Менеджер',
|
||||
'super-admin': 'Супер-админ'
|
||||
};
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const { token, user: currentUser } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const [users, setUsers] = useState<AdminUser[]>([]);
|
||||
const [roles, setRoles] = useState<AdminRole[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
|
||||
const [password, setPassword] = useState('');
|
||||
const [actionLoading, setActionLoading] = useState(false);
|
||||
const [dialog, setDialog] = useState<'password' | 'roles' | null>(null);
|
||||
const [documentsUser, setDocumentsUser] = useState<AdminUser | null>(null);
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
if (!token) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await apiFetch<{ users: AdminUser[] }>(`/admin/users${search ? `?search=${encodeURIComponent(search)}` : ''}`, {}, token);
|
||||
setUsers(response.users ?? []);
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось загрузить пользователей');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [search, showToast, token]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadUsers();
|
||||
}, [loadUsers]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !currentUser?.canManageRoles) return;
|
||||
apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token)
|
||||
.then((response) => setRoles(response.roles ?? []))
|
||||
.catch(() => undefined);
|
||||
}, [currentUser?.canManageRoles, token]);
|
||||
|
||||
const assignableRoles = useMemo(() => roles.filter((role) => role.slug !== 'super-admin'), [roles]);
|
||||
|
||||
async function handleSuspend(user: AdminUser) {
|
||||
if (!token) return;
|
||||
setActionLoading(true);
|
||||
try {
|
||||
await apiFetch(`/admin/users/${user.id}/suspend`, { method: 'POST' }, token);
|
||||
showToast('Пользователь заблокирован');
|
||||
await loadUsers();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось заблокировать пользователя');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResetPassword() {
|
||||
if (!token || !selectedUser || password.length < 8) return;
|
||||
setActionLoading(true);
|
||||
try {
|
||||
await apiFetch(`/admin/users/${selectedUser.id}/reset-password`, { method: 'POST', body: JSON.stringify({ newPassword: password }) }, token);
|
||||
showToast('Пароль обновлён');
|
||||
setDialog(null);
|
||||
setPassword('');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось сбросить пароль');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleSuperAdmin(user: AdminUser) {
|
||||
if (!token || !currentUser?.canManageRoles) return;
|
||||
setActionLoading(true);
|
||||
try {
|
||||
await apiFetch(`/admin/users/${user.id}/super-admin`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ isSuperAdmin: !user.isSuperAdmin })
|
||||
}, token);
|
||||
showToast(user.isSuperAdmin ? 'Права супер-админа сняты' : 'Пользователь назначен супер-админом');
|
||||
await loadUsers();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось изменить права');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAssignRole(roleSlug: string) {
|
||||
if (!token || !selectedUser) return;
|
||||
setActionLoading(true);
|
||||
try {
|
||||
const response = await apiFetch<{ roles: string[] }>(`/admin/rbac/users/${selectedUser.id}/roles`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ roleSlug })
|
||||
}, token);
|
||||
setSelectedUser({ ...selectedUser, roles: response.roles ?? [] });
|
||||
showToast('Роль назначена');
|
||||
await loadUsers();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось назначить роль');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveRole(roleSlug: string) {
|
||||
if (!token || !selectedUser) return;
|
||||
setActionLoading(true);
|
||||
try {
|
||||
await apiFetch(`/admin/rbac/users/${selectedUser.id}/roles/${roleSlug}`, { method: 'DELETE' }, token);
|
||||
setSelectedUser({ ...selectedUser, roles: (selectedUser.roles ?? []).filter((role) => role !== roleSlug) });
|
||||
showToast('Роль снята');
|
||||
await loadUsers();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось снять роль');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function renderRoles(user: AdminUser) {
|
||||
const userRoles = user.roles ?? [];
|
||||
const labels = user.isSuperAdmin ? ['Супер-админ', ...userRoles.map((role) => roleLabels[role] ?? role)] : userRoles.map((role) => roleLabels[role] ?? role);
|
||||
if (!labels.length) return 'Пользователь';
|
||||
return labels.join(', ');
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminShell active="/admin/users">
|
||||
<div className="mb-6 flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-medium">Пользователи</h2>
|
||||
<p className="text-sm text-[#667085]">Поиск, блокировка, сброс пароля и управление доступом</p>
|
||||
</div>
|
||||
<div className="relative w-full max-w-sm">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#667085]" />
|
||||
<Input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Поиск по имени, почте или телефону" className="pl-10" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden rounded-[24px] border border-[#eceef4] bg-white">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center gap-2 py-16 text-[#667085]">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
Загрузка...
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Пользователь</TableHead>
|
||||
<TableHead>Телефон</TableHead>
|
||||
<TableHead>Роли</TableHead>
|
||||
<TableHead>Статус</TableHead>
|
||||
<TableHead className="text-right">Действия</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell>
|
||||
<div className="font-medium">{user.displayName}</div>
|
||||
<div className="text-sm text-[#667085]">{user.email ?? user.username ?? '—'}</div>
|
||||
</TableCell>
|
||||
<TableCell>{user.phone ?? '—'}</TableCell>
|
||||
<TableCell>{renderRoles(user)}</TableCell>
|
||||
<TableCell>
|
||||
<span className="rounded-full bg-[#f4f5f8] px-3 py-1 text-xs font-semibold">{statusLabels[user.status] ?? user.status}</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex justify-end gap-2">
|
||||
{currentUser?.canManageUsers ? (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
aria-label="Сбросить пароль"
|
||||
disabled={actionLoading}
|
||||
onClick={() => {
|
||||
setSelectedUser(user);
|
||||
setPassword('');
|
||||
setDialog('password');
|
||||
}}
|
||||
>
|
||||
<KeyRound className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="secondary" size="icon" aria-label="Заблокировать" disabled={actionLoading || user.status === 'SUSPENDED'} onClick={() => void handleSuspend(user)}>
|
||||
<Ban className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
{currentUser?.canViewUserDocuments ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
aria-label="Документы пользователя"
|
||||
disabled={actionLoading}
|
||||
onClick={() => setDocumentsUser(user)}
|
||||
>
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
) : null}
|
||||
{currentUser?.canManageRoles ? (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
aria-label="Управление ролями"
|
||||
disabled={actionLoading}
|
||||
onClick={() => {
|
||||
setSelectedUser(user);
|
||||
setDialog('roles');
|
||||
}}
|
||||
>
|
||||
<UserCog className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={user.isSuperAdmin ? 'default' : 'secondary'}
|
||||
size="icon"
|
||||
aria-label="Супер-админ"
|
||||
disabled={actionLoading || user.id === currentUser?.id}
|
||||
onClick={() => void handleToggleSuperAdmin(user)}
|
||||
>
|
||||
<Crown className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Dialog open={dialog === 'password'} onOpenChange={(open) => !open && setDialog(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Сброс пароля</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="mb-4 text-sm text-[#667085]">Новый пароль для {selectedUser?.displayName}</p>
|
||||
<Input type="password" value={password} onChange={(event) => setPassword(event.target.value)} placeholder="Минимум 8 символов" />
|
||||
<Button className="mt-4 w-full" disabled={actionLoading || password.length < 8} onClick={() => void handleResetPassword()}>
|
||||
{actionLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Сохранить пароль'}
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={dialog === 'roles'} onOpenChange={(open) => !open && setDialog(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Роли и доступ</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="mb-4 text-sm text-[#667085]">{selectedUser?.displayName}</p>
|
||||
<div className="space-y-2">
|
||||
{(selectedUser?.roles ?? []).map((role) => (
|
||||
<div key={role} className="flex items-center justify-between rounded-xl bg-[#f4f5f8] px-3 py-2">
|
||||
<span>{roleLabels[role] ?? role}</span>
|
||||
<Button variant="ghost" size="sm" disabled={actionLoading} onClick={() => void handleRemoveRole(role)}>
|
||||
Снять
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{!(selectedUser?.roles ?? []).length ? <p className="text-sm text-[#667085]">Роли не назначены</p> : null}
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
<p className="text-sm font-medium">Назначить роль</p>
|
||||
{assignableRoles.map((role) => (
|
||||
<Button
|
||||
key={role.id}
|
||||
variant="secondary"
|
||||
className="w-full justify-start"
|
||||
disabled={actionLoading || (selectedUser?.roles ?? []).includes(role.slug)}
|
||||
onClick={() => void handleAssignRole(role.slug)}
|
||||
>
|
||||
<ShieldPlus className="mr-2 h-4 w-4" />
|
||||
{role.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{documentsUser ? (
|
||||
<UserDocumentsDialog
|
||||
open={Boolean(documentsUser)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDocumentsUser(null);
|
||||
}}
|
||||
targetUserId={documentsUser.id}
|
||||
targetUserName={documentsUser.displayName}
|
||||
token={token}
|
||||
/>
|
||||
) : null}
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
365
apps/frontend/app/auth/login/page.tsx
Normal file
365
apps/frontend/app/auth/login/page.tsx
Normal file
@@ -0,0 +1,365 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ChevronLeft, KeyRound, Mail, Network, Phone, ShieldQuestion, UserRound } from 'lucide-react';
|
||||
import { BrandLogo, ProjectTagline } from '@/components/id/brand-logo';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { usePublicSettings } from '@/components/id/public-settings-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { OtpInput } from '@/components/ui/otp-input';
|
||||
import { PhoneInput, phoneCountries, toE164 } from '@/components/ui/phone-input';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import type { LoginMethod } from '@/lib/api';
|
||||
|
||||
type Step = 'identify' | 'otp' | 'password' | 'pin' | 'ldap';
|
||||
|
||||
const channelIcon: Record<string, typeof Mail> = {
|
||||
email: Mail,
|
||||
backupEmail: Mail,
|
||||
phone: Phone,
|
||||
backupPhone: Phone,
|
||||
password: KeyRound
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { identifyLogin, sendLoginOtp, verifyLoginOtp, loginWithPassword, loginWithLdap, completePin } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const { ldapEnabled, ldapUseLdaps } = usePublicSettings();
|
||||
|
||||
const [authTab, setAuthTab] = useState<'email' | 'phone'>('email');
|
||||
const [email, setEmail] = useState('');
|
||||
const [phoneNumber, setPhoneNumber] = useState('');
|
||||
const [country, setCountry] = useState(phoneCountries[0]);
|
||||
|
||||
const [recipient, setRecipient] = useState('');
|
||||
const [maskedTarget, setMaskedTarget] = useState('');
|
||||
const [otp, setOtp] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [ldapUsername, setLdapUsername] = useState('');
|
||||
const [ldapPassword, setLdapPassword] = useState('');
|
||||
const [pin, setPin] = useState('');
|
||||
const [pendingSessionId, setPendingSessionId] = useState<string | null>(null);
|
||||
const [methods, setMethods] = useState<LoginMethod[]>([]);
|
||||
const [showMethods, setShowMethods] = useState(false);
|
||||
const [step, setStep] = useState<Step>('identify');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
function getIdentifier() {
|
||||
return authTab === 'email' ? email.trim() : toE164(country, phoneNumber);
|
||||
}
|
||||
|
||||
function finishAuth(pinVerified: boolean, sessionId: string) {
|
||||
if (!pinVerified) {
|
||||
setPendingSessionId(sessionId);
|
||||
setStep('pin');
|
||||
} else {
|
||||
router.push('/');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleIdentify(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const identifier = getIdentifier();
|
||||
setRecipient(identifier);
|
||||
const result = await identifyLogin(identifier);
|
||||
setMethods(result.methods ?? []);
|
||||
const masked = await sendLoginOtp(identifier);
|
||||
setMaskedTarget(masked);
|
||||
setOtp('');
|
||||
setStep('otp');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось продолжить вход');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyOtp(code: string) {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const response = await verifyLoginOtp(recipient, code);
|
||||
if (response.auth) {
|
||||
finishAuth(response.auth.pinVerified, response.auth.sessionId);
|
||||
} else {
|
||||
showToast('Не удалось завершить вход');
|
||||
}
|
||||
} catch (error) {
|
||||
setOtp('');
|
||||
showToast(error instanceof Error ? error.message : 'Неверный код');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePasswordSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const auth = await loginWithPassword(recipient, password);
|
||||
finishAuth(auth.pinVerified, auth.sessionId);
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Неверный пароль');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseMethod(method: LoginMethod) {
|
||||
setShowMethods(false);
|
||||
if (method.kind === 'password') {
|
||||
setPassword('');
|
||||
setStep('password');
|
||||
return;
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const masked = await sendLoginOtp(recipient, method.channel);
|
||||
setMaskedTarget(masked);
|
||||
setOtp('');
|
||||
setStep('otp');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось отправить код');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLdapSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const auth = await loginWithLdap(ldapUsername.trim(), ldapPassword);
|
||||
finishAuth(auth.pinVerified, auth.sessionId);
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось выполнить LDAP-вход');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePinSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!pendingSessionId) return;
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await completePin(pendingSessionId, pin);
|
||||
router.push('/');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось проверить PIN-код');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function resetToIdentify() {
|
||||
setStep('identify');
|
||||
setShowMethods(false);
|
||||
setOtp('');
|
||||
setPassword('');
|
||||
setLdapUsername('');
|
||||
setLdapPassword('');
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[radial-gradient(circle_at_center,#596075_0%,#2b2534_45%,#121017_100%)] px-5">
|
||||
<section className="w-full max-w-[430px] rounded-[34px] bg-[#1f2028] px-9 pb-8 pt-10 text-white shadow-2xl">
|
||||
<div className="mb-8 flex flex-col items-center text-center">
|
||||
<BrandLogo size="lg" variant="light" />
|
||||
<h1 className="mt-8 text-xl font-bold">Войдите с ID</h1>
|
||||
</div>
|
||||
|
||||
{step !== 'identify' ? (
|
||||
<button type="button" onClick={resetToIdentify} className="mb-4 flex items-center gap-1 text-sm text-[#b9bdc9] hover:text-white">
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
Изменить аккаунт
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{step === 'identify' ? (
|
||||
<form onSubmit={handleIdentify}>
|
||||
<Tabs value={authTab} onValueChange={(value) => setAuthTab(value as 'email' | 'phone')} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="email">Почта</TabsTrigger>
|
||||
<TabsTrigger value="phone">Телефон</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="email">
|
||||
<Input
|
||||
className="h-[58px] border-[#555762] bg-transparent text-lg text-white placeholder:text-[#8f92a0]"
|
||||
placeholder="name@example.com"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
required={authTab === 'email'}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="phone">
|
||||
<PhoneInput country={country} value={phoneNumber} onCountryChange={setCountry} onValueChange={setPhoneNumber} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<Button variant="white" size="lg" className="mt-8 w-full rounded-[18px] text-base" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Отправляем код...' : 'Далее'}
|
||||
</Button>
|
||||
{ldapEnabled ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="mt-3 w-full rounded-[18px] border-[#424550] text-white hover:bg-[#2a2c36]"
|
||||
onClick={() => {
|
||||
setLdapUsername('');
|
||||
setLdapPassword('');
|
||||
setStep('ldap');
|
||||
}}
|
||||
>
|
||||
<Network className="h-5 w-5" />
|
||||
{ldapUseLdaps ? 'Войти через LDAPS' : 'Войти через LDAP'}
|
||||
</Button>
|
||||
) : null}
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{step === 'ldap' ? (
|
||||
<form onSubmit={handleLdapSubmit}>
|
||||
<div className="mb-5 flex items-center gap-3 rounded-[20px] bg-[#2a2c36] p-3">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-full bg-white/10">
|
||||
<Network className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 text-left">
|
||||
<p className="text-sm text-[#b9bdc9]">Корпоративный вход</p>
|
||||
<p className="truncate text-sm font-semibold">{ldapUseLdaps ? 'LDAPS' : 'LDAP'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Input
|
||||
className="h-[58px] border-[#555762] bg-transparent text-lg text-white placeholder:text-[#8f92a0]"
|
||||
placeholder="Логин LDAP"
|
||||
value={ldapUsername}
|
||||
onChange={(event) => setLdapUsername(event.target.value)}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
className="mt-3 h-[58px] border-[#555762] bg-transparent text-lg text-white placeholder:text-[#8f92a0]"
|
||||
placeholder="Пароль LDAP"
|
||||
type="password"
|
||||
value={ldapPassword}
|
||||
onChange={(event) => setLdapPassword(event.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
<Button variant="white" size="lg" className="mt-8 w-full rounded-[18px] text-base" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Проверяем...' : ldapUseLdaps ? 'Войти через LDAPS' : 'Войти через LDAP'}
|
||||
</Button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{step === 'otp' ? (
|
||||
<div>
|
||||
<div className="mb-5 flex items-center gap-3 rounded-[20px] bg-[#2a2c36] p-3">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-full bg-white/10">
|
||||
<UserRound className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 text-left">
|
||||
<p className="text-sm text-[#b9bdc9]">Код отправлен на</p>
|
||||
<p className="truncate text-sm font-semibold">{maskedTarget || recipient}</p>
|
||||
</div>
|
||||
</div>
|
||||
<OtpInput value={otp} onChange={setOtp} onComplete={verifyOtp} disabled={isSubmitting} />
|
||||
{isSubmitting ? <p className="mt-3 text-center text-sm text-[#b9bdc9]">Проверяем код...</p> : null}
|
||||
|
||||
{methods.length ? (
|
||||
<div className="mt-6">
|
||||
<Button type="button" variant="outline" size="lg" className="w-full rounded-[18px] border-[#424550] text-white hover:bg-[#2a2c36]" onClick={() => setShowMethods((prev) => !prev)}>
|
||||
<ShieldQuestion className="h-5 w-5" />
|
||||
Другой способ входа
|
||||
</Button>
|
||||
{showMethods ? (
|
||||
<div className="mt-3 space-y-2">
|
||||
{methods.map((method) => {
|
||||
const Icon = channelIcon[method.channel] ?? KeyRound;
|
||||
return (
|
||||
<button
|
||||
key={`${method.kind}-${method.channel}`}
|
||||
type="button"
|
||||
onClick={() => chooseMethod(method)}
|
||||
className="flex w-full items-center gap-3 rounded-[16px] bg-[#2a2c36] p-3 text-left hover:bg-[#33353f]"
|
||||
>
|
||||
<Icon className="h-5 w-5 text-[#b9bdc9]" />
|
||||
<span className="text-sm">
|
||||
{method.kind === 'password' ? 'Войти с паролем' : `Код на ${method.masked}`}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{step === 'password' ? (
|
||||
<form onSubmit={handlePasswordSubmit}>
|
||||
<div className="mb-5 flex items-center gap-3 rounded-[20px] bg-[#2a2c36] p-3">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-full bg-white/10">
|
||||
<UserRound className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 text-left">
|
||||
<p className="text-sm text-[#b9bdc9]">Вход в аккаунт</p>
|
||||
<p className="truncate text-sm font-semibold">{recipient}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Input
|
||||
className="h-[58px] border-[#555762] bg-transparent text-lg text-white placeholder:text-[#8f92a0]"
|
||||
placeholder="Пароль"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
required
|
||||
/>
|
||||
<Button variant="white" size="lg" className="mt-8 w-full rounded-[18px] text-base" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Входим...' : 'Войти'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="lg" className="mt-3 w-full rounded-[18px] border-[#424550] text-white hover:bg-[#2a2c36]" onClick={() => setStep('otp')}>
|
||||
Войти по коду
|
||||
</Button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{step === 'pin' && pendingSessionId ? (
|
||||
<form onSubmit={handlePinSubmit} className="space-y-3">
|
||||
<Input
|
||||
className="h-[58px] border-[#555762] bg-transparent text-center text-lg tracking-[0.4em] text-white placeholder:text-[#8f92a0]"
|
||||
placeholder="PIN"
|
||||
value={pin}
|
||||
onChange={(event) => setPin(event.target.value)}
|
||||
required
|
||||
minLength={4}
|
||||
maxLength={6}
|
||||
/>
|
||||
<Button variant="white" size="lg" className="w-full rounded-[18px] text-base" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Проверяем...' : 'Подтвердить PIN'}
|
||||
</Button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{step === 'identify' ? (
|
||||
<div className="mt-3">
|
||||
<Button asChild variant="outline" size="lg" className="w-full rounded-[18px] border-[#424550] text-white hover:bg-[#2a2c36]">
|
||||
<Link href="/auth/register">Создать ID</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<ProjectTagline className="mt-9 text-center text-sm font-semibold" />
|
||||
<p className="mt-2 text-center text-sm font-bold">Узнать больше</p>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
82
apps/frontend/app/auth/register/page.tsx
Normal file
82
apps/frontend/app/auth/register/page.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { FormEvent, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ShieldCheck } from 'lucide-react';
|
||||
import { BrandLogo } from '@/components/id/brand-logo';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PhoneInput, phoneCountries, toE164 } from '@/components/ui/phone-input';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter();
|
||||
const { sendLoginOtp } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const [authTab, setAuthTab] = useState<'email' | 'phone'>('email');
|
||||
const [email, setEmail] = useState('');
|
||||
const [phoneNumber, setPhoneNumber] = useState('');
|
||||
const [country, setCountry] = useState(phoneCountries[0]);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const recipient = authTab === 'email' ? email.trim() : toE164(country, phoneNumber);
|
||||
await sendLoginOtp(recipient);
|
||||
showToast('Код отправлен. Подтвердите его на экране входа.');
|
||||
router.push('/auth/login');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось отправить код');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[radial-gradient(circle_at_center,#5d6578_0%,#2c2736_48%,#111016_100%)] px-5">
|
||||
<section className="w-full max-w-[430px] rounded-[34px] bg-[#1f2028] px-9 py-10 text-white shadow-2xl">
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<BrandLogo size="lg" variant="light" />
|
||||
<h1 className="mt-8 text-xl font-bold">Создайте ID</h1>
|
||||
<p className="mt-2 text-sm text-[#b9bdc9]">Введите почту или телефон. Пароль не нужен.</p>
|
||||
</div>
|
||||
<form className="mt-8 space-y-3" onSubmit={handleSubmit}>
|
||||
<Tabs value={authTab} onValueChange={(value) => setAuthTab(value as 'email' | 'phone')} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="email">Почта</TabsTrigger>
|
||||
<TabsTrigger value="phone">Телефон</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="email">
|
||||
<Input
|
||||
className="h-[56px] border-[#555762] bg-transparent text-white placeholder:text-[#8f92a0]"
|
||||
placeholder="name@example.com"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
required={authTab === 'email'}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="phone">
|
||||
<PhoneInput country={country} value={phoneNumber} onCountryChange={setCountry} onValueChange={setPhoneNumber} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<Button variant="white" size="lg" className="w-full rounded-[18px]" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Отправляем...' : 'Получить код'}
|
||||
</Button>
|
||||
</form>
|
||||
<div className="mt-5 flex items-start gap-3 rounded-[22px] bg-[#2a2c36] p-4 text-sm">
|
||||
<ShieldCheck className="mt-0.5 h-5 w-5 text-[#8ec5ff]" />
|
||||
<p>Первый зарегистрированный пользователь автоматически станет суперадминистратором.</p>
|
||||
</div>
|
||||
<Button asChild variant="ghost" className="mt-5 w-full text-white hover:bg-[#2a2c36]">
|
||||
<Link href="/auth/login">У меня уже есть ID</Link>
|
||||
</Button>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
291
apps/frontend/app/data/page.tsx
Normal file
291
apps/frontend/app/data/page.tsx
Normal file
@@ -0,0 +1,291 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Car, ChevronRight, FileText, Loader2, Mail, Phone, Trash2, UserRound } from 'lucide-react';
|
||||
import { AddressQuickSection } from '@/components/addresses/address-quick-section';
|
||||
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
|
||||
import { ActionTile } from '@/components/id/action-tile';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { AvatarDisplay, AvatarUpload } from '@/components/id/avatar-upload';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
import {
|
||||
getDocumentType,
|
||||
indexDocumentsByType,
|
||||
type DocumentTypeCode
|
||||
} from '@/lib/document-catalog';
|
||||
import { apiFetch, getApiErrorMessage, softDeleteProfile, UserDocument } from '@/lib/api';
|
||||
|
||||
function Row({
|
||||
icon: Icon,
|
||||
title,
|
||||
text,
|
||||
onClick,
|
||||
destructive
|
||||
}: {
|
||||
icon: typeof Mail;
|
||||
title: string;
|
||||
text?: string;
|
||||
onClick?: () => void;
|
||||
destructive?: boolean;
|
||||
}) {
|
||||
const content = (
|
||||
<>
|
||||
<div className={`flex h-11 w-11 items-center justify-center rounded-2xl ${destructive ? 'bg-red-50' : 'bg-[#f4f5f8]'}`}>
|
||||
<Icon className={`h-5 w-5 ${destructive ? 'text-red-500' : ''}`} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className={`font-medium ${destructive ? 'text-red-600' : ''}`}>{title}</div>
|
||||
{text ? <div className="truncate text-sm text-[#667085]">{text}</div> : null}
|
||||
</div>
|
||||
{onClick ? <ChevronRight className="h-5 w-5 text-[#a8adbc]" /> : null}
|
||||
</>
|
||||
);
|
||||
|
||||
if (!onClick) {
|
||||
return <div className="flex items-center gap-4 border-b border-[#eceef4] py-4">{content}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="flex w-full items-center gap-4 border-b border-[#eceef4] py-4 text-left transition hover:bg-[#fafbfd]"
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DataPage() {
|
||||
const router = useRouter();
|
||||
const { user, token, refreshProfile, logout } = useAuth();
|
||||
const { isReady, isPinLocked } = useRequireAuth();
|
||||
const { showToast } = useToast();
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [backupEmail, setBackupEmail] = useState('');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [backupPhone, setBackupPhone] = useState('');
|
||||
const [documents, setDocuments] = useState<UserDocument[]>([]);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [activeDocumentType, setActiveDocumentType] = useState<DocumentTypeCode | null>(null);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
|
||||
const loadDocuments = useCallback(async () => {
|
||||
if (!user || !token || isPinLocked) return;
|
||||
try {
|
||||
const response = await apiFetch<{ documents?: UserDocument[] }>(`/documents/users/${user.id}`, {}, token);
|
||||
setDocuments(response.documents ?? []);
|
||||
} catch (error) {
|
||||
const message = getApiErrorMessage(error, 'Не удалось загрузить документы');
|
||||
if (message) showToast(message);
|
||||
}
|
||||
}, [isPinLocked, showToast, token, user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
setDisplayName(user.displayName);
|
||||
setEmail(user.email ?? '');
|
||||
setBackupEmail(user.backupEmail ?? '');
|
||||
setPhone(user.phone ?? '');
|
||||
setBackupPhone(user.backupPhone ?? '');
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isReady && user && !isPinLocked) void loadDocuments();
|
||||
}, [isPinLocked, isReady, loadDocuments, user]);
|
||||
|
||||
const documentsByType = useMemo(() => indexDocumentsByType(documents), [documents]);
|
||||
|
||||
function openDocument(type: DocumentTypeCode) {
|
||||
setActiveDocumentType(type);
|
||||
}
|
||||
|
||||
async function updateProfile() {
|
||||
if (!user || !token) return;
|
||||
setIsSaving(true);
|
||||
const trimmedName = displayName.trim();
|
||||
const [firstName, ...rest] = trimmedName.split(' ');
|
||||
try {
|
||||
await apiFetch(`/profile/users/${user.id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ firstName: firstName || undefined, lastName: rest.join(' ') || undefined })
|
||||
}, token);
|
||||
|
||||
const contacts: Record<string, string> = {};
|
||||
if (email.trim() && email.trim() !== (user.email ?? '')) contacts.email = email.trim();
|
||||
if (phone.trim() && phone.trim() !== (user.phone ?? '')) contacts.phone = phone.trim();
|
||||
if (backupEmail.trim() && backupEmail.trim() !== (user.backupEmail ?? '')) contacts.backupEmail = backupEmail.trim();
|
||||
if (backupPhone.trim() && backupPhone.trim() !== (user.backupPhone ?? '')) contacts.backupPhone = backupPhone.trim();
|
||||
|
||||
if (Object.keys(contacts).length > 0) {
|
||||
await apiFetch(`/profile/users/${user.id}/contacts`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(contacts)
|
||||
}, token);
|
||||
}
|
||||
|
||||
await refreshProfile();
|
||||
showToast('Профиль обновлён');
|
||||
} catch (error) {
|
||||
const message = getApiErrorMessage(error, 'Не удалось обновить профиль');
|
||||
if (message) showToast(message);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmDeleteProfile() {
|
||||
if (!user || !token) return;
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await softDeleteProfile(user.id, token);
|
||||
setDeleteDialogOpen(false);
|
||||
showToast('Профиль удалён');
|
||||
logout();
|
||||
} catch (error) {
|
||||
const message = getApiErrorMessage(error, 'Не удалось удалить профиль');
|
||||
if (message) showToast(message);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<IdShell active="/data">
|
||||
<div className="mb-8 flex items-center gap-4 rounded-[24px] border border-[#20212b] p-4">
|
||||
{user ? (
|
||||
<AvatarUpload userId={user.id} displayName={user.displayName} hasAvatar={user.hasAvatar} token={token} onUpdated={refreshProfile} />
|
||||
) : (
|
||||
<AvatarDisplay userId="" displayName="" hasAvatar={false} token={null} className="h-14 w-14" />
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<h1 className="text-lg font-semibold">{user?.displayName ?? 'Профиль'}</h1>
|
||||
<p className="text-sm text-[#667085]">Логин: {user?.username ?? user?.email ?? user?.phone ?? 'не указан'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h2 className="text-2xl font-medium">Личные данные</h2>
|
||||
<p className="mt-1 text-sm text-[#667085]">Эти данные помогают быстрее входить в сервисы и восстанавливать доступ.</p>
|
||||
<div className="mt-5 grid gap-3 sm:grid-cols-2">
|
||||
<Input placeholder="ФИО" value={displayName} onChange={(event) => setDisplayName(event.target.value)} />
|
||||
<Input placeholder="Дата рождения" />
|
||||
<Input placeholder="Основная почта" value={email} onChange={(event) => setEmail(event.target.value)} />
|
||||
<Input placeholder="Резервная почта" value={backupEmail} onChange={(event) => setBackupEmail(event.target.value)} />
|
||||
<Input placeholder="Основной телефон" value={phone} onChange={(event) => setPhone(event.target.value)} />
|
||||
<Input placeholder="Резервный телефон" value={backupPhone} onChange={(event) => setBackupPhone(event.target.value)} />
|
||||
</div>
|
||||
<Button className="mt-4" onClick={updateProfile} disabled={isSaving}>
|
||||
{isSaving ? 'Сохраняем...' : 'Обновить профиль'}
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
<section className="mt-10">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-medium">Документы</h2>
|
||||
<p className="mt-1 text-sm text-[#667085]">ID бережно хранит документы и подставляет их там, где вы разрешили.</p>
|
||||
</div>
|
||||
<Button variant="secondary" onClick={() => router.push('/documents')}>Все документы</Button>
|
||||
</div>
|
||||
<div className="mt-5 grid grid-cols-4 gap-3">
|
||||
<ActionTile icon={FileText} label="Паспорт РФ" onClick={() => openDocument('PASSPORT_RF')} />
|
||||
<ActionTile icon={FileText} label="Загран" onClick={() => openDocument('FOREIGN_PASSPORT')} />
|
||||
<ActionTile icon={Car} label="ВУ" onClick={() => openDocument('DRIVER_LICENSE')} />
|
||||
<ActionTile icon={FileText} label="ОМС" onClick={() => openDocument('OMS')} />
|
||||
</div>
|
||||
<div className="mt-4 overflow-hidden rounded-[24px] bg-[#f4f5f8]">
|
||||
{documents.length === 0 ? (
|
||||
<p className="px-4 py-6 text-center text-sm text-[#667085]">Документы пока не добавлены</p>
|
||||
) : (
|
||||
documents.map((document) => {
|
||||
const config = getDocumentType(document.type);
|
||||
return (
|
||||
<Row
|
||||
key={document.id}
|
||||
icon={FileText}
|
||||
title={config?.label ?? document.type}
|
||||
text={document.number}
|
||||
onClick={() => openDocument(document.type as DocumentTypeCode)}
|
||||
/>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<AddressQuickSection layout="data" isPinLocked={isPinLocked} isReady={isReady} />
|
||||
|
||||
<section className="mt-10">
|
||||
<h2 className="text-2xl font-medium">Контакты</h2>
|
||||
<Row icon={Mail} title="Email в ID" text={email || 'Не указан'} />
|
||||
<Row icon={Phone} title="Основной телефон" text={phone || 'Не указан'} />
|
||||
<Row icon={Mail} title="Запасная почта" text={backupEmail || 'Не указана'} />
|
||||
<Row icon={UserRound} title="Добавить внешние аккаунты" text="Помогут быстрее входить и заполнить данные" />
|
||||
</section>
|
||||
|
||||
<section className="mt-10">
|
||||
<h2 className="text-2xl font-medium">Управление данными</h2>
|
||||
<div className="mt-2 overflow-hidden rounded-[24px] border border-red-100 bg-red-50/40">
|
||||
<Row
|
||||
icon={Trash2}
|
||||
title="Удалить профиль"
|
||||
text="Аккаунт будет деактивирован, вход станет невозможен"
|
||||
onClick={() => setDeleteDialogOpen(true)}
|
||||
destructive
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{activeDocumentType && user ? (
|
||||
<DocumentFormDialog
|
||||
open={Boolean(activeDocumentType)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setActiveDocumentType(null);
|
||||
}}
|
||||
documentType={activeDocumentType}
|
||||
userId={user.id}
|
||||
token={token}
|
||||
existing={documentsByType.get(activeDocumentType) ?? null}
|
||||
onSaved={loadDocuments}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[440px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Удалить профиль?</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm leading-relaxed text-[#667085]">
|
||||
Ваш аккаунт будет помечен как удалённый. Вы сразу выйдете из системы и больше не сможете войти с текущими
|
||||
данными. Почта, телефон и логин будут освобождены для новой регистрации. Административные роли будут сняты.
|
||||
Запись в базе сохранится в архивном виде.
|
||||
</p>
|
||||
<div className="mt-6 flex gap-3">
|
||||
<Button variant="secondary" className="flex-1" onClick={() => setDeleteDialogOpen(false)} disabled={isDeleting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button className="flex-1 bg-red-600 hover:bg-red-700" onClick={() => void confirmDeleteProfile()} disabled={isDeleting}>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Удаляем...
|
||||
</>
|
||||
) : (
|
||||
'Удалить профиль'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
133
apps/frontend/app/documents/page.tsx
Normal file
133
apps/frontend/app/documents/page.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ChevronRight, Plus } from 'lucide-react';
|
||||
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import {
|
||||
DOCUMENT_CATEGORIES,
|
||||
DOCUMENT_TYPES,
|
||||
getDocumentType,
|
||||
QUICK_DOCUMENT_TYPES,
|
||||
indexDocumentsByType,
|
||||
type DocumentTypeCode
|
||||
} from '@/lib/document-catalog';
|
||||
import { apiFetch, getApiErrorMessage, UserDocument } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
|
||||
export default function DocumentsPage() {
|
||||
const router = useRouter();
|
||||
const { user, token } = useAuth();
|
||||
const { isReady, isPinLocked } = useRequireAuth();
|
||||
const { showToast } = useToast();
|
||||
const [documents, setDocuments] = useState<UserDocument[]>([]);
|
||||
const [activeType, setActiveType] = useState<DocumentTypeCode | null>(null);
|
||||
|
||||
const loadDocuments = useCallback(async () => {
|
||||
if (!user || !token || isPinLocked) return;
|
||||
try {
|
||||
const response = await apiFetch<{ documents?: UserDocument[] }>(`/documents/users/${user.id}`, {}, token);
|
||||
setDocuments(response.documents ?? []);
|
||||
} catch (error) {
|
||||
const message = getApiErrorMessage(error, 'Не удалось загрузить документы');
|
||||
if (message) showToast(message);
|
||||
}
|
||||
}, [isPinLocked, showToast, token, user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isReady || !user || isPinLocked) return;
|
||||
void loadDocuments();
|
||||
}, [isPinLocked, isReady, loadDocuments, user]);
|
||||
|
||||
const documentsByType = useMemo(() => indexDocumentsByType(documents), [documents]);
|
||||
|
||||
function openCreate(type: DocumentTypeCode) {
|
||||
setActiveType(type);
|
||||
}
|
||||
|
||||
return (
|
||||
<IdShell active="/documents" wide>
|
||||
<h1 className="text-3xl font-medium tracking-tight">Документы</h1>
|
||||
<p className="mt-1 text-sm text-[#667085]">Храните документы и заполняйте формы — ID подставит данные там, где вы разрешите.</p>
|
||||
|
||||
<div className="mt-6 overflow-hidden rounded-[28px] bg-[linear-gradient(135deg,#fff4f4,#fff8ef)] p-5">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-lg font-medium">Здесь будут ваши документы</p>
|
||||
<p className="mt-1 text-sm text-[#667085]">Добавьте паспорт, права или полис — данные сохранятся в зашифрованном виде.</p>
|
||||
</div>
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-3xl bg-white text-3xl shadow-sm">🛂</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 grid grid-cols-3 gap-3">
|
||||
{QUICK_DOCUMENT_TYPES.map((typeCode) => {
|
||||
const config = getDocumentType(typeCode);
|
||||
if (!config) return null;
|
||||
const Icon = config.icon;
|
||||
return (
|
||||
<button
|
||||
key={typeCode}
|
||||
type="button"
|
||||
onClick={() => openCreate(typeCode)}
|
||||
className="flex min-h-[110px] flex-col items-center justify-center gap-2 rounded-[22px] bg-[#f4f5f8] p-3 text-center transition hover:bg-[#eceef4]"
|
||||
>
|
||||
<div className={cn('flex h-12 w-12 items-center justify-center rounded-2xl', config.accent)}>
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<span className="text-[12px] font-medium leading-tight">Добавить {config.shortLabel.toLowerCase()}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{DOCUMENT_CATEGORIES.map((category) => (
|
||||
<section key={category.id} className="mt-8">
|
||||
<h2 className="mb-3 text-xl font-medium">{category.title}</h2>
|
||||
<div className="overflow-hidden rounded-[24px] bg-[#f4f5f8]">
|
||||
{DOCUMENT_TYPES.filter((item) => item.category === category.id).map((item) => {
|
||||
const Icon = item.icon;
|
||||
const existing = documentsByType.get(item.type);
|
||||
return (
|
||||
<button
|
||||
key={item.type}
|
||||
type="button"
|
||||
onClick={() => openCreate(item.type)}
|
||||
className="flex w-full items-center gap-4 border-b border-white/70 px-4 py-4 text-left last:border-b-0 hover:bg-white/60"
|
||||
>
|
||||
<div className={cn('flex h-11 w-11 items-center justify-center rounded-2xl', item.accent)}>
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="font-medium">{item.label}</div>
|
||||
{existing ? <div className="truncate text-sm text-[#667085]">{existing.number}</div> : null}
|
||||
</div>
|
||||
{existing ? <ChevronRight className="h-5 w-5 text-[#a8adbc]" /> : <Plus className="h-5 w-5 text-[#a8adbc]" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
{activeType ? (
|
||||
<DocumentFormDialog
|
||||
open={Boolean(activeType)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setActiveType(null);
|
||||
}}
|
||||
documentType={activeType}
|
||||
userId={user?.id ?? ''}
|
||||
token={token}
|
||||
existing={documentsByType.get(activeType) ?? null}
|
||||
onSaved={loadDocuments}
|
||||
/>
|
||||
) : null}
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
14
apps/frontend/app/family/[groupId]/page.tsx
Normal file
14
apps/frontend/app/family/[groupId]/page.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
'use client';
|
||||
|
||||
import { use } from 'react';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { FamilyGroupView } from '@/components/family/family-group-view';
|
||||
|
||||
export default function FamilyGroupPage({ params }: { params: Promise<{ groupId: string }> }) {
|
||||
const { groupId } = use(params);
|
||||
return (
|
||||
<IdShell active="/family" wide>
|
||||
<FamilyGroupView groupId={groupId} />
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
97
apps/frontend/app/family/page.tsx
Normal file
97
apps/frontend/app/family/page.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ChevronRight, Heart, Plus, UsersRound } from 'lucide-react';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
import { apiFetch, FamilyGroup, fetchFamilyGroups, getApiErrorMessage } from '@/lib/api';
|
||||
|
||||
export default function FamilyPage() {
|
||||
const router = useRouter();
|
||||
const { user, token } = useAuth();
|
||||
const { isReady, isPinLocked } = useRequireAuth();
|
||||
const { showToast } = useToast();
|
||||
const [groups, setGroups] = useState<FamilyGroup[]>([]);
|
||||
const [name, setName] = useState('Моя семья');
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || !token || isPinLocked) return;
|
||||
fetchFamilyGroups(user.id, token)
|
||||
.then((response) => setGroups(response.groups ?? []))
|
||||
.catch((error) => {
|
||||
const message = getApiErrorMessage(error, 'Не удалось загрузить семью');
|
||||
if (message) showToast(message);
|
||||
});
|
||||
}, [isPinLocked, showToast, token, user]);
|
||||
|
||||
async function createGroup() {
|
||||
if (!user || !token) return;
|
||||
setCreating(true);
|
||||
try {
|
||||
const group = await apiFetch<FamilyGroup>('/family/groups', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ownerId: user.id, name })
|
||||
}, token);
|
||||
router.push(`/family/${group.id}`);
|
||||
} catch (error) {
|
||||
const message = getApiErrorMessage(error, 'Не удалось создать семью');
|
||||
if (message) showToast(message);
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isReady) {
|
||||
return (
|
||||
<IdShell active="/family">
|
||||
<div className="py-20 text-center text-[#667085]">Загрузка...</div>
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IdShell active="/family" wide>
|
||||
<p className="text-sm text-[#667085]">Семья</p>
|
||||
<h1 className="text-4xl font-medium tracking-tight">Семейный доступ</h1>
|
||||
<p className="mt-2 text-[#667085]">Приглашайте близких, общайтесь в чатах и управляйте семейной группой.</p>
|
||||
|
||||
<div className="mt-8 flex gap-3">
|
||||
<Input value={name} onChange={(event) => setName(event.target.value)} placeholder="Название семьи" />
|
||||
<Button onClick={() => void createGroup()} disabled={creating}>
|
||||
{creating ? 'Создаём...' : (<><Plus className="h-4 w-4" />Создать</>)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 space-y-3">
|
||||
{groups.length ? groups.map((group) => (
|
||||
<button
|
||||
key={group.id}
|
||||
type="button"
|
||||
onClick={() => router.push(`/family/${group.id}`)}
|
||||
className="flex w-full items-center gap-4 rounded-[24px] bg-[#f4f5f8] p-5 text-left transition hover:bg-[#eceef4]"
|
||||
>
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-white">
|
||||
<Heart className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h2 className="font-semibold">{group.name}</h2>
|
||||
<p className="text-sm text-[#667085]">{(group.members ?? []).length} участников</p>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-[#a8adbc]" />
|
||||
</button>
|
||||
)) : (
|
||||
<div className="rounded-[24px] bg-[#f4f5f8] p-5 text-[#667085]">
|
||||
<UsersRound className="mb-3 h-6 w-6" />
|
||||
Семейных групп пока нет
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
45
apps/frontend/app/globals.css
Normal file
45
apps/frontend/app/globals.css
Normal file
@@ -0,0 +1,45 @@
|
||||
@import "tailwindcss";
|
||||
@import "leaflet/dist/leaflet.css";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #111827;
|
||||
--muted: #f4f5f8;
|
||||
--muted-foreground: #667085;
|
||||
--border: #e6e8ef;
|
||||
--primary: #20212b;
|
||||
--primary-foreground: #ffffff;
|
||||
--radius: 1.25rem;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.soft-card {
|
||||
border-radius: 24px;
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.id-shadow {
|
||||
box-shadow: 0 24px 70px rgb(22 26 43 / 12%);
|
||||
}
|
||||
28
apps/frontend/app/icon.tsx
Normal file
28
apps/frontend/app/icon.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { ImageResponse } from 'next/og';
|
||||
|
||||
export const size = { width: 32, height: 32 };
|
||||
export const contentType = 'image/png';
|
||||
|
||||
export default function Icon() {
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'linear-gradient(135deg, #6f58ff, #ffd2a8)',
|
||||
borderRadius: 8,
|
||||
color: 'white',
|
||||
fontSize: 14,
|
||||
fontWeight: 700
|
||||
}}
|
||||
>
|
||||
ID
|
||||
</div>
|
||||
),
|
||||
size
|
||||
);
|
||||
}
|
||||
18
apps/frontend/app/layout.tsx
Normal file
18
apps/frontend/app/layout.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { Providers } from './providers';
|
||||
import './globals.css';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'MVK ID',
|
||||
description: 'Единый аккаунт для сервисов Lendry'
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||
return (
|
||||
<html lang="ru">
|
||||
<body>
|
||||
<Providers>{children}</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
137
apps/frontend/app/page.tsx
Normal file
137
apps/frontend/app/page.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { BadgeCheck, Bell, Car, FileText, Fingerprint, Heart, KeyRound, PawPrint, ShieldCheck, Smartphone, UserRound } from 'lucide-react';
|
||||
import { AddressQuickSection } from '@/components/addresses/address-quick-section';
|
||||
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
|
||||
import { ActionTile, SectionTitle } from '@/components/id/action-tile';
|
||||
import { AdminBadge } from '@/components/id/admin-badge';
|
||||
import { AvatarUpload } from '@/components/id/avatar-upload';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
import { type DocumentTypeCode, indexDocumentsByType } from '@/lib/document-catalog';
|
||||
import { apiFetch, UserDocument } from '@/lib/api';
|
||||
|
||||
export default function HomePage() {
|
||||
const router = useRouter();
|
||||
const { user, token, refreshProfile, isPinLocked } = useAuth();
|
||||
const { isReady } = useRequireAuth();
|
||||
const contactLine = [user?.phone, user?.username ?? user?.email].filter(Boolean).join(' · ');
|
||||
const [documents, setDocuments] = useState<UserDocument[]>([]);
|
||||
const [activeDocumentType, setActiveDocumentType] = useState<DocumentTypeCode | null>(null);
|
||||
|
||||
const loadDocuments = useCallback(async () => {
|
||||
if (!user || !token || isPinLocked) return;
|
||||
try {
|
||||
const response = await apiFetch<{ documents?: UserDocument[] }>(`/documents/users/${user.id}`, {}, token);
|
||||
setDocuments(response.documents ?? []);
|
||||
} catch {
|
||||
setDocuments([]);
|
||||
}
|
||||
}, [isPinLocked, token, user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isReady && user && !isPinLocked) void loadDocuments();
|
||||
}, [isPinLocked, isReady, loadDocuments, user]);
|
||||
|
||||
const documentsByType = useMemo(() => indexDocumentsByType(documents), [documents]);
|
||||
|
||||
function openDocument(type: DocumentTypeCode) {
|
||||
setActiveDocumentType(type);
|
||||
}
|
||||
|
||||
if (!isReady) {
|
||||
return (
|
||||
<IdShell active="/" wide>
|
||||
<div className="py-20 text-center text-[#667085]">Загрузка профиля...</div>
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IdShell active="/" wide>
|
||||
<div className="flex flex-col items-center">
|
||||
{user ? (
|
||||
<AvatarUpload
|
||||
userId={user.id}
|
||||
displayName={user.displayName}
|
||||
hasAvatar={user.hasAvatar}
|
||||
token={token}
|
||||
onUpdated={refreshProfile}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-24 w-24 rounded-full bg-[#f4f5f8]" />
|
||||
)}
|
||||
<h1 className="mt-4 text-2xl font-semibold">{user?.displayName ?? 'Загрузка профиля...'}</h1>
|
||||
{user ? <AdminBadge user={user} className="mt-2" /> : null}
|
||||
<p className="text-sm text-[#667085]">{contactLine || 'Данные профиля загружаются'}</p>
|
||||
<div className="mt-4 flex gap-3">
|
||||
<Button variant="secondary" size="sm" onClick={() => router.push('/family')}>
|
||||
<Heart className="h-4 w-4 text-red-500" />
|
||||
Семья
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={() => router.push('/data')}>
|
||||
<UserRound className="h-4 w-4" />
|
||||
Профиль
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex w-full max-w-[450px] items-center justify-between rounded-[24px] bg-[#f0f2f7] p-5">
|
||||
<div>
|
||||
<h2 className="font-semibold">Защитите ваш аккаунт</h2>
|
||||
<p className="mt-1 text-sm text-[#667085]">Настройте PIN-код и способы восстановления</p>
|
||||
<Button className="mt-4 rounded-xl" size="sm" onClick={() => router.push('/security')}>
|
||||
Перейти к защите
|
||||
</Button>
|
||||
</div>
|
||||
<BadgeCheck className="h-20 w-20 text-[#68b8ff]" />
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-[720px]">
|
||||
<SectionTitle>Защита аккаунта</SectionTitle>
|
||||
<div className="grid grid-cols-3 gap-4 md:grid-cols-5">
|
||||
<ActionTile icon={ShieldCheck} label="Способы входа" onClick={() => router.push('/security')} />
|
||||
<ActionTile icon={Smartphone} label="Проверить устройства" onClick={() => router.push('/security')} />
|
||||
<ActionTile icon={Bell} label="Активность" onClick={() => router.push('/security')} />
|
||||
<ActionTile icon={KeyRound} label="Добавить запасную почту" onClick={() => router.push('/security')} />
|
||||
<ActionTile icon={Fingerprint} label="Привязать лицо или отпечаток" onClick={() => router.push('/security')} />
|
||||
</div>
|
||||
|
||||
<SectionTitle>Документы</SectionTitle>
|
||||
<div className="grid grid-cols-3 gap-4 md:grid-cols-6">
|
||||
<ActionTile icon={FileText} label="Все" onClick={() => router.push('/documents')} />
|
||||
<ActionTile icon={FileText} label="Паспорт" onClick={() => openDocument('PASSPORT_RF')} />
|
||||
<ActionTile icon={FileText} label="Загран" onClick={() => openDocument('FOREIGN_PASSPORT')} />
|
||||
<ActionTile icon={Car} label="ВУ" onClick={() => openDocument('DRIVER_LICENSE')} />
|
||||
</div>
|
||||
|
||||
<AddressQuickSection layout="home" isPinLocked={isPinLocked} isReady={isReady} />
|
||||
|
||||
<SectionTitle>Семья</SectionTitle>
|
||||
<div className="grid grid-cols-3 gap-4 md:grid-cols-6">
|
||||
<ActionTile icon={UserRound} label="Вы" onClick={() => router.push('/family')} />
|
||||
<ActionTile icon={Heart} label="Добавить" onClick={() => router.push('/family')} />
|
||||
<ActionTile icon={PawPrint} label="Питомцы" onClick={() => router.push('/family')} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{activeDocumentType && user ? (
|
||||
<DocumentFormDialog
|
||||
open={Boolean(activeDocumentType)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setActiveDocumentType(null);
|
||||
}}
|
||||
documentType={activeDocumentType}
|
||||
userId={user.id}
|
||||
token={token}
|
||||
existing={documentsByType.get(activeDocumentType) ?? null}
|
||||
onSaved={loadDocuments}
|
||||
/>
|
||||
) : null}
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
20
apps/frontend/app/providers.tsx
Normal file
20
apps/frontend/app/providers.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
'use client';
|
||||
|
||||
import { AuthProvider } from '@/components/id/auth-provider';
|
||||
import { RealtimeProvider } from '@/components/notifications/realtime-provider';
|
||||
import { PublicSettingsProvider } from '@/components/id/public-settings-provider';
|
||||
import { ProjectHead } from '@/components/id/project-head';
|
||||
import { AppToastProvider } from '@/components/id/toast-provider';
|
||||
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<AppToastProvider>
|
||||
<PublicSettingsProvider>
|
||||
<ProjectHead />
|
||||
<AuthProvider>
|
||||
<RealtimeProvider>{children}</RealtimeProvider>
|
||||
</AuthProvider>
|
||||
</PublicSettingsProvider>
|
||||
</AppToastProvider>
|
||||
);
|
||||
}
|
||||
277
apps/frontend/app/security/page.tsx
Normal file
277
apps/frontend/app/security/page.tsx
Normal file
@@ -0,0 +1,277 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
ChevronRight,
|
||||
Clock3,
|
||||
Fingerprint,
|
||||
KeyRound,
|
||||
Laptop,
|
||||
LogOut,
|
||||
Mail,
|
||||
Monitor,
|
||||
type LucideIcon,
|
||||
Phone,
|
||||
ShieldCheck,
|
||||
Smartphone,
|
||||
Speaker,
|
||||
Tv
|
||||
} from 'lucide-react';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ActiveDevice, apiFetch, SignInEvent } from '@/lib/api';
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
const deviceIcons: Record<string, LucideIcon> = {
|
||||
WEB: Monitor,
|
||||
DESKTOP: Monitor,
|
||||
IOS: Smartphone,
|
||||
ANDROID: Smartphone,
|
||||
TV: Tv,
|
||||
SMART_SPEAKER: Speaker,
|
||||
OTHER: Laptop
|
||||
};
|
||||
|
||||
type DialogMode = 'pin' | 'password' | 'backupEmail' | 'backupPhone' | null;
|
||||
|
||||
const dialogConfig: Record<Exclude<DialogMode, null>, { title: string; placeholder: string; type: string }> = {
|
||||
pin: { title: 'Установить PIN-код', placeholder: 'PIN из 4-6 цифр', type: 'password' },
|
||||
password: { title: 'Установить пароль', placeholder: 'Новый пароль (мин. 8 символов)', type: 'password' },
|
||||
backupEmail: { title: 'Резервная почта', placeholder: 'backup@example.com', type: 'email' },
|
||||
backupPhone: { title: 'Резервный телефон', placeholder: '+79991234567', type: 'tel' }
|
||||
};
|
||||
|
||||
export default function SecurityPage() {
|
||||
const router = useRouter();
|
||||
const { user, token, logout } = useAuth();
|
||||
const { isReady } = useRequireAuth();
|
||||
const { showToast } = useToast();
|
||||
const [devices, setDevices] = useState<ActiveDevice[]>([]);
|
||||
const [history, setHistory] = useState<SignInEvent[]>([]);
|
||||
const [isSecurityLoading, setIsSecurityLoading] = useState(true);
|
||||
const [isRevoking, setIsRevoking] = useState(false);
|
||||
const [dialogMode, setDialogMode] = useState<DialogMode>(null);
|
||||
const [dialogValue, setDialogValue] = useState('');
|
||||
const [isDialogSaving, setIsDialogSaving] = useState(false);
|
||||
|
||||
const loadSecurity = useCallback(async () => {
|
||||
if (!user || !token) return;
|
||||
setIsSecurityLoading(true);
|
||||
try {
|
||||
const [devicesResponse, historyResponse] = await Promise.all([
|
||||
apiFetch<{ devices: ActiveDevice[] }>(`/security/users/${user.id}/devices`, {}, token),
|
||||
apiFetch<{ events: SignInEvent[] }>(`/security/users/${user.id}/sign-in-history`, {}, token)
|
||||
]);
|
||||
setDevices(devicesResponse.devices ?? []);
|
||||
setHistory(historyResponse.events ?? []);
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось загрузить безопасность');
|
||||
} finally {
|
||||
setIsSecurityLoading(false);
|
||||
}
|
||||
}, [showToast, token, user]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isReady || !user) return;
|
||||
void loadSecurity();
|
||||
}, [isReady, loadSecurity, user]);
|
||||
|
||||
async function revokeDevice(deviceId: string) {
|
||||
if (!user || !token) return;
|
||||
try {
|
||||
await apiFetch(`/security/users/${user.id}/devices/${deviceId}/revoke`, { method: 'POST' }, token);
|
||||
setDevices((current) => current.filter((device) => device.id !== deviceId));
|
||||
showToast('Сессии устройства завершены');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось завершить сессию');
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeAllSessions() {
|
||||
if (!user || !token) return;
|
||||
setIsRevoking(true);
|
||||
try {
|
||||
await apiFetch(`/security/users/${user.id}/revoke-all-sessions`, { method: 'POST' }, token);
|
||||
showToast('Все сессии завершены');
|
||||
logout();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось выйти везде');
|
||||
} finally {
|
||||
setIsRevoking(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitDialog() {
|
||||
if (!user || !token || !dialogMode) return;
|
||||
setIsDialogSaving(true);
|
||||
try {
|
||||
if (dialogMode === 'pin') {
|
||||
await apiFetch(`/security/users/${user.id}/pin/setup`, { method: 'POST', body: JSON.stringify({ pin: dialogValue.trim() }) }, token);
|
||||
showToast('PIN-код установлен');
|
||||
} else if (dialogMode === 'password') {
|
||||
await apiFetch(`/profile/users/${user.id}/password`, { method: 'POST', body: JSON.stringify({ password: dialogValue }) }, token);
|
||||
showToast('Пароль установлен');
|
||||
} else if (dialogMode === 'backupEmail') {
|
||||
await apiFetch(`/profile/users/${user.id}/contacts`, { method: 'PATCH', body: JSON.stringify({ backupEmail: dialogValue.trim() }) }, token);
|
||||
showToast('Резервная почта добавлена');
|
||||
} else if (dialogMode === 'backupPhone') {
|
||||
await apiFetch(`/profile/users/${user.id}/contacts`, { method: 'PATCH', body: JSON.stringify({ backupPhone: dialogValue.trim() }) }, token);
|
||||
showToast('Резервный телефон добавлен');
|
||||
}
|
||||
setDialogMode(null);
|
||||
setDialogValue('');
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось сохранить');
|
||||
} finally {
|
||||
setIsDialogSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
function openDialog(mode: Exclude<DialogMode, null>) {
|
||||
setDialogValue('');
|
||||
setDialogMode(mode);
|
||||
}
|
||||
|
||||
return (
|
||||
<IdShell active="/security">
|
||||
<p className="text-sm text-[#667085]">Безопасность</p>
|
||||
<h1 className="text-4xl font-medium tracking-tight">Устройства</h1>
|
||||
<p className="mt-2 max-w-[460px] text-base">На них вы вошли в ID и получаете уведомления безопасности от сервисов</p>
|
||||
|
||||
<div className="mt-8 space-y-2">
|
||||
{isSecurityLoading ? (
|
||||
<div className="rounded-[20px] bg-[#f4f5f8] px-4 py-5 text-[#667085]">Загружаем устройства...</div>
|
||||
) : devices.length ? (
|
||||
devices.map((device) => {
|
||||
const Icon = deviceIcons[device.type] ?? Laptop;
|
||||
return (
|
||||
<div key={device.id} className="flex items-center gap-4 rounded-[20px] bg-[#f4f5f8] px-4 py-3">
|
||||
<div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-white">
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="block truncate font-medium">{device.name}</span>
|
||||
<span className="text-xs text-[#667085]">{device.lastIp ?? 'IP не сохранён'} · {formatDate(device.lastSeenAt)}</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="shrink-0 text-[#d14343] hover:bg-[#fbeaea]" onClick={() => revokeDevice(device.id)}>
|
||||
Выйти
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div className="rounded-[20px] bg-[#f4f5f8] px-4 py-5 text-[#667085]">Активных устройств пока нет</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 space-y-1">
|
||||
<button type="button" onClick={revokeAllSessions} disabled={isRevoking || !user} className="flex w-full items-center gap-4 border-t border-[#eceef4] py-4 text-left disabled:opacity-60">
|
||||
<LogOut className="h-6 w-6" />
|
||||
<span>{isRevoking ? 'Выходим...' : 'Выйти везде'}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section className="mt-10">
|
||||
<h2 className="text-2xl font-medium">Способ входа в профиль</h2>
|
||||
<div className="mt-4 space-y-2">
|
||||
<button type="button" onClick={() => openDialog('pin')} className="flex w-full items-center gap-4 rounded-[18px] bg-[#f8f9fb] p-4 text-left hover:bg-[#f1f2f6]">
|
||||
<Fingerprint className="h-5 w-5" />
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">PIN-код</p>
|
||||
<p className="text-sm text-[#667085]">Установить или изменить PIN для входа</p>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-[#a8adbc]" />
|
||||
</button>
|
||||
<button type="button" onClick={() => openDialog('password')} className="flex w-full items-center gap-4 rounded-[18px] bg-[#f8f9fb] p-4 text-left hover:bg-[#f1f2f6]">
|
||||
<KeyRound className="h-5 w-5" />
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">Пароль</p>
|
||||
<p className="text-sm text-[#667085]">{user?.email || user?.phone ? 'Добавить пароль как способ входа' : 'Установить пароль'}</p>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-[#a8adbc]" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mt-10">
|
||||
<h2 className="text-2xl font-medium">Способы восстановления</h2>
|
||||
<div className="mt-4 space-y-2">
|
||||
<button type="button" onClick={() => openDialog('backupEmail')} className="flex w-full items-center gap-4 rounded-[18px] bg-[#f8f9fb] p-4 text-left hover:bg-[#f1f2f6]">
|
||||
<Mail className="h-5 w-5" />
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">Резервная почта</p>
|
||||
<p className="text-sm text-[#667085]">{user?.backupEmail || 'Не добавлена'}</p>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-[#a8adbc]" />
|
||||
</button>
|
||||
<button type="button" onClick={() => openDialog('backupPhone')} className="flex w-full items-center gap-4 rounded-[18px] bg-[#f8f9fb] p-4 text-left hover:bg-[#f1f2f6]">
|
||||
<Phone className="h-5 w-5" />
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">Резервный телефон</p>
|
||||
<p className="text-sm text-[#667085]">{user?.backupPhone || 'Не добавлен'}</p>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-[#a8adbc]" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mt-10">
|
||||
<h2 className="text-2xl font-medium">Активность</h2>
|
||||
<div className="mt-4 space-y-3">
|
||||
{isSecurityLoading ? (
|
||||
<div className="text-[#667085]">Загружаем историю входов...</div>
|
||||
) : history.length ? (
|
||||
history.map((item) => (
|
||||
<div key={item.id} className="flex items-center gap-4 border-b border-[#eceef4] pb-3">
|
||||
<Clock3 className="h-5 w-5" />
|
||||
<span className="flex-1">{item.success ? 'Успешный вход' : item.reason ?? 'Неудачная попытка входа'}</span>
|
||||
<span className="text-sm text-[#667085]">{formatDate(item.createdAt)}</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="text-[#667085]">История входов пока пуста</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Dialog open={dialogMode !== null} onOpenChange={(open) => (open ? null : setDialogMode(null))}>
|
||||
<DialogContent>
|
||||
{dialogMode ? (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{dialogConfig[dialogMode].title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-4">
|
||||
<ShieldCheck className="h-5 w-5 text-[#667085]" />
|
||||
<Input
|
||||
className="border-0 bg-transparent focus:ring-0"
|
||||
type={dialogConfig[dialogMode].type}
|
||||
placeholder={dialogConfig[dialogMode].placeholder}
|
||||
value={dialogValue}
|
||||
onChange={(event) => setDialogValue(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button className="mt-5 w-full" onClick={submitDialog} disabled={isDialogSaving || !dialogValue.trim()}>
|
||||
{isDialogSaving ? 'Сохраняем...' : 'Сохранить'}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</IdShell>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user