Browse Source

外部评审权限功能

warrior 3 weeks ago
parent
commit
7fc830441e
2 changed files with 198 additions and 191 deletions
  1. 195 189
      server/api/textbook/routes.js
  2. 3 2
      server/server.js

+ 195 - 189
server/api/textbook/routes.js

@@ -1,107 +1,131 @@
 let Parse = global.Parse
-const router = require('express').Router();
 let bodyParser = require('body-parser')
 const pgp = require('pg-promise')();
 
-router.use(bodyParser.json({ limit: '10mb' }))
-router.use(bodyParser.urlencoded({ extended: false }))
-
-router.use("/test", async (req, res, next) => {
-    res.json({
-        code: 200,
-        data: "test"
-    })
-})
+// const router = require('express').Router();
+// router.use(bodyParser.json({ limit: '10mb' }))
+// router.use(bodyParser.urlencoded({ extended: false }))
 
+export function defineTbookReview(app){
 
-router.post("/login", async (req, res, next) => {
-    goWrong(res, "接口已停止维护");
-    return
-    let id = req.body.id;
-    if (!id) {
-        goWrong(res, "参数不完整,请检查");
-        return
-    }
-    // 检查用户信息
-    let query = new global.Parse.Query("_User");
-    query.equalTo("objectId", id);
-    let user = query.first({ useMasterKey: true });
-    if (user?.id) {
-        let token = await setMobileSessionToken(user)
-        res.json({
-            code: 200,
-            msg: '登录成功',
-            data: {
-                userId: user.id,
-                username: user.get("username"),
-                mobile: user.get("mobile"),
-                token: token?.get("sessionToken")
-            }
-        })
-        return
-    }
-    goWrong(res, "用户不存在,请先注册")
-})
-
-
-router.post("/register", async (req, res, next) => {
-    let company = req.body.company;
-    let mobile = req.body.mobile;
-    let code = req.body.code;
-    let password = req.body.password
-    if (!company || !mobile || !code) {
-        goWrong(res, "参数不完整,请检查");
-        return
-    }
-    // 检查用户信息
-    let user;
-    user = await getUserByMobile(mobile, company);
-    if (user) {
-        // goWrong(res, "用户已存在,请登录")
-        let token = await setMobileSessionToken(user)
-        res.json({
-            code: 200,
-            msg: '用户已存在,请登录',
-            data: {
-                userId: user.id,
-                username: user.get("username"),
-                mobile: user.get("mobile"),
-                token: token?.get("sessionToken")
-            }
-        })
-        return
-    }
-    try {
-        let _User = Parse.Object.extend("_User")
-        let User = new _User
-        User.set("username", company + mobile)
-        User.set("password", company + mobile)
-        User.set("company", {
-            __type: 'Pointer',
-            className: 'Company',
-            objectId: company
-        })
-        User.set("mobile", mobile)
-        User.set("status", 'normal')
-        let saveUser = await User.save({ useMasterKey: true })
-        let token = await setMobileSessionToken(saveUser)
+    app.get("/parse/api/review/test", async (req, res, next) => {
         res.json({
             code: 200,
-            msg: '注册成功',
-            data: {
-                userId: saveUser.id,
-                username: saveUser.get("username"),
-                mobile: saveUser.get("mobile"),
-                token: token?.get("sessionToken")
-            }
+            data: "test"
         })
+    })
 
-    } catch (error) {
-        console.log(error)
-        return
-    }
 
-})
+    app.post("/parse/api/review/token", async (req, res) => {
+        let refer = req.headers["referer"] || req.headers["referered"];
+        // 检查referer来源
+        if (refer && refer.includes('https://145.tbook.com.cn')) {
+        Parse.User.logIn('145review', 'review-textbook145').then((user) => {
+                console.log(user?.get('sessionToken'));
+                res.json({
+                    token: user?.get('sessionToken'),
+                })
+            }).catch(err=>{
+                goWrong(res, "invalid user");
+            })
+        }else{
+            res.json({
+                code: 404,
+            })
+        }
+    })
+}
+
+
+
+// router.post("/login", async (req, res, next) => {
+//     goWrong(res, "接口已停止维护");
+//     return
+//     let id = req.body.id;
+//     if (!id) {
+//         goWrong(res, "参数不完整,请检查");
+//         return
+//     }
+//     // 检查用户信息
+//     let query = new global.Parse.Query("_User");
+//     query.equalTo("objectId", id);
+//     let user = query.first({ useMasterKey: true });
+//     if (user?.id) {
+//         let token = await setMobileSessionToken(user)
+//         res.json({
+//             code: 200,
+//             msg: '登录成功',
+//             data: {
+//                 userId: user.id,
+//                 username: user.get("username"),
+//                 mobile: user.get("mobile"),
+//                 token: token?.get("sessionToken")
+//             }
+//         })
+//         return
+//     }
+//     goWrong(res, "用户不存在,请先注册")
+// })
+
+
+// router.post("/register", async (req, res, next) => {
+//     let company = req.body.company;
+//     let mobile = req.body.mobile;
+//     let code = req.body.code;
+//     let password = req.body.password
+//     if (!company || !mobile || !code) {
+//         goWrong(res, "参数不完整,请检查");
+//         return
+//     }
+//     // 检查用户信息
+//     let user;
+//     user = await getUserByMobile(mobile, company);
+//     if (user) {
+//         // goWrong(res, "用户已存在,请登录")
+//         let token = await setMobileSessionToken(user)
+//         res.json({
+//             code: 200,
+//             msg: '用户已存在,请登录',
+//             data: {
+//                 userId: user.id,
+//                 username: user.get("username"),
+//                 mobile: user.get("mobile"),
+//                 token: token?.get("sessionToken")
+//             }
+//         })
+//         return
+//     }
+//     try {
+//         let _User = Parse.Object.extend("_User")
+//         let User = new _User
+//         User.set("username", company + mobile)
+//         User.set("password", company + mobile)
+//         User.set("company", {
+//             __type: 'Pointer',
+//             className: 'Company',
+//             objectId: company
+//         })
+//         User.set("mobile", mobile)
+//         User.set("status", 'normal')
+//         let saveUser = await User.save({ useMasterKey: true })
+//         let token = await setMobileSessionToken(saveUser)
+//         res.json({
+//             code: 200,
+//             msg: '注册成功',
+//             data: {
+//                 userId: saveUser.id,
+//                 username: saveUser.get("username"),
+//                 mobile: saveUser.get("mobile"),
+//                 token: token?.get("sessionToken")
+//             }
+//         })
+
+//     } catch (error) {
+//         console.log(error)
+//         return
+//     }
+
+// })
 
 function goWrong(response, msg) {
     response.status(500)
@@ -118,101 +142,83 @@ function getUserByMobile(mobile, company) {
     query.equalTo("company", company);
     return query.first({ useMasterKey: true });
 }
-/* 创建_Session并返回 */
-import {pgClient} from "../../db/pg-instance";
-
-async function setMobileSessionToken(user, reset) {
-    try {
-        // let Session = global.Parse.Object.extend('_Session');
-        if (user) {
-            //获取最后一次的token,如果过期时间大于未来2小时直接返回,若不是重置
-            let nowTime = new Date().getTime() + (1000 * 60 * 120)
-            let query = new Parse.Query('_Session')
-            query.equalTo('user', user.id)
-            query.descending('expiresAt')
-            query.greaterThan('expiresAt', new Date(nowTime))
-            query.select('expiresAt', 'sessionToken')
-            let reqSessionToken = await query.first({ useMasterKey: true })
-            if (reqSessionToken?.id && reqSessionToken.get('sessionToken')) {
-                return reqSessionToken
-            }
-            let username = user?.username || user?.get('username')
-            let sessionToken = "r:" + username + (new Date().getTime() / 1000).toFixed();
-            // 创建新Session登录系统
-            let Session = Parse.Object.extend('_Session');
-            let session = new Session()
-            let r = await session.save(null, {
-                useMasterKey: true
-            })
-            const objectId = r.id;
-            let now = new Date();
-            let expiresAt = (now.getFullYear() + 1) + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 12:00:00'
-            console.log(expiresAt);
-            let sql = `INSERT INTO "_Session" ("objectId","user", "sessionToken", "expiresAt", "createdWith")
-            VALUES
-            ('${objectId}','${user.id}', '${sessionToken}','${expiresAt}','{"action": "login","authProvider": "appPassword"}')
-            ON CONFLICT("objectId") DO UPDATE
-            SET 
-            "user" = excluded."user",
-            "sessionToken" = excluded."sessionToken",
-            "expiresAt"=excluded."expiresAt",
-            "createdWith"=excluded."createdWith"
-            `
-            const data = await pgClient().any(sql);
-            console.log('_Session', data)
-            let doneObj = {
-                get(field = 'sessionToken') {
-                    if (field = 'sessionToken') return sessionToken
-                }
-            }
-            // let session = new Session();
-            // session.set("user", {
-            //     __type: 'Pointer',
-            //     className: '_User',
-            //     objectId: user.id
-            // });
-            // session.set("sessionToken", sessionToken);
-            // let now = new Date();
-            // now.setFullYear(now.getFullYear() + 1);
-            // let expiresAt = now;
-            // session.set("expiresAt", expiresAt);
-            // session.set("createdWith", {
-            //     "action": "login",
-            //     "authProvider": "appPassword"
-            // })
-            // session.set("restricted", false)
-            // let doneObj = await session.save(null, {
-            //     useMasterKey: true
-            // })
-            // if (!doneObj) {
-            //     return false
-            // }
-            return doneObj
-        }
-    } catch (err) {
-        console.log(err)
-        return false
-    }
-}
+// /* 创建_Session并返回 */
+// import {pgClient} from "../../db/pg-instance";
+
+// async function setMobileSessionToken(user, reset) {
+//     try {
+//         // let Session = global.Parse.Object.extend('_Session');
+//         if (user) {
+//             //获取最后一次的token,如果过期时间大于未来2小时直接返回,若不是重置
+//             let nowTime = new Date().getTime() + (1000 * 60 * 120)
+//             let query = new Parse.Query('_Session')
+//             query.equalTo('user', user.id)
+//             query.descending('expiresAt')
+//             query.greaterThan('expiresAt', new Date(nowTime))
+//             query.select('expiresAt', 'sessionToken')
+//             let reqSessionToken = await query.first({ useMasterKey: true })
+//             if (reqSessionToken?.id && reqSessionToken.get('sessionToken')) {
+//                 return reqSessionToken
+//             }
+//             let username = user?.username || user?.get('username')
+//             let sessionToken = "r:" + username + (new Date().getTime() / 1000).toFixed();
+//             // 创建新Session登录系统
+//             let Session = Parse.Object.extend('_Session');
+//             let session = new Session()
+//             let r = await session.save(null, {
+//                 useMasterKey: true
+//             })
+//             const objectId = r.id;
+//             let now = new Date();
+//             let expiresAt = (now.getFullYear() + 1) + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 12:00:00'
+//             console.log(expiresAt);
+//             let sql = `INSERT INTO "_Session" ("objectId","user", "sessionToken", "expiresAt", "createdWith")
+//             VALUES
+//             ('${objectId}','${user.id}', '${sessionToken}','${expiresAt}','{"action": "login","authProvider": "appPassword"}')
+//             ON CONFLICT("objectId") DO UPDATE
+//             SET 
+//             "user" = excluded."user",
+//             "sessionToken" = excluded."sessionToken",
+//             "expiresAt"=excluded."expiresAt",
+//             "createdWith"=excluded."createdWith"
+//             `
+//             const data = await pgClient().any(sql);
+//             console.log('_Session', data)
+//             let doneObj = {
+//                 get(field = 'sessionToken') {
+//                     if (field = 'sessionToken') return sessionToken
+//                 }
+//             }
+//             // let session = new Session();
+//             // session.set("user", {
+//             //     __type: 'Pointer',
+//             //     className: '_User',
+//             //     objectId: user.id
+//             // });
+//             // session.set("sessionToken", sessionToken);
+//             // let now = new Date();
+//             // now.setFullYear(now.getFullYear() + 1);
+//             // let expiresAt = now;
+//             // session.set("expiresAt", expiresAt);
+//             // session.set("createdWith", {
+//             //     "action": "login",
+//             //     "authProvider": "appPassword"
+//             // })
+//             // session.set("restricted", false)
+//             // let doneObj = await session.save(null, {
+//             //     useMasterKey: true
+//             // })
+//             // if (!doneObj) {
+//             //     return false
+//             // }
+//             return doneObj
+//         }
+//     } catch (err) {
+//         console.log(err)
+//         return false
+//     }
+// }
 
-router.post("/review/token", async (req, res) => {
-    let refer = req.headers["referer"] || req.headers["referered"];
-    // 检查referer来源
-    if (refer && refer.indexOf('https://145.tbook.com.cn') == 0) {
-       Parse.User.logIn('145review', 'review-textbook145').then((user) => {
-            console.log(user?.get('sessionToken'));
-            response.json({
-                token: user?.get('sessionToken'),
-            })
-        }).catch(err=>{
-            goWrong(res, "invalid user");
-        })
-    }else{
-        response.json({
-            code: 404,
-        })
-    }
-})
 
-module.exports = router;
-export const textbookRouter = router;
+// module.exports = router;
+// export const textbookRouter = router;

+ 3 - 2
server/server.js

@@ -43,7 +43,7 @@ global.config["LOCAL"] = argv.local || process.env["LOCAL"] || appConfig["LOCAL"
 global.config["PORT"] = argv.port || process.env["PORT"] || appConfig["PORT"] || global.config['PORT'] ||  61337
 
 
-import  {textbookRouter} from "./api/textbook/routes";
+import  {defineTbookReview} from "./api/textbook/routes";
 import { defineAliOssSTS } from "./cloud/aliyun"
 import { defineAliSMSSend } from "./cloud/aliyun/func-aliyun-sms"
 import { defineAuthingLogin, defineDepartmentTrigger, defineUserAfterDelete, defineUserBeforeSave } from "./cloud/authing"
@@ -161,7 +161,7 @@ async function initParseAndDatabase(){
 
     console.log("正在启动api接口")
     // 加载textbook专属路由 通过代理操控局域网设备
-    app.use("/api/textbook",textbookRouter)
+    // app.use("/parse/api/textbook",textbookRouter)
     app.get("/",(req,res)=>{
       res.json({
         code:200,
@@ -194,6 +194,7 @@ async function initParseAndDatabase(){
       defineDepartmentTrigger();
       defineTbookISBN();
       defineTbookExportReport(app);
+      defineTbookReview(app);
     });
  
     console.log("正在启动管理看板...")