From 446c084156bf91b091220d7b12ce1a373905037d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20L=C3=A1szl=C3=B3?= <rlacko99@gmail.com> Date: Tue, 20 Oct 2020 23:59:13 +0200 Subject: [PATCH] specify redirect uri after auth in env --- .env.example | 3 +- src/middlewares/auth/complete.ts | 60 ++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 src/middlewares/auth/complete.ts diff --git a/.env.example b/.env.example index 41cb9efb..71bcc64a 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,4 @@ AUTH_SECRET_KEY= AUTH_ID= -SESSION_SECRET= \ No newline at end of file +SESSION_SECRET= +REDIRECT_URI={redirect after auth, not required, default = /} \ No newline at end of file diff --git a/src/middlewares/auth/complete.ts b/src/middlewares/auth/complete.ts new file mode 100644 index 00000000..ac2036d5 --- /dev/null +++ b/src/middlewares/auth/complete.ts @@ -0,0 +1,60 @@ +import Profile, { Role } from "../../models/ProfileSchema"; +import { Request, Response } from "express"; +import { oauth2, scope } from "../../utils/auth"; + +import { authschResponse } from "../../utils/types/authschResponse"; +import axios from "axios"; + +const complete = () => async (req: Request, res: Response) => { + const tokenConfig = { + code: req.query.code, + scope: scope, + redirect_uri: "", + }; + + try { + const token = await oauth2().authorizationCode.getToken(tokenConfig); + await axios + .get<authschResponse>( + `https://auth.sch.bme.hu/api/profile/?access_token=${token.access_token}` + ) + .then((response) => { + Profile.findOne( + { external_id: response.data.internal_id }, + (error, profile) => { + if (error) { + console.warn(error); + return res.status(400); + } else { + if (!profile) { + const newProfile = new Profile(); + newProfile.external_id = response.data.internal_id; + newProfile.email = response.data.mail; + newProfile.name = `${response.data.sn} ${response.data.givenName}`; + newProfile.save((err) => { + if (err) { + console.log(err); + return res.status(400); + } + }); + } + } + } + ); + req.session!.user = { + id: String(response.data.internal_id), + email: String(response.data.mail), + name: `${response.data.sn} ${response.data.givenName}`, + token, + }; + }) + .catch(function (error) { + console.log(error); + }); + return res.redirect(process.env.REDIRECT_URI || "/"); + } catch (error) { + console.log("Access Token Error", error.message); + } +}; + +export default complete; -- GitLab