Kaynağa Gözat

move the authenticate request from client to server

Starink 6 yıl önce
ebeveyn
işleme
998217051e

+ 7 - 21
middleware/auth.js

@@ -1,9 +1,8 @@
 import { mapMutations } from 'vuex'
 
-export default function ({route, store, req, res, redirect}) {
+export default function ({route, store, req, res, redirect, next}) {
   let isClient = process.client;
   let isServer = process.server;
-  let redirectURL = '/login';
   let token, path;
 
   token = store.state.token;
@@ -18,26 +17,13 @@ export default function ({route, store, req, res, redirect}) {
   }
 
   console.log("path:"+path);
-  store.commit('saveOriginPath', path);
+  let mainPath = path.split("?")[0];
 
-  if (!token && path !== "/" && path !=="/login" && path !== "/register") {
-    let return_uri = encodeURIComponent("http://localhost:8000/receiveIDToken");
-    console.log("encoded path");
-    let url = 'http://localhost:3000/api/interaction?'+
-      'client_id='+ 'seec-portal-1919810-114514' +
-      '&scope=openid' +
-      '&redirect_uri=' + return_uri +
-      '&response_type=code';
+  if (!token && mainPath !== "/" && mainPath !=="/login" && mainPath !== "/register" && mainPath !=="/error" && mainPath !== "/api/receiveIDToken") {
+    redirect('/api/authenticate?path=' + mainPath);
 
-    // req.headers.cookies.set(
-    //   'interaction',
-    //   'seec-114514-1919810',    //可替换为token
-    //   {
-    //     maxAge: 10 * 60 * 1000, // cookie有效时长
-    //     sameSite: none
-    //   }
-    // );
-
-    redirect(url);
+  }else{
+    console.log("next");
+    next();
   }
 }

+ 2 - 0
package.json

@@ -22,6 +22,8 @@
     "element-ui": "^2.4.11",
     "jsonwebtoken": "^8.5.1",
     "koa": "^2.6.2",
+    "koa-router": "^8.0.8",
+    "koa2-cors": "^2.0.6",
     "nuxt": "^2.0.0"
   },
   "devDependencies": {

+ 66 - 0
server/controller/auth.js

@@ -0,0 +1,66 @@
+const Response = require('../util/response');
+const jwt = require('jsonwebtoken');
+
+class AuthController{
+    static processIDToken(ctx){
+      const query = ctx.query;
+      const {id_token} = query;
+      if(!id_token){
+        ctx.body = Response.failed("非法请求!")
+      }else{
+        jwt.verify(id_token, 'SEEC-1919810-OIDC-114514', (err, authData) => {
+          if(err) {
+            ctx.redirect("/error");
+          }
+          else {
+            const { iss, sub, aud, auth_time, iat, exp} = authData;
+            if(!iss || !sub || !aud || !auth_time || !iat || !exp){
+              ctx.redirect("/error");
+            }
+            else if(iss !== "http://localhost" || aud!=='seec-portal' ){
+              ctx.redirect("/error");
+            }
+            else{
+              let claims = sub.split('%26');
+              let origin_path = ctx.cookies.get('origin_path');
+              let user = {
+                id: parseInt(claims[0]),
+                name: claims[1],
+                phone: claims[2]
+              };
+              console.log("user:", user);
+              let my_token = jwt.sign(
+                user,'seec',{ expiresIn: '1day' }
+              );
+              ctx.cookies.set('my_token', my_token);
+              // store.commit("saveUser", user);
+              // store.commit("saveToken", my_token);
+              ctx.redirect(origin_path);
+            }
+          }
+        });
+
+      }
+
+    }
+
+  static authenticate(ctx){
+    const query = ctx.query;
+    const {path} = query;
+
+    let return_uri = encodeURIComponent("http://localhost:8000/api/receiveIDToken");
+    console.log("encoded path");
+    let url = 'http://localhost:3000/api/interaction?'+
+      'client_id='+ 'seec-portal' +
+      '&scope=openid' +
+      '&redirect_uri=' + return_uri +
+      '&response_type=code';
+
+    ctx.cookies.set("origin_path", path);
+
+    ctx.redirect(url);
+  }
+
+}
+
+module.exports = AuthController;

+ 16 - 0
server/index.js

@@ -1,9 +1,24 @@
 const Koa = require('koa')
+const cors = require('koa2-cors');
 const consola = require('consola')
 const { Nuxt, Builder } = require('nuxt')
 
+const router = require('./routes/index');
+
 const app = new Koa()
 
+// routes
+app.use(router().routes(), router().allowedMethods());
+
+app.use(cors({
+  origin:  'http://localhost:3000',
+  // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
+  maxAge: 3600,
+  credentials: true,
+  allowMethods: ['GET', 'POST', 'OPTIONS'],
+  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
+}));
+
 // Import and Set Nuxt.js options
 const config = require('../nuxt.config.js')
 config.dev = app.env !== 'production'
@@ -24,6 +39,7 @@ async function start () {
     await builder.build()
   }
 
+
   app.use((ctx) => {
     ctx.status = 200
     ctx.respond = false // Bypass Koa's built-in response handling

+ 4 - 12
server/routes/index.js

@@ -1,20 +1,12 @@
-const Router = require('koa-router');
-const UserController = require('../controller/user');
-const CourseController = require('../controller/course');
-const OIDCController = require('../controller/oidc');
+const Router = require('koa-router')
 const AuthController = require('../controller/auth');
 const router = new Router({prefix: '/api'});
 
 module.exports = () => {
-    router.post('/user/login', UserController.login); // 登录
-    router.post('/user/register', UserController.register);  // 登录(回调)
-
-    router.get('/course/getMyCourses',  CourseController.getMyCourses);
-    router.get('/course/getHotCourses',  CourseController.getHotCourses);
-
-    router.get('/interaction', AuthController.checkClient);
+  router.get('/receiveIDToken', AuthController.processIDToken);
+  router.get('/authenticate', AuthController.authenticate)
 
     //用户信息
     //.post('/user/get', UserController.get); // 获取用户信息
-    return router;
+  return router;
 };

+ 13 - 0
server/util/request.js

@@ -0,0 +1,13 @@
+const request = require('request');
+const util = require('util');
+const getPromise = util.promisify(request.get);
+
+module.exports = async function (url, data) {
+    let result = await getPromise({url:url, headers: {
+            'Authorization': 'Basic cm9vdDpOSlU2N3NvZnR3YXJl'
+        }
+    });
+    // 可以加入 try catch 捕获异常  也可以加 .catch()
+    console.log("result" , result);
+    return result;
+};

+ 11 - 0
server/util/response.js

@@ -0,0 +1,11 @@
+class Response {
+    static success(data){
+        return {code: 0, data: data};
+    }
+
+    static failed(message){
+        return {code: -1, message: message};
+    }
+}
+
+module.exports = Response;

+ 44 - 0
server/util/time-processer.js

@@ -0,0 +1,44 @@
+module.exports = function getNowFormatDate() {
+    let date = new Date();
+
+    let year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
+    let month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
+    let day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
+
+    let hours = date.getHours();          //小时 ,返回 Date 对象的小时 (0 ~ 23)
+    let minutes = date.getMinutes();      //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
+    let seconds = date.getSeconds();      //秒 ,返回 Date 对象的秒数 (0 ~ 59)
+
+
+//修改月份格式
+    if (month >= 1 && month <= 9) {
+        month = "0" + month;
+    }
+
+//修改日期格式
+    if (day >= 0 && day <= 9) {
+        day = "0" + day;
+    }
+
+//修改小时格式
+    if (hours >= 0 && hours <= 9) {
+        hours = "0" + hours;
+    }
+
+//修改分钟格式
+    if (minutes >= 0 && minutes <= 9) {
+        minutes = "0" + minutes;
+    }
+
+//修改秒格式
+    if (seconds >= 0 && seconds <= 9) {
+        seconds = "0" + seconds;
+    }
+
+//获取当前系统时间  格式(yyyy-mm-dd hh:mm:ss)
+    let currentFormatDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
+
+    return currentFormatDate;
+}
+
+

+ 36 - 2
yarn.lock

@@ -4647,7 +4647,7 @@ http-errors@1.7.2:
     statuses ">= 1.5.0 < 2"
     toidentifier "1.0.0"
 
-http-errors@^1.6.3, http-errors@~1.7.2:
+http-errors@^1.6.3, http-errors@^1.7.3, http-errors@~1.7.2:
   version "1.7.3"
   resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.7.3.tgz#6c619e4f9c60308c38519498c14fbb10aacebb06"
   integrity sha512-ZTTX0MWrsQ2ZAhA1cejAwDLycFsd7I7nVtnkT3Ol0aqodaKW+0CTZDQ1uBv5whptCnc8e8HeRRJxRs0kmm/Qfw==
@@ -5173,6 +5173,11 @@ is-wsl@^1.1.0:
   resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-1.1.0.tgz#1f16e4aa22b04d1336b66188a66af3c600c3a66d"
   integrity sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=
 
+isarray@0.0.1:
+  version "0.0.1"
+  resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf"
+  integrity sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=
+
 isarray@1.0.0, isarray@^1.0.0, isarray@~1.0.0:
   version "1.0.0"
   resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
@@ -5828,6 +5833,23 @@ koa-convert@^1.2.0:
     co "^4.6.0"
     koa-compose "^3.0.0"
 
+koa-router@^8.0.8:
+  version "8.0.8"
+  resolved "https://registry.yarnpkg.com/koa-router/-/koa-router-8.0.8.tgz#f0b70f90dae275db8c71a41e1efb625581fb3b5a"
+  integrity sha512-2rNF2cgu/EWi/NV8GlBE5+H/QBoaof83X6Z0dULmalkbt7W610/lyP2EOLVqVrUUFfjsVWL/Ju5TVBcGJDY9XQ==
+  dependencies:
+    debug "^4.1.1"
+    http-errors "^1.7.3"
+    koa-compose "^4.1.0"
+    methods "^1.1.2"
+    path-to-regexp "1.x"
+    urijs "^1.19.2"
+
+koa2-cors@^2.0.6:
+  version "2.0.6"
+  resolved "https://registry.yarnpkg.com/koa2-cors/-/koa2-cors-2.0.6.tgz#9ad23df3a0b9bb84530b46f5944f3fb576086554"
+  integrity sha512-JRCcSM4lamM+8kvKGDKlesYk2ASrmSTczDtGUnIadqMgnHU4Ct5Gw7Bxt3w3m6d6dy3WN0PU4oMP43HbddDEWg==
+
 koa@^2.6.2:
   version "2.11.0"
   resolved "https://registry.yarnpkg.com/koa/-/koa-2.11.0.tgz#fe5a51c46f566d27632dd5dc8fd5d7dd44f935a4"
@@ -6238,7 +6260,7 @@ merge-stream@^2.0.0:
   resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60"
   integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==
 
-methods@~1.1.2:
+methods@^1.1.2, methods@~1.1.2:
   version "1.1.2"
   resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee"
   integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=
@@ -7089,6 +7111,13 @@ path-to-regexp@0.1.7:
   resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c"
   integrity sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=
 
+path-to-regexp@1.x:
+  version "1.8.0"
+  resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-1.8.0.tgz#887b3ba9d84393e87a0a0b9f4cb756198b53548a"
+  integrity sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==
+  dependencies:
+    isarray "0.0.1"
+
 path-type@^1.0.0:
   version "1.1.0"
   resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441"
@@ -9646,6 +9675,11 @@ uri-js@^4.2.2:
   dependencies:
     punycode "^2.1.0"
 
+urijs@^1.19.2:
+  version "1.19.2"
+  resolved "https://registry.yarnpkg.com/urijs/-/urijs-1.19.2.tgz#f9be09f00c4c5134b7cb3cf475c1dd394526265a"
+  integrity sha512-s/UIq9ap4JPZ7H1EB5ULo/aOUbWqfDi7FKzMC2Nz+0Si8GiT1rIEaprt8hy3Vy2Ex2aJPpOQv4P4DuOZ+K1c6w==
+
 urix@^0.1.0:
   version "0.1.0"
   resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72"