Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion src/entity/User.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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
*/
Expand Down
7 changes: 4 additions & 3 deletions src/services/Authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/services/CourseService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
50 changes: 2 additions & 48 deletions src/services/UserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,63 +77,17 @@ 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<User> = [];
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 [];
}

}

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
Expand Down