diff --git a/src/entity/User.ts b/src/entity/User.ts index fc03403..7a7e998 100644 --- a/src/entity/User.ts +++ b/src/entity/User.ts @@ -1,5 +1,9 @@ -import {Entity, Column, PrimaryColumn, OneToMany, JoinTable} from "typeorm"; +import {Entity, Column, PrimaryColumn, OneToMany, JoinTable, AfterLoad} from "typeorm"; +import Logger from "../services/Logger"; import { Group } from "./Group"; +import { Token } from "./Token"; + +var axios = require('axios'); @Entity() export class User { @@ -19,6 +23,46 @@ export class User { @JoinTable() groups!: Group[]; + @AfterLoad() + private getUserWithPortailData = async (retry: number = 0) => { + if (retry >= Token.__MAX_RETRIES_) { + Logger.error('Max retries exceeded while fetching the portail'); + return null; + } else { + if (!Token.isValid()) { + Token.refreshToken(); + } + + const responseAxios = await axios({ + method: 'GET', + url: `${process.env.AUTH_PORTAIL_URL}/api/v1/users/${this.id}`, + headers: { + 'Accept': 'application/json', + 'Accept-Charset': 'utf-8', + 'Authorization': 'Bearer ' + Token.getAccessToken() + } + }).catch((err: any) => { + return err.response; + }).then((response: any) => { + return response; + }); + + if (responseAxios.status === 200) { + this.deserializeFromPortailData(responseAxios.data); + return + } else if (responseAxios.status === 401) { + Logger.info('Unauthorized while fetching the portail: ' + responseAxios.data.message + + ' -> ' + responseAxios.data.exception); + Token.refreshToken(); + await this.getUserWithPortailData(retry++); + return; + } else { + Logger.error(responseAxios.data.message + ' -> ' + responseAxios.data.exception); + return; + } + } + } + /** * These properties come from the portail */ diff --git a/src/services/Authentication.ts b/src/services/Authentication.ts index 8657622..7b352cb 100644 --- a/src/services/Authentication.ts +++ b/src/services/Authentication.ts @@ -49,7 +49,7 @@ export const authenticationFilter = async function (req: Request, res: Response, }); if (responseAxios.status !== 200) { - return res.redirect(authURL); + return res.status(401).send('Unautorized: Access token or authorization code is missing'); } // Send the request to next server's middlware @@ -63,14 +63,14 @@ export const authenticationFilter = async function (req: Request, res: Response, if (authorizationCode === null || authorizationCode === undefined || authorizationCode === '') { // Handle redirection (the user is not connected with oauth2 yet) - return res.redirect(authURL); + return res.status(401).send('Unautorized: Acces otken or authorization code missing'); } else { // Obtaining access_token oauth2.getOAuthAccessToken( authorizationCode, { 'redirect_uri': redirectURL, - 'grant_type':'authorization_code' + 'grant_type':'authorization_code', }, async function (err:any, access_token:any, refresh_token:any, results:any) { if (err) { @@ -95,6 +95,7 @@ export const authenticationFilter = async function (req: Request, res: Response, }).then(function (response:any) { // Print user information Logger.debug(response.data); + res.locals.user = response.data; next(); }).catch(function (err:any) { console.error(err); diff --git a/src/services/CourseService.ts b/src/services/CourseService.ts index 0ecd648..1299b73 100644 --- a/src/services/CourseService.ts +++ b/src/services/CourseService.ts @@ -30,7 +30,7 @@ export class CourseService { /** * Get users from course's id * @param id - * @returns Course | undefined + * @returns User[] */ public findUsers = async (id: String) => { const users = await this.userRepository.findUsersByCourse(id); diff --git a/src/services/UserService.ts b/src/services/UserService.ts index 189c1d9..9082aec 100644 --- a/src/services/UserService.ts +++ b/src/services/UserService.ts @@ -77,18 +77,10 @@ export class UserService { */ public findUsersByTimeSlot = async (timeSlotId: number) => { // TODO: get the Token -> get user's information from the portail + Logger.debug("findUsersByTimeSlot called"); const timeSlot = await this.timeSlotRepository.findById(timeSlotId); if (timeSlot !== undefined) { - const users: Array = []; - for (const user of timeSlot.users) { - if (user !== null && user.id !== undefined) { - const finalUser = await this.getUserWithPortailData(user); - if (finalUser !== null) { - users.push(finalUser); - } - } - } - return users; + return timeSlot.users; } else { Logger.debug('TimeSlot ' + timeSlotId + ' not found'); return []; @@ -96,44 +88,6 @@ export class UserService { } - private getUserWithPortailData = async (user: User, retry: number = 0) => { - if (retry >= Token.__MAX_RETRIES_) { - Logger.error('Max retries exceeded while fetching the portail'); - return null; - } else { - if (!Token.isValid()) { - Token.refreshToken(); - } - - const responseAxios = await axios({ - method: 'GET', - url: `${process.env.AUTH_PORTAIL_URL}/api/v1/users/${user.id}`, - headers: { - 'Accept': 'application/json', - 'Accept-Charset': 'utf-8', - 'Authorization': 'Bearer ' + Token.getAccessToken() - } - }).catch((err: any) => { - return err.response; - }).then((response: any) => { - return response; - }); - - if (responseAxios.status === 200) { - user.deserializeFromPortailData(responseAxios.data); - return user; - } else if (responseAxios.status === 401) { - Logger.info('Unauthorized while fetching the portail: ' + responseAxios.data.message - + ' -> ' + responseAxios.data.exception); - Token.refreshToken(); - return this.getUserWithPortailData(user, retry++); - } else { - Logger.error(responseAxios.data.message + ' -> ' + responseAxios.data.exception); - return null; - } - } - } - /** * Create a new user entity * @param body Validated body of the request