import { Response, Request } from "express"; import { Controller, Post } from "@ControllerPattern/index"; import ApiController from "@Common/system/controller-pattern/ApiController"; import { Service } from "typedi"; import AuthService, { IUserJwtPayload } from "@Services/common/AuthService/AuthService"; import IdNotService from "@Services/common/IdNotService/IdNotService"; @Controller() @Service() export default class UserController extends ApiController { constructor(private authService: AuthService, private idNotService: IdNotService) { super(); } /** * @description Get user created from IdNot authentification * @todo Used for test, should be removed * @returns User */ @Post("/api/v1/idnot/user/:code") protected async getUserInfosFromIdnot(req: Request, response: Response) { try { const code = req.params["code"]; if (!code) throw new Error("code is required"); const idNotToken = await this.idNotService.getIdNotToken(code); if(!idNotToken) { this.httpValidationError(response, "IdNot token undefined"); return; } const user = await this.idNotService.getOrCreateUser(idNotToken); if(!user) { this.httpUnauthorized(response); return; } await this.idNotService.updateUser(user.uid); await this.idNotService.updateOffice(user.office_uid); const payload = await this.authService.getUserJwtPayload(user.idNot); const accessToken = this.authService.generateAccessToken(payload); const refreshToken = this.authService.generateRefreshToken(payload); this.httpSuccess(response, { accessToken, refreshToken }); } catch (error) { console.log(error); this.httpInternalError(response); return; } } @Post("/api/v1/idnot/user/auth/refresh-token") protected async refreshToken(req: Request, response: Response) { try { const authHeader = req.headers["authorization"]; const token = authHeader && authHeader.split(" ")[1]; if (!token) { this.httpBadRequest(response); return; } let accessToken; this.authService.verifyRefreshToken(token, (err, userPayload) => { if (err) { console.log(err); this.httpUnauthorized(response); return; } const user = userPayload as IUserJwtPayload; accessToken = this.authService.generateAccessToken(user); }); //success this.httpSuccess(response, { accessToken }); } catch (error) { this.httpInternalError(response); return; } } }