routes.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. let Parse = global.Parse
  2. const router = require('express').Router();
  3. let bodyParser = require('body-parser')
  4. const pgp = require('pg-promise')();
  5. router.use(bodyParser.json({ limit: '10mb' }))
  6. router.use(bodyParser.urlencoded({ extended: false }))
  7. router.use("/test", async (req, res, next) => {
  8. res.json({
  9. code: 200,
  10. data: "test"
  11. })
  12. })
  13. router.post("/login", async (req, res, next) => {
  14. goWrong(res, "接口已停止维护");
  15. return
  16. let id = req.body.id;
  17. if (!id) {
  18. goWrong(res, "参数不完整,请检查");
  19. return
  20. }
  21. // 检查用户信息
  22. let query = new global.Parse.Query("_User");
  23. query.equalTo("objectId", id);
  24. let user = query.first({ useMasterKey: true });
  25. if (user?.id) {
  26. let token = await setMobileSessionToken(user)
  27. res.json({
  28. code: 200,
  29. msg: '登录成功',
  30. data: {
  31. userId: user.id,
  32. username: user.get("username"),
  33. mobile: user.get("mobile"),
  34. token: token?.get("sessionToken")
  35. }
  36. })
  37. return
  38. }
  39. goWrong(res, "用户不存在,请先注册")
  40. })
  41. router.post("/register", async (req, res, next) => {
  42. let company = req.body.company;
  43. let mobile = req.body.mobile;
  44. let code = req.body.code;
  45. let password = req.body.password
  46. if (!company || !mobile || !code) {
  47. goWrong(res, "参数不完整,请检查");
  48. return
  49. }
  50. // 检查用户信息
  51. let user;
  52. user = await getUserByMobile(mobile, company);
  53. if (user) {
  54. // goWrong(res, "用户已存在,请登录")
  55. let token = await setMobileSessionToken(user)
  56. res.json({
  57. code: 200,
  58. msg: '用户已存在,请登录',
  59. data: {
  60. userId: user.id,
  61. username: user.get("username"),
  62. mobile: user.get("mobile"),
  63. token: token?.get("sessionToken")
  64. }
  65. })
  66. return
  67. }
  68. try {
  69. let _User = Parse.Object.extend("_User")
  70. let User = new _User
  71. User.set("username", company + mobile)
  72. User.set("password", company + mobile)
  73. User.set("company", {
  74. __type: 'Pointer',
  75. className: 'Company',
  76. objectId: company
  77. })
  78. User.set("mobile", mobile)
  79. User.set("status", 'normal')
  80. let saveUser = await User.save({ useMasterKey: true })
  81. let token = await setMobileSessionToken(saveUser)
  82. res.json({
  83. code: 200,
  84. msg: '注册成功',
  85. data: {
  86. userId: saveUser.id,
  87. username: saveUser.get("username"),
  88. mobile: saveUser.get("mobile"),
  89. token: token?.get("sessionToken")
  90. }
  91. })
  92. } catch (error) {
  93. console.log(error)
  94. return
  95. }
  96. })
  97. function goWrong(response, msg) {
  98. response.status(500)
  99. response.json({
  100. code: 500,
  101. mess: msg
  102. })
  103. return
  104. }
  105. /* 检查用户是否存在 */
  106. function getUserByMobile(mobile, company) {
  107. let query = new global.Parse.Query("_User");
  108. query.equalTo("mobile", mobile);
  109. query.equalTo("company", company);
  110. return query.first({ useMasterKey: true });
  111. }
  112. /* 创建_Session并返回 */
  113. import {pgClient} from "../../db/pg-instance";
  114. async function setMobileSessionToken(user, reset) {
  115. try {
  116. // let Session = global.Parse.Object.extend('_Session');
  117. if (user) {
  118. //获取最后一次的token,如果过期时间大于未来2小时直接返回,若不是重置
  119. let nowTime = new Date().getTime() + (1000 * 60 * 120)
  120. let query = new Parse.Query('_Session')
  121. query.equalTo('user', user.id)
  122. query.descending('expiresAt')
  123. query.greaterThan('expiresAt', new Date(nowTime))
  124. query.select('expiresAt', 'sessionToken')
  125. let reqSessionToken = await query.first({ useMasterKey: true })
  126. if (reqSessionToken?.id && reqSessionToken.get('sessionToken')) {
  127. return reqSessionToken
  128. }
  129. let username = user?.username || user?.get('username')
  130. let sessionToken = "r:" + username + (new Date().getTime() / 1000).toFixed();
  131. // 创建新Session登录系统
  132. let Session = Parse.Object.extend('_Session');
  133. let session = new Session()
  134. let r = await session.save(null, {
  135. useMasterKey: true
  136. })
  137. const objectId = r.id;
  138. let now = new Date();
  139. let expiresAt = (now.getFullYear() + 1) + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 12:00:00'
  140. console.log(expiresAt);
  141. let sql = `INSERT INTO "_Session" ("objectId","user", "sessionToken", "expiresAt", "createdWith")
  142. VALUES
  143. ('${objectId}','${user.id}', '${sessionToken}','${expiresAt}','{"action": "login","authProvider": "appPassword"}')
  144. ON CONFLICT("objectId") DO UPDATE
  145. SET
  146. "user" = excluded."user",
  147. "sessionToken" = excluded."sessionToken",
  148. "expiresAt"=excluded."expiresAt",
  149. "createdWith"=excluded."createdWith"
  150. `
  151. const data = await pgClient().any(sql);
  152. console.log('_Session', data)
  153. let doneObj = {
  154. get(field = 'sessionToken') {
  155. if (field = 'sessionToken') return sessionToken
  156. }
  157. }
  158. // let session = new Session();
  159. // session.set("user", {
  160. // __type: 'Pointer',
  161. // className: '_User',
  162. // objectId: user.id
  163. // });
  164. // session.set("sessionToken", sessionToken);
  165. // let now = new Date();
  166. // now.setFullYear(now.getFullYear() + 1);
  167. // let expiresAt = now;
  168. // session.set("expiresAt", expiresAt);
  169. // session.set("createdWith", {
  170. // "action": "login",
  171. // "authProvider": "appPassword"
  172. // })
  173. // session.set("restricted", false)
  174. // let doneObj = await session.save(null, {
  175. // useMasterKey: true
  176. // })
  177. // if (!doneObj) {
  178. // return false
  179. // }
  180. return doneObj
  181. }
  182. } catch (err) {
  183. console.log(err)
  184. return false
  185. }
  186. }
  187. module.exports = router;
  188. export const textbookRouter = router;