refactor: the whole role and permission flow
This commit is contained in:
@@ -2,49 +2,40 @@ import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import slugify from "slugify";
|
||||
import { In, Not, QueryRunner } from "typeorm";
|
||||
|
||||
import { CommonMessage, UserMessage } from "../../../common/enums/message.enum";
|
||||
// import { CreateFinancialDto } from "../DTO/create-legal-user.dto";
|
||||
import { AdminMessage, AdsMessage, CommonMessage, UserMessage } from "../../../common/enums/message.enum";
|
||||
import { CompleteRegistrationDto } from "../../auth/DTO/complete-register.dto";
|
||||
import { UserSettingsService } from "../../settings/providers/user-settings.service";
|
||||
import { PaginationUtils } from "../../utils/providers/pagination.utils";
|
||||
import { PasswordService } from "../../utils/providers/password.service";
|
||||
import { WalletsService } from "../../wallets/providers/wallets.service";
|
||||
import { CheckValidityDTO } from "../DTO/check-validity.dto";
|
||||
// import { CreateFinancialDto } from "../DTO/create-legal-user.dto";
|
||||
import { SearchAdminsDto } from "../DTO/search-admins.dto";
|
||||
import { CreateAdminDto } from "../DTO/create-admin.dto";
|
||||
import { CreateRoleDto } from "../DTO/create-role.dto";
|
||||
import { SearchAdminQueryDto } from "../DTO/search-admins-query.dto";
|
||||
import { SearchCustomersDto } from "../DTO/search-customers.dto";
|
||||
import { SearchRolesQueryDto } from "../DTO/search-roles.dto";
|
||||
import { UpdateProfileDto } from "../DTO/update-profile.dto";
|
||||
import { CreateUserGroupDto } from "../DTO/user-group.dto";
|
||||
import { Role } from "../entities/role.entity";
|
||||
import { User } from "../entities/user.entity";
|
||||
import { RoleEnum } from "../enums/role.enum";
|
||||
import { ValidityType } from "../enums/validity-type.enum";
|
||||
// import { LegalUserRepository } from "../repositories/legal-user.repository";
|
||||
// import { RealUserRepository } from "../repositories/real-user.repository";
|
||||
import { PermissionsRepository } from "../repositories/permissions.repository";
|
||||
import { RoleRepository } from "../repositories/roles.repository";
|
||||
import { UserGroupRepository } from "../repositories/user-group.repository";
|
||||
import { UserRepository } from "../repositories/users.repository";
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
private readonly userSelect = {
|
||||
id: true,
|
||||
phone: true,
|
||||
email: true,
|
||||
userName: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
nationalCode: true,
|
||||
birthDate: true,
|
||||
role: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
};
|
||||
constructor(
|
||||
private readonly userRepository: UserRepository,
|
||||
private readonly userGroupRepository: UserGroupRepository,
|
||||
private readonly userSettingsService: UserSettingsService,
|
||||
private readonly walletsService: WalletsService,
|
||||
// private readonly realUserRepository: RealUserRepository,
|
||||
// private readonly legalUserRepository: LegalUserRepository,
|
||||
private readonly rolesRepository: RoleRepository,
|
||||
private readonly permissionsRepository: PermissionsRepository,
|
||||
private readonly passwordService: PasswordService,
|
||||
) {}
|
||||
|
||||
/************************************************************ */
|
||||
@@ -65,7 +56,7 @@ export class UsersService {
|
||||
/************************************************************ */
|
||||
|
||||
async getMe(userId: string) {
|
||||
const user = await this.userRepository.findOne({ where: { id: userId }, select: this.userSelect });
|
||||
const user = await this.userRepository.findOne({ where: { id: userId }, relations: { roles: true } });
|
||||
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
return { user };
|
||||
}
|
||||
@@ -74,6 +65,7 @@ export class UsersService {
|
||||
|
||||
async updateProfile(userId: string, updateProfileDto: UpdateProfileDto) {
|
||||
if (updateProfileDto.userName) {
|
||||
//
|
||||
updateProfileDto.userName = slugify(updateProfileDto.userName, { lower: true, trim: true });
|
||||
const existUserName = await this.userRepository.findOneBy({ userName: updateProfileDto.userName, id: Not(userId) });
|
||||
if (existUserName) throw new BadRequestException(UserMessage.USERNAME_EXIST);
|
||||
@@ -81,12 +73,8 @@ export class UsersService {
|
||||
const user = await this.userRepository.findOneBy({ id: userId });
|
||||
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
|
||||
// const { userName } = updateProfileDto;
|
||||
// if (userName) user.userName = userName;
|
||||
// if (firstName) user.firstName = firstName;
|
||||
// if (lastName) user.lastName = lastName;
|
||||
|
||||
await this.userRepository.save({ ...user, ...updateProfileDto });
|
||||
//
|
||||
return {
|
||||
message: CommonMessage.UPDATE_SUCCESS,
|
||||
};
|
||||
@@ -110,6 +98,9 @@ export class UsersService {
|
||||
const role = await queryRunner.manager.findOneBy(Role, { name: RoleEnum.USER });
|
||||
if (!role) throw new BadRequestException(UserMessage.ROLE_NOT_FOUND);
|
||||
|
||||
const existUser = await queryRunner.manager.findOneBy(User, { nationalCode: registerDto.nationalCode });
|
||||
if (existUser) throw new BadRequestException(UserMessage.NATIONAL_CODE_EXIST);
|
||||
|
||||
const user = queryRunner.manager.create(User, {
|
||||
...registerDto,
|
||||
password: hashedPassword,
|
||||
@@ -122,12 +113,47 @@ export class UsersService {
|
||||
await this.walletsService.createUserWallet(user.id, queryRunner);
|
||||
|
||||
return user;
|
||||
// const role = await this.roleRepository.findOneBy({ name: RoleEnum.USER });
|
||||
// if (!role) throw new BadRequestException(UserMessage.ROLE_NOT_FOUND);
|
||||
}
|
||||
|
||||
// const user = this.userRepository.create({ ...registerDto, password: hashedPassword, role });
|
||||
// await this.userSettingsService.createUserSettings(user.id);
|
||||
// return await this.userRepository.save(user);
|
||||
/************************************************************ */
|
||||
|
||||
async createAdmin(createDto: CreateAdminDto) {
|
||||
const existEmail = await this.userRepository.findOneBy({ email: createDto.email });
|
||||
if (existEmail) throw new BadRequestException(UserMessage.EMAIL_EXIST);
|
||||
|
||||
const role = await this.rolesRepository.findOne({ where: { id: createDto.roleId }, relations: { permissions: true } });
|
||||
if (!role) throw new BadRequestException(AdsMessage.ROLE_NOT_FOUND);
|
||||
|
||||
await this.rolesRepository.save(role);
|
||||
|
||||
if (createDto.password !== createDto.repeatPassword) throw new BadRequestException(AdminMessage.PASSWORD_NOT_MATCH);
|
||||
|
||||
const hashedPassword = await this.passwordService.hashPassword(createDto.password);
|
||||
|
||||
const userName = slugify(`${createDto.firstName} ${Date.now().toString().slice(-5)}`, { lower: true, trim: true });
|
||||
|
||||
const adminUser = this.userRepository.create({ ...createDto, roles: [role], password: hashedPassword, userName });
|
||||
await this.userRepository.save(adminUser);
|
||||
return {
|
||||
message: AdminMessage.ADMIN_CREATED,
|
||||
adminUser,
|
||||
};
|
||||
}
|
||||
/************************************************************ */
|
||||
|
||||
async createRole(createDto: CreateRoleDto) {
|
||||
const existRole = await this.rolesRepository.findOne({ where: { name: createDto.name } });
|
||||
if (existRole) throw new BadRequestException(AdminMessage.ROLE_EXIST);
|
||||
|
||||
const permissions = await this.permissionsRepository.findBy({ id: In(createDto.permissions) });
|
||||
if (permissions.length !== createDto.permissions.length) throw new BadRequestException(AdminMessage.PERMISSIONS_NOT_FOUND);
|
||||
|
||||
const role = this.rolesRepository.create({ ...createDto, permissions, isAdmin: true });
|
||||
await this.rolesRepository.save(role);
|
||||
return {
|
||||
message: AdminMessage.ROLE_CREATED,
|
||||
role,
|
||||
};
|
||||
}
|
||||
|
||||
/************************************************************ */
|
||||
@@ -209,30 +235,6 @@ export class UsersService {
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
async findAllAdmins(queryDto: SearchAdminsDto) {
|
||||
const { limit, skip } = PaginationUtils(queryDto);
|
||||
|
||||
const queryBuilder = this.userRepository
|
||||
.createQueryBuilder("user")
|
||||
.leftJoin("user.role", "role")
|
||||
.where("role.name = :roleName", { roleName: RoleEnum.ADMIN })
|
||||
.leftJoin("user.groups", "groups")
|
||||
.addSelect(["groups.id", "groups.name"]);
|
||||
|
||||
if (queryDto.q) {
|
||||
queryBuilder
|
||||
.orWhere("user.firstName ILIKE :search", { search: `%${queryDto.q}%` })
|
||||
.orWhere("user.lastName ILIKE :search", { search: `%${queryDto.q}%` })
|
||||
.orWhere("user.userName ILIKE :search", { search: `%${queryDto.q}%` });
|
||||
}
|
||||
|
||||
const [admins, count] = await queryBuilder.skip(skip).take(limit).getManyAndCount();
|
||||
|
||||
return { admins, count };
|
||||
}
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
async findAllCustomers(queryDto: SearchCustomersDto) {
|
||||
const { limit, skip } = PaginationUtils(queryDto);
|
||||
|
||||
@@ -273,73 +275,77 @@ export class UsersService {
|
||||
|
||||
return { customer };
|
||||
}
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
// async createRealUserData(createDto: CreateFinancialDto, user: User) {
|
||||
// const userExist = await this.userRepository.findOneBy({
|
||||
// id: user.role.name === RoleEnum.USER ? user.id : createDto.userId,
|
||||
// });
|
||||
async getAdmins(queryDto: SearchAdminQueryDto) {
|
||||
const { limit, skip } = PaginationUtils(queryDto);
|
||||
const queryBuilder = this.userRepository.createQueryBuilder("user");
|
||||
|
||||
// if (!userExist) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
queryBuilder
|
||||
.leftJoinAndSelect("user.roles", "role")
|
||||
// .addSelect(["role.id", "role.name"])
|
||||
.where("role.isAdmin = :isAdmin", { isAdmin: true })
|
||||
.leftJoinAndSelect("user.groups", "groups")
|
||||
.leftJoinAndSelect("role.permissions", "permissions");
|
||||
// .where("permissions.name IN (:...adminPermissions)", {
|
||||
// adminPermissions: [PermissionEnum.ADMINS],
|
||||
// });
|
||||
// .addSelect(["permissions.id", "permissions.name"]);
|
||||
|
||||
// const existingFinancial = await this.userFinancialRepository.findOne({
|
||||
// where: { user: { id: userExist.id }, type: createDto.type },
|
||||
// });
|
||||
// console.log(existingFinancial);
|
||||
if (queryDto.q) {
|
||||
queryBuilder.andWhere("user.firstName ILIKE :q OR user.lastName ILIKE :q OR user.userName ILIKE :q", {
|
||||
q: `%${queryDto.q}%`,
|
||||
});
|
||||
}
|
||||
|
||||
// if (existingFinancial) throw new BadRequestException(FinancialMessage.FINANCIAL_INFO_ALREADY_EXISTS);
|
||||
if (queryDto.permission) {
|
||||
queryBuilder.andWhere("permissions.name = :permName", { permName: queryDto.permission });
|
||||
}
|
||||
|
||||
// const userFinancial = this.userFinancialRepository.create({
|
||||
// ...createDto,
|
||||
// user: userExist,
|
||||
// });
|
||||
queryBuilder.take(limit).skip(skip).orderBy("user.createdAt", "DESC");
|
||||
|
||||
// await this.userFinancialRepository.save(userFinancial);
|
||||
const [users, count] = await queryBuilder.getManyAndCount();
|
||||
|
||||
// return {
|
||||
// message: CommonMessage.CREATED,
|
||||
// userFinancial,
|
||||
// };
|
||||
// }
|
||||
|
||||
// /************************************************************ */
|
||||
|
||||
// async updateUserFinancial(updateDto: CreateFinancialDto, user: User, userFinancialId: string) {
|
||||
// const userExist = await this.userRepository.findOneBy({
|
||||
// id: user.role.name === RoleEnum.USER ? user.id : updateDto.userId,
|
||||
// });
|
||||
|
||||
// if (!userExist) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
|
||||
// const existingFinancial = await this.userFinancialRepository.findOne({
|
||||
// where: { id: userFinancialId, user: { id: userExist.id }, type: updateDto.type },
|
||||
// });
|
||||
|
||||
// if (!existingFinancial) throw new BadRequestException(FinancialMessage.FINANCIAL_INFO_NOT_FOUND);
|
||||
|
||||
// await this.userFinancialRepository.save({
|
||||
// ...existingFinancial,
|
||||
// updateDto,
|
||||
// });
|
||||
|
||||
// return {
|
||||
// message: CommonMessage.UPDATE_SUCCESS,
|
||||
// userFinancial: existingFinancial,
|
||||
// };
|
||||
// }
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
async getUserFinancial(userId: string) {
|
||||
const user = await this.userRepository.findOne({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
relations: ["userFinancials"],
|
||||
});
|
||||
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
|
||||
|
||||
return { user };
|
||||
return {
|
||||
users,
|
||||
count,
|
||||
paginate: true,
|
||||
};
|
||||
}
|
||||
|
||||
/************************************************************ */
|
||||
|
||||
async getPermissions() {
|
||||
const permissions = await this.permissionsRepository.find({ select: { id: true, name: true } });
|
||||
return {
|
||||
permissions,
|
||||
};
|
||||
}
|
||||
/************************************************************ */
|
||||
|
||||
async getRoles(queryDto: SearchRolesQueryDto) {
|
||||
const { limit, skip } = PaginationUtils(queryDto);
|
||||
const queryBuilder = this.rolesRepository.createQueryBuilder("role");
|
||||
|
||||
queryBuilder
|
||||
.where("role.isAdmin = :isAdmin", { isAdmin: true })
|
||||
// .leftJoinAndSelect("role.permissions", "permissions")
|
||||
.loadRelationCountAndMap("role.userCount", "role.users");
|
||||
|
||||
if (queryDto.q) {
|
||||
queryBuilder.andWhere("role.name ILIKE :q", { q: `%${queryDto.q}%` });
|
||||
}
|
||||
|
||||
queryBuilder.take(limit).skip(skip).orderBy("role.createdAt", "DESC");
|
||||
|
||||
const [roles, count] = await queryBuilder.getManyAndCount();
|
||||
|
||||
return {
|
||||
roles,
|
||||
count,
|
||||
paginate: true,
|
||||
};
|
||||
}
|
||||
|
||||
/************************************************************ */
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user