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"; 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); const user = await this.idNotService.getOrCreateUser(idNotToken); 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/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/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 JwtPayload; delete user.iat; delete user!.exp; accessToken = this.authService.generateAccessToken(user); }); //success this.httpSuccess(response, {accessToken}); } catch (error) { this.httpInternalError(response); return; } } }