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 from "@Services/common/AuthService/AuthService"; import { JwtPayload } from "jsonwebtoken"; @Controller() @Service() export default class UserController extends ApiController { constructor(private authService: AuthService) { 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) { console.warn("/api/v1/idnot/user/:code used for test, should be removed"); try { const code = req.params["code"]; if (!code) throw new Error("code is required"); const token = await fetch("https://qual-connexion.idnot.fr/IdPOAuth2/token/idnot_idp_v1", { method: "POST" }); console.log(token); //const user = await this.authService.getUserFromIdNotTokens(code!); //success this.httpSuccess(response); } catch (error) { console.log(error); this.httpInternalError(response); return; } } @Post("/api/v1/idnot/user/login/:idnot") protected async login(req: Request, response: Response) { try { const id = req.params["idnot"]; if (!id) throw new Error("idnot is required"); const payload = await this.authService.getUserJwtPayload(id!); const accessToken = this.authService.generateAccessToken(payload); const refreshToken = this.authService.generateRefreshToken(payload); //success this.httpSuccess(response, { accessToken, refreshToken }); } catch (error) { console.log(error); this.httpInternalError(response); return; } } @Post("/api/v1/idnot/user/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) { this.httpUnauthorized(response); return; } const user = userPayload as JwtPayload; delete user.iat; delete user!.exp; accessToken = this.authService.generateAccessToken(user); }); //success this.httpSuccess(response, accessToken); } catch (error) { this.httpInternalError(response); return; } } }