src/application-user/application-user.service.ts
Methods |
|
constructor(appUserRepository: Repository<ApplicationUser>, applicationClientRepository: Repository<ApplicationClient>, applicationProfileRepository: Repository
|
||||||||||||||||||
|
Parameters :
|
| Async addUser | |||||||||
addUser(applicationClientId: number, body: ApplicationUserBodyDto)
|
|||||||||
|
Parameters :
Returns :
unknown
|
| Async createPasswordForUserInKeycloak | ||||||
createPasswordForUserInKeycloak(data: UserSetPasswordBodyDto)
|
||||||
|
Parameters :
Returns :
any
|
| Async delete |
delete(applicationClientId: number, id: number)
|
|
Returns :
unknown
|
| Async disable |
disable(applicationClientId: number, id: number)
|
|
Returns :
Promise<ApplicationUser>
|
| Async enable |
enable(applicationClientId: number, id: number)
|
|
Returns :
Promise<ApplicationUser>
|
| Async getUsersByApplicationId | ||||||
getUsersByApplicationId(applicationClientId: number)
|
||||||
|
Parameters :
Returns :
unknown
|
| Private Async leaveGroupOrDelete | |||
leaveGroupOrDelete(undefined)
|
|||
|
Parameters :
Returns :
any
|
| Async userSyncKeycloak | |||||||||
userSyncKeycloak(body: ApplicationUserBodyDto, config?: Config)
|
|||||||||
|
Parameters :
Returns :
any
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { configENV } from 'config-env';
import { ApplicationUser } from 'src/entities/application-user';
import { ApplicationProfile } from 'src/entities/application-profile';
import { User } from 'src/entities/user';
import { ApplicationUserBodyDto } from './dto/application-user.dto';
import { UserSetPasswordBodyDto } from './dto/user-set-password.dto';
import { GeneralException, formatName } from 'src/util';
import { ApplicationClient } from 'src/entities/applicationClient';
import { KafkaApiService } from 'src/provider/kafka-api/kafka-api.service';
import { type Config } from 'src/types/application-user';
@Injectable()
export class ApplicationUserService {
constructor(
@InjectRepository(ApplicationUser)
private appUserRepository: Repository<ApplicationUser>,
@InjectRepository(ApplicationClient)
private applicationClientRepository: Repository<ApplicationClient>,
@InjectRepository(ApplicationProfile)
private applicationProfileRepository: Repository<ApplicationProfile>,
@InjectRepository(User)
private userRepository: Repository<User>,
private readonly kafkaApiService: KafkaApiService,
) {}
async addUser(applicationClientId: number, body: ApplicationUserBodyDto) {
const application = await this.applicationClientRepository.countBy({
id: applicationClientId,
});
if (!application) {
throw new NotFoundException({
messageKey: 'application_client_not_found',
});
}
const { applicationProfileId, userId } = body;
const applicationUserExists = await this.appUserRepository.countBy({
applicationClientId,
userId,
});
if (applicationUserExists) {
throw new GeneralException('application_user_already_exists');
}
const saveResult = await this.appUserRepository.insert({
applicationClientId,
userId,
applicationProfileId,
});
return saveResult.raw[0].id;
}
private async leaveGroupOrDelete({ user, client, appName, profile }) {
const applicationProfile = await this.appUserRepository.find({
select: ['applicationClientId'],
where: { userId: user.id },
});
const idsApp = applicationProfile.map((app) => app.applicationClientId);
const totalApps = await this.applicationClientRepository
.createQueryBuilder()
.whereInIds(idsApp)
.andWhere({ clientId: client.id })
.getCount();
if (totalApps > 1) {
const data = {
realm: client.name,
appName: formatName(appName.name),
profile: formatName(profile.name),
email: user.email,
};
const { keycloak_topic_unlink_user } = configENV;
await this.kafkaApiService.sendMessage(data, keycloak_topic_unlink_user);
return;
}
const data = {
realm: client.name,
email: user.email,
};
const { keycloak_topic_delete_user } = configENV;
await this.kafkaApiService.sendMessage(data, keycloak_topic_delete_user);
}
async userSyncKeycloak(body: ApplicationUserBodyDto, config?: Config) {
const { userId, applicationProfileId, applicationId, clientId, password } = body;
const application = await this.applicationClientRepository
.createQueryBuilder('appClient')
.where({ applicationId, clientId })
.innerJoinAndSelect('appClient.client', 'client')
.innerJoinAndSelect('appClient.application', 'application')
.innerJoinAndSelect('application.translations', 'appTranslation')
.orderBy('appClient.id', 'ASC')
.getOne();
const { client } = application;
const appName = application.application.translations.find(
(translation) => translation.locale === 'pt-BR',
);
const profile = await this.applicationProfileRepository.findOneBy({
id: applicationProfileId,
});
const user = await this.userRepository.findOneBy({ id: userId });
if (config?.leaveGroup) {
await this.leaveGroupOrDelete({ user, client, appName, profile });
return;
}
const data: any = {
realm: client.name,
appName: formatName(appName.name),
profileName: formatName(profile.name),
user: {
username: user.username,
email: user.email,
firstName: user.name.split(' ')[0],
lastName: user.name.split(' ')[1],
}
};
if (password) {
data.password = {
...password,
clientname: password.clientname
}
}
const { keycloak_topic } = configENV;
await this.kafkaApiService.sendMessage(data, keycloak_topic);
}
async createPasswordForUserInKeycloak(data: UserSetPasswordBodyDto) {
const { setPassKeycloak } = configENV;
const params = {
...data,
clientname: data.clientname,
};
await this.kafkaApiService.sendMessage(params, setPassKeycloak);
}
async getUsersByApplicationId(applicationClientId: number) {
return this.appUserRepository
.createQueryBuilder('appUser')
.select([
'appUser.id AS id',
'appUser.applicationClientId AS "applicationClientId"',
'appUser.applicationProfileId AS "applicationProfileId"',
'appUser.userId AS "userId"',
'appUser.enabled AS enabled',
'user.name AS name',
'user.username AS username',
'appProfile.name AS "profileName"',
'client.name AS clientName',
])
.where({
applicationClientId,
})
.innerJoin('appUser.user', 'user')
.innerJoin('appUser.applicationProfile', 'appProfile')
.innerJoin('appUser.applicationClient', 'appClient')
.innerJoin('appClient.client', 'client')
.orderBy('appUser.id', 'ASC')
.getRawMany();
}
async enable(
applicationClientId: number,
id: number,
): Promise<ApplicationUser> {
const applicationUser = await this.appUserRepository.findOneBy({
id,
applicationClientId,
});
if (!applicationUser) {
throw new NotFoundException({ messageKey: 'application_user_not_found' });
}
return this.appUserRepository.save({
...applicationUser,
enabled: true,
});
}
async disable(
applicationClientId: number,
id: number,
): Promise<ApplicationUser> {
const applicationUser = await this.appUserRepository.findOneBy({
id,
applicationClientId,
});
if (!applicationUser) {
throw new NotFoundException({ messageKey: 'application_user_not_found' });
}
return this.appUserRepository.save({
...applicationUser,
enabled: false,
});
}
async delete(applicationClientId: number, id: number) {
const applicationUser = await this.appUserRepository.countBy({
id,
applicationClientId,
});
if (!applicationUser) {
throw new NotFoundException({ messageKey: 'application_user_not_found' });
}
return this.appUserRepository.delete({ applicationClientId, id });
}
}