Merge branch 'master' into dev

This commit is contained in:
2025-12-16 14:22:11 +03:30
6 changed files with 115 additions and 39 deletions
+3
View File
@@ -5,5 +5,8 @@
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.fixAll.eslint": "explicit"
},
"[typescript]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
}
}
@@ -0,0 +1,66 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, Inject, Logger } from '@nestjs/common';
import { Request } from 'express';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class SuperAdminAuthGuard implements CanActivate {
private readonly logger = new Logger(SuperAdminAuthGuard.name);
constructor(
@Inject(ConfigService)
private readonly configService: ConfigService,
) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
try {
const credentials = this.extractBasicAuthCredentials(request);
if (!credentials) {
throw new UnauthorizedException('Basic authentication required');
}
const { username, password } = credentials;
const expectedUsername = this.configService.get<string>('SUPER_ADMIN_USERNAME') ?? 'danak@dsc.com';
const expectedPassword = this.configService.get<string>('SUPER_ADMIN_PASSWORD') ?? 'DsCdAnAk?@ABC';
if (username !== expectedUsername || password !== expectedPassword) {
this.logger.warn(`Invalid super admin credentials attempt for username: ${username}`);
throw new UnauthorizedException('Invalid credentials');
}
return true;
} catch (err) {
if (err instanceof UnauthorizedException) {
throw err;
}
this.logger.error('error in SuperAdminAuthGuard', err);
throw new UnauthorizedException('Authentication failed');
}
}
private extractBasicAuthCredentials(request: Request): { username: string; password: string } | null {
const authHeader = request.headers.authorization;
if (!authHeader) {
return null;
}
const [type, encoded] = authHeader.split(' ');
if (type?.toLowerCase() !== 'basic' || !encoded) {
return null;
}
try {
const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
const [username, password] = decoded.split(':');
if (!username || !password) {
return null;
}
return { username, password };
} catch (error) {
this.logger.error('Failed to decode Basic Auth credentials', error);
return null;
}
}
}
@@ -8,106 +8,108 @@ import { UpdateGroupDto } from '../dto/update-group.dto';
import {
ApiTags,
ApiOperation,
ApiCreatedResponse,
ApiOkResponse,
ApiNotFoundResponse,
ApiParam,
ApiBody,
ApiBearerAuth,
} from '@nestjs/swagger';
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
import { SuperAdminAuthGuard } from 'src/modules/auth/guards/superAdminAuth.guard';
import { UseGuards } from '@nestjs/common';
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
@ApiTags('icons')
@Controller('admin/icons')
@UseGuards(AdminAuthGuard)
@Controller()
@ApiBearerAuth()
export class IconsController {
constructor(
private readonly iconService: IconService,
private readonly groupService: GroupService,
) {}
) { }
// Icon endpoints
@Post()
@Get('admin/groups/icons')
@UseGuards(AdminAuthGuard)
@ApiOperation({ summary: 'Get all icons' })
findAllPublicIcons() {
return this.groupService.findAllPublic();
}
@Post('super-admin/icons')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Create icon' })
@ApiCreatedResponse({ description: 'Icon created', type: CreateIconDto })
@ApiBody({ type: CreateIconDto })
createIcon(@Body() dto: CreateIconDto) {
return this.iconService.create(dto);
}
@Get()
@Get('super-admin/icons')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Get all icons' })
@ApiOkResponse({ description: 'List of all icons' })
findAllIcons() {
return this.iconService.findAll();
}
@Get(':id')
@Get('super-admin/icons/:id')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Get icon by id' })
@ApiOkResponse({ description: 'Icon detail', type: CreateIconDto })
@ApiNotFoundResponse({ description: 'Icon not found' })
@ApiParam({ name: 'id', required: true, type: String })
findOneIcon(@Param('id') id: string) {
return this.iconService.findOne(id);
}
@Patch(':id')
@Patch('super-admin/icons/:id')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Update icon' })
@ApiParam({ name: 'id' })
@ApiBody({ type: UpdateIconDto })
@ApiOkResponse({ description: 'Updated icon', type: UpdateIconDto })
updateIcon(@Param('id') id: string, @Body() dto: UpdateIconDto) {
return this.iconService.update(id, dto);
}
@Delete(':id')
@Delete('super-admin/icons/:id')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Delete icon' })
@ApiParam({ name: 'id' })
@ApiOkResponse({ description: 'Deleted' })
removeIcon(@Param('id') id: string) {
return this.iconService.remove(id);
}
// Group endpoints (must come before :id routes to avoid route conflicts)
@Post('groups')
@Post('super-admin/icons/groups')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Create icon group' })
@ApiCreatedResponse({ description: 'Group created', type: CreateGroupDto })
@ApiBody({ type: CreateGroupDto })
createGroup(@Body() dto: CreateGroupDto) {
return this.groupService.create(dto);
}
@Get('groups')
@Get('super-admin/icons/groups')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Get all icon groups' })
@ApiOkResponse({ description: 'List of all icon groups' })
findAllGroups() {
return this.groupService.findAll();
}
@Get('groups/:id')
@Get('super-admin/icons/groups/:id')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Get icon group by id' })
@ApiOkResponse({ description: 'Group detail', type: CreateGroupDto })
@ApiNotFoundResponse({ description: 'Group not found' })
@ApiParam({ name: 'id', required: true, type: String })
findOneGroup(@Param('id') id: string) {
return this.groupService.findOne(id);
}
@Patch('groups/:id')
@Patch('super-admin/icons/groups/:id')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Update icon group' })
@ApiParam({ name: 'id' })
@ApiBody({ type: UpdateGroupDto })
@ApiOkResponse({ description: 'Updated group', type: UpdateGroupDto })
updateGroup(@Param('id') id: string, @Body() dto: UpdateGroupDto) {
return this.groupService.update(id, dto);
}
@Delete('groups/:id')
@Delete('super-admin/icons/groups/:id')
@UseGuards(SuperAdminAuthGuard)
@ApiOperation({ summary: 'Delete icon group' })
@ApiParam({ name: 'id' })
@ApiOkResponse({ description: 'Deleted' })
removeGroup(@Param('id') id: string) {
return this.groupService.remove(id);
}
+5 -2
View File
@@ -1,4 +1,4 @@
import { Entity, Index, Property, Collection, OneToMany } from '@mikro-orm/core';
import { Entity, Index, Property, Collection, OneToMany, Cascade } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { Icon } from './icon.entity';
@@ -7,6 +7,9 @@ export class Group extends BaseEntity {
@Property()
name!: string;
@OneToMany(() => Icon, icon => icon.group)
@OneToMany(() => Icon, icon => icon.group,{
cascade: [Cascade.ALL],
orphanRemoval: true,
})
icons = new Collection<Icon>(this);
}
+7 -4
View File
@@ -12,7 +12,7 @@ export class GroupService {
constructor(
private readonly groupRepository: GroupRepository,
private readonly em: EntityManager,
) {}
) { }
async create(dto: CreateGroupDto): Promise<Group> {
const data: RequiredEntityData<Group> = {
@@ -47,12 +47,15 @@ export class GroupService {
}
async remove(id: string): Promise<void> {
const group = await this.groupRepository.findOne({ id });
const group = await this.groupRepository.findOne({ id }, { populate: ['icons'] });
if (!group) {
throw new NotFoundException(GroupMessage.NOT_FOUND);
}
group.deletedAt = new Date();
await this.em.persistAndFlush(group);
await this.em.removeAndFlush(group);
}
findAllPublic(): Promise<Group[]> {
return this.groupRepository.find({ deletedAt: null }, { populate: ['icons'] });
}
}
+1 -2
View File
@@ -70,8 +70,7 @@ export class IconService {
if (!icon) {
throw new NotFoundException(IconMessage.NOT_FOUND);
}
icon.deletedAt = new Date();
await this.em.persistAndFlush(icon);
await this.em.removeAndFlush(icon);
}
}