From 91c0879b001bb7f5cc326ae102e0a80e101d0f1e 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 19:26:42 +0200
Subject: [PATCH] save new User in DB and retrieve from it on login

---
 src/middlewares/auth/authenticated.ts       |  2 +-
 src/middlewares/auth/complete.ts            | 28 +++++++++++++++++++--
 src/middlewares/user/getOwnUser.ts          | 15 ++++++++---
 src/models/ProfileSchema.ts                 |  2 +-
 src/routes/user.ts                          |  2 +-
 src/utils/declarations/authschResponse.d.ts | 20 +++++++++++++++
 6 files changed, 60 insertions(+), 9 deletions(-)
 create mode 100644 src/utils/declarations/authschResponse.d.ts

diff --git a/src/middlewares/auth/authenticated.ts b/src/middlewares/auth/authenticated.ts
index 8e9d0301..503fa2a3 100644
--- a/src/middlewares/auth/authenticated.ts
+++ b/src/middlewares/auth/authenticated.ts
@@ -7,7 +7,7 @@ const authenticated = () => (
 ) => {
   if (req.session!.user) next();
   else {
-    res.status(403);
+    res.status(401);
     res.json({ message: "You have to login to see this page" });
   }
 };
diff --git a/src/middlewares/auth/complete.ts b/src/middlewares/auth/complete.ts
index 28c3f98f..e4864b53 100644
--- a/src/middlewares/auth/complete.ts
+++ b/src/middlewares/auth/complete.ts
@@ -1,6 +1,8 @@
+import Profile, { Role } from "../../models/ProfileSchema";
 import { Request, Response } from "express";
 import { oauth2, scope } from "../../utils/auth";
 
+import { authschResponse } from "../../utils/declarations/authschResponse";
 import axios from "axios";
 
 const complete = () => async (req: Request, res: Response) => {
@@ -13,10 +15,32 @@ const complete = () => async (req: Request, res: Response) => {
   try {
     const token = await oauth2().authorizationCode.getToken(tokenConfig);
     await axios
-      .get(
+      .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),
@@ -27,7 +51,7 @@ const complete = () => async (req: Request, res: Response) => {
       .catch(function (error) {
         console.log(error);
       });
-    res.redirect("/");
+    return res.redirect("/");
   } catch (error) {
     console.log("Access Token Error", error.message);
   }
diff --git a/src/middlewares/user/getOwnUser.ts b/src/middlewares/user/getOwnUser.ts
index d236dd46..dd25d51b 100644
--- a/src/middlewares/user/getOwnUser.ts
+++ b/src/middlewares/user/getOwnUser.ts
@@ -3,10 +3,17 @@ import { NextFunction, Request, Response } from "express";
 import Profile from "../../models/ProfileSchema";
 
 const getOwnUser = () => (req: Request, res: Response, next: NextFunction) => {
-  if (!req.session!.user) {
-    return res.json({ loggedIn: false });
-  }
-  res.json({ ...req.session!.user, loggedIn: true });
+  console.log(req.session!.user);
+  Profile.findOne({ external_id: req.session!.user!.id }, (error, profile) => {
+    if (error) {
+      console.warn(error);
+      res.status(400);
+    } else {
+      res.status(200);
+      res.data = { profile };
+    }
+    next();
+  });
 };
 
 export default getOwnUser;
diff --git a/src/models/ProfileSchema.ts b/src/models/ProfileSchema.ts
index efb8c59f..0d5ffd64 100644
--- a/src/models/ProfileSchema.ts
+++ b/src/models/ProfileSchema.ts
@@ -22,7 +22,7 @@ export interface IProfile extends Document {
 
 const ProfileSchema = new Schema({
   external_id: { type: String, required: true, unique: true, dropDups: true },
-  studentCardNumber: { type: String, required: true },
+  studentCardNumber: { type: String, required: false },
   roomNumber: { type: String },
   picture: { type: String },
   role: {
diff --git a/src/routes/user.ts b/src/routes/user.ts
index 4f7c00c6..eb3dbfa7 100644
--- a/src/routes/user.ts
+++ b/src/routes/user.ts
@@ -20,7 +20,7 @@ const usersRoute = (app: Application): void => {
 
   app.post("/api/v1/users", authenticated(), addUser(), responseUser());
 
-  app.get("/api/v1/users/me", getOwnUser(), responseUser());
+  app.get("/api/v1/users/me", authenticated(), getOwnUser(), responseUser());
 
   app.get("/api/v1/users/:id", getUser(), responseUser());
 
diff --git a/src/utils/declarations/authschResponse.d.ts b/src/utils/declarations/authschResponse.d.ts
new file mode 100644
index 00000000..6bf887ee
--- /dev/null
+++ b/src/utils/declarations/authschResponse.d.ts
@@ -0,0 +1,20 @@
+export interface authschResponse {
+  internal_id: string;
+  displayName: string;
+  /** surname */
+  sn: string;
+  givenName: string;
+  mail: string;
+  linkedAccounts: {
+    bme: string;
+    schacc: string;
+    vir: string;
+  };
+  eduPersonEntitlement: [
+    {
+      id: number;
+      name: string;
+      status: string;
+    }
+  ];
+}
-- 
GitLab