IdNot Connexion log + Role update fix

This commit is contained in:
Vins 2024-10-09 12:08:30 +02:00
commit 3a97d50a26
3 changed files with 128 additions and 49 deletions

View File

@ -32,19 +32,24 @@ export default class UserController extends ApiController {
protected async getUserInfosFromIdnot(req: Request, response: Response) { protected async getUserInfosFromIdnot(req: Request, response: Response) {
try { try {
const code = req.params["code"]; const code = req.params["code"];
console.log("code", code);
if (!code) throw new Error("code is required"); if (!code) throw new Error("code is required");
const idNotToken = await this.idNotService.getIdNotToken(code); const idNotToken = await this.idNotService.getIdNotToken(code);
console.log("idNotToken", idNotToken);
if (!idNotToken) { if (!idNotToken) {
console.error("IdNot token undefined");
this.httpValidationError(response, "IdNot token undefined"); this.httpValidationError(response, "IdNot token undefined");
return; return;
} }
const user = await this.idNotService.getOrCreateUser(idNotToken); const user = await this.idNotService.getOrCreateUser(idNotToken);
console.log("user", user);
if (!user) { if (!user) {
console.error("User not found");
this.httpUnauthorized(response, "User not found"); this.httpUnauthorized(response, "User not found");
return; return;
} }
@ -56,6 +61,7 @@ export default class UserController extends ApiController {
const prismaUser = await this.userService.getByUid(user.uid, { contact: true, role: true, office_membership: true }); const prismaUser = await this.userService.getByUid(user.uid, { contact: true, role: true, office_membership: true });
if (!prismaUser) { if (!prismaUser) {
console.error("Prisma user not found");
this.httpNotFoundRequest(response, "user not found"); this.httpNotFoundRequest(response, "user not found");
return; return;
} }
@ -65,11 +71,11 @@ export default class UserController extends ApiController {
if (!userHydrated.contact?.email || userHydrated.contact?.email === "") { if (!userHydrated.contact?.email || userHydrated.contact?.email === "") {
console.error("Email not found");
this.httpUnauthorized(response, "Email not found"); this.httpUnauthorized(response, "Email not found");
return; return;
} }
let isSubscribed = await this.subscriptionsService.isUserSubscribed(user.uid, userHydrated.office_membership?.uid!); let isSubscribed = await this.subscriptionsService.isUserSubscribed(user.uid, userHydrated.office_membership?.uid!);
//Check if user is whitelisted //Check if user is whitelisted
// const isWhitelisted = await this.whitelistService.getByEmail(userHydrated.contact!.email); // const isWhitelisted = await this.whitelistService.getByEmail(userHydrated.contact!.email);
@ -86,8 +92,13 @@ export default class UserController extends ApiController {
await this.idNotService.updateOffice(user.office_uid); await this.idNotService.updateOffice(user.office_uid);
const payload = await this.authService.getUserJwtPayload(user.idNot); const payload = await this.authService.getUserJwtPayload(user.idNot);
console.log("payload", payload);
if (!payload) return;
if (!payload) {
console.error("No payload");
return;
}
if (!isSubscribed && (userHydrated.role?.name === "admin" || userHydrated.role?.name === "super-admin")) { if (!isSubscribed && (userHydrated.role?.name === "admin" || userHydrated.role?.name === "super-admin")) {
@ -106,7 +117,8 @@ export default class UserController extends ApiController {
isSubscribed = true; isSubscribed = true;
} }
if (!isSubscribed) { if (!isSubscribed) {
console.error("User not subscribed");
this.httpUnauthorized(response, "User not subscribed"); this.httpUnauthorized(response, "User not subscribed");
return; return;
} }

View File

@ -24,7 +24,7 @@ export default class UsersService extends BaseService {
* @throws {Error} If user modification failed * @throws {Error} If user modification failed
*/ */
public async update(uid: string, userEntity: User): Promise<Users> { public async update(uid: string, userEntity: User): Promise<Users> {
return this.userRepository.updateOfficeRole(uid, userEntity); return this.userRepository.update(uid, userEntity);
} }
/** /**

View File

@ -122,15 +122,16 @@ export default class IdNotService extends BaseService {
grant_type: "authorization_code", grant_type: "authorization_code",
}); });
const token = await fetch(this.variables.IDNOT_BASE_URL + this.variables.IDNOT_CONNEXION_URL + "?" + query, { method: "POST" }); try {
const token = await fetch(this.variables.IDNOT_BASE_URL + this.variables.IDNOT_CONNEXION_URL + "?" + query, { method: "POST" });
if (token.status !== 200) console.error(await token.text()); if (token.status !== 200) console.error(await token.text());
const decodedToken = (await token.json()) as IIdNotToken;
const decodedToken = (await token.json()) as IIdNotToken; const decodedIdToken = jwt.decode(decodedToken.id_token) as IdNotJwtPayload;
return decodedIdToken;
const decodedIdToken = jwt.decode(decodedToken.id_token) as IdNotJwtPayload; } catch (error) {
console.error(error);
return decodedIdToken; return null;
}
} }
public async getRole(roleName: string): Promise<Role> { public async getRole(roleName: string): Promise<Role> {
@ -211,22 +212,37 @@ export default class IdNotService extends BaseService {
const searchParams = new URLSearchParams({ const searchParams = new URLSearchParams({
key: this.variables.IDNOT_API_KEY, key: this.variables.IDNOT_API_KEY,
}); });
let userData = (await (
await fetch( let userData: IRattachementData;
`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/rattachements/${user.idNot}_${user.office_membership!.idNot}?` + try {
searchParams, userData = (await (
{ await fetch(
method: "GET", `${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/rattachements/${user.idNot}_${user.office_membership!.idNot}?` +
}, searchParams,
) {
).json()) as IRattachementData; method: "GET",
},
)
).json()) as IRattachementData;
} catch (error) {
console.error("Error fetching user data", error);
return;
}
if (!userData.statutDuRattachement) { if (!userData.statutDuRattachement) {
const rattachements = (await ( let rattachements: any;
await fetch(`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/personnes/${user.idNot}/rattachements?` + searchParams, {
method: "GET", try {
}) rattachements = (await (
).json()) as any; await fetch(`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/personnes/${user.idNot}/rattachements?` + searchParams, {
method: "GET",
})
).json()) as any;
} catch (error) {
console.error("Error fetching rattachements", error);
return;
}
if (rattachements.totalResultCount === 0) { if (rattachements.totalResultCount === 0) {
await this.userService.updateCheckedAt(user.uid!); await this.userService.updateCheckedAt(user.uid!);
//await this.userService.delete(user.uid!); //await this.userService.delete(user.uid!);
@ -236,11 +252,19 @@ export default class IdNotService extends BaseService {
if (!rattachementsResults) return; if (!rattachementsResults) return;
rattachementsResults.forEach(async (rattachement) => { rattachementsResults.forEach(async (rattachement) => {
if (rattachement.statutDuRattachement) { if (rattachement.statutDuRattachement) {
const officeData = (await ( let officeData: IOfficeData;
await fetch(`${this.variables.IDNOT_API_BASE_URL + rattachement.entiteUrl}?` + searchParams, {
method: "GET", try {
}) officeData = (await (
).json()) as IOfficeData; await fetch(`${this.variables.IDNOT_API_BASE_URL + rattachement.entiteUrl}?` + searchParams, {
method: "GET",
})
).json()) as IOfficeData;
} catch (error) {
console.error("Error fetching office data", error);
return;
}
if (officeData.typeEntite.name === "office") { if (officeData.typeEntite.name === "office") {
userData = rattachement; userData = rattachement;
} }
@ -254,9 +278,19 @@ export default class IdNotService extends BaseService {
updates++; updates++;
let officeData = (await this.officeService.get({ where: { idNot: userData.entite.ou } }))[0]; let officeData = (await this.officeService.get({ where: { idNot: userData.entite.ou } }))[0];
if (!officeData) { if (!officeData) {
const officeLocationData = (await ( let officeLocationData: IOfficeLocation;
await fetch(`${this.variables.IDNOT_API_BASE_URL + userData.entite.locationsUrl}?` + searchParams, { method: "GET" })
).json()) as IOfficeLocation; try {
officeLocationData = (await (
await fetch(`${this.variables.IDNOT_API_BASE_URL + userData.entite.locationsUrl}?` + searchParams, {
method: "GET",
})
).json()) as IOfficeLocation;
} catch (error) {
console.error("Error fetching office location data", error);
return;
}
const office = { const office = {
idNot: userData.entite.ou, idNot: userData.entite.ou,
name: userData.entite.denominationSociale, name: userData.entite.denominationSociale,
@ -289,21 +323,34 @@ export default class IdNotService extends BaseService {
await this.userService.updateCheckedAt(user.uid!); await this.userService.updateCheckedAt(user.uid!);
} }
public async updateOffice(officeId: string) { public async updateOffice(officeId: string) {
const officeInfos = await this.officeService.getByUid(officeId); const officeInfos = await this.officeService.getByUid(officeId, { address: true });
const office = Office.hydrate<Office>(officeInfos!); const office = Office.hydrate<Office>(officeInfos!);
const searchParams = new URLSearchParams({ const searchParams = new URLSearchParams({
key: this.variables.IDNOT_API_KEY, key: this.variables.IDNOT_API_KEY,
}); });
const officeRawData = await fetch(`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/entites/${office.idNot}?` + searchParams, {
method: "GET", let officeRawData;
}); try {
officeRawData = await fetch(`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/entites/${office.idNot}?` + searchParams, {
method: "GET",
});
} catch (error) {
console.error("Error fetching office data", error);
return;
}
if (officeRawData.status === 404) { if (officeRawData.status === 404) {
console.error("Fetching office raw data failed with status 404");
await this.officeService.updateCheckedAt(office.uid!); await this.officeService.updateCheckedAt(office.uid!);
//await this.officeService.delete(office.uid!); //await this.officeService.delete(office.uid!);
return; return;
} }
const officeData = (await officeRawData.json()) as IOfficeData; const officeData = (await officeRawData.json()) as IOfficeData;
console.log("office", office);
console.log("officeData", officeData);
let updates = 0; let updates = 0;
if (office.name !== officeData.denominationSociale) { if (office.name !== officeData.denominationSociale) {
updates++; updates++;
@ -324,19 +371,38 @@ export default class IdNotService extends BaseService {
key: this.variables.IDNOT_API_KEY, key: this.variables.IDNOT_API_KEY,
}); });
const userData = (await ( let userData: IRattachementData;
await fetch(`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/rattachements/${decodedToken.profile_idn}?` + searchParams, {
method: "GET",
})
).json()) as IRattachementData;
if (!userData.statutDuRattachement || userData.entite.typeEntite.name !== "office") { try {
userData = (await (
await fetch(
`${this.variables.IDNOT_API_BASE_URL}/api/pp/v2/rattachements/${decodedToken.profile_idn}?` + searchParams,
{
method: "GET",
},
)
).json()) as IRattachementData;
console.log("userData", userData);
} catch (error) {
console.error(error);
return null; return null;
} }
const officeLocationData = (await ( if (!userData.statutDuRattachement || userData.entite.typeEntite.name !== "office") {
await fetch(`${this.variables.IDNOT_API_BASE_URL + userData.entite.locationsUrl}?` + searchParams, { method: "GET" }) console.info("User not attached to an office (May be a partner)");
).json()) as IOfficeLocation; return null;
}
let officeLocationData: IOfficeLocation;
try {
officeLocationData = (await (
await fetch(`${this.variables.IDNOT_API_BASE_URL + userData.entite.locationsUrl}?` + searchParams, { method: "GET" })
).json()) as IOfficeLocation;
} catch (error) {
console.error(error);
return null;
}
const office = await this.officeService.get({ where: { idNot: decodedToken.entity_idn } }); const office = await this.officeService.get({ where: { idNot: decodedToken.entity_idn } });
@ -377,6 +443,7 @@ export default class IdNotService extends BaseService {
}; };
if (!userToAdd.contact.email) { if (!userToAdd.contact.email) {
console.error("User pro email empty");
return null; return null;
} }