feat: Add SUPER_ADMIN role with dedicated admin user management and updated access controls for existing admin features.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Injectable, BadRequestException, NotFoundException, ForbiddenException } from '@nestjs/common';
|
||||
import { UserStatus, UserRole, Prisma, VerificationStatus } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import * as argon2 from 'argon2';
|
||||
|
||||
type UserWithProfiles = Prisma.UserGetPayload<{
|
||||
include: { userProfile: true; agentProfile: { include: { agentType: true } } };
|
||||
@@ -519,4 +520,68 @@ export class UsersService {
|
||||
|
||||
return { message: 'Account deleted successfully' };
|
||||
}
|
||||
|
||||
// =============================================
|
||||
// ADMIN MANAGEMENT (SUPER_ADMIN only)
|
||||
// =============================================
|
||||
|
||||
async getAdminUsers() {
|
||||
return this.prisma.user.findMany({
|
||||
where: { role: { in: ['ADMIN', 'SUPER_ADMIN'] } },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
lastLoginAt: true,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async createAdminUser(email: string, password: string) {
|
||||
const existing = await this.prisma.user.findUnique({ where: { email } });
|
||||
if (existing) {
|
||||
throw new BadRequestException('A user with this email already exists');
|
||||
}
|
||||
|
||||
const hashedPassword = await argon2.hash(password);
|
||||
return this.prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
password: hashedPassword,
|
||||
role: 'ADMIN',
|
||||
status: 'ACTIVE',
|
||||
emailVerified: true,
|
||||
emailVerifiedAt: new Date(),
|
||||
authProvider: 'LOCAL',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async deleteAdminUser(id: string, requesterId: string) {
|
||||
if (id === requesterId) {
|
||||
throw new BadRequestException('You cannot delete your own account');
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id } });
|
||||
if (!user) throw new NotFoundException('User not found');
|
||||
if (user.role === 'SUPER_ADMIN') {
|
||||
throw new ForbiddenException('Cannot delete a super admin');
|
||||
}
|
||||
if (user.role !== 'ADMIN') {
|
||||
throw new BadRequestException('This user is not an admin');
|
||||
}
|
||||
|
||||
await this.prisma.user.delete({ where: { id } });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user