func-authing-session-sync.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const { AuthenticationClient } = require('authing-js-sdk')
  2. import { pgClient } from '../../db/pg-instance'
  3. export function defineAuthingLogin(){
  4. Parse.Cloud.define("authingLogin", async (request) => {
  5. let token = request.params.token;
  6. if(token) {
  7. let result = await syncSessionWithIdToken(token)
  8. return result
  9. }
  10. return null
  11. },{
  12. fields : {
  13. token:{
  14. required:true
  15. }
  16. }
  17. });
  18. }
  19. /**
  20. * 同步用户登录信息
  21. * @desc
  22. * https://docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html#获取当前登录的用户信息
  23. * @param {*} token
  24. * @returns
  25. */
  26. async function syncSessionWithIdToken(token){
  27. // 通过用户的 id_token 初始化之后获取用户信息
  28. let authenticationClient = new AuthenticationClient({
  29. appId: '6682ab96b7bd5db59d6785a0',
  30. appHost: 'https://textbook.u2-dev.hep.com.cn', // 应用的认证地址
  31. token: token
  32. })
  33. let user = await authenticationClient.getCurrentUser()
  34. // console.log(user)
  35. // 生成Parse库所需_Session记录 objectId唯一
  36. let sessionObjectId = generateObjectId(user?.id+user?.token)
  37. let username = user?.phone || user?.username || user?.email
  38. let syncSessionSQL = `
  39. INSERT INTO "_User" ("objectId", "username","mobile", "createdAt", "updatedAt")
  40. VALUES
  41. ($2,$7,$8,$5,$6)
  42. ON conflict("objectId") DO UPDATE
  43. SET
  44. "username" = excluded."username",
  45. "updatedAt"=excluded."updatedAt";
  46. ALTER TABLE "_Session"
  47. ADD CONSTRAINT unique_objectId UNIQUE ("objectId");
  48. INSERT INTO "_Session" ("objectId", "user", "sessionToken","expiresAt", "createdAt")
  49. VALUES
  50. ($1, $2,$3,$4,$5)
  51. ON conflict("objectId") DO UPDATE
  52. SET
  53. "user" = excluded."user",
  54. "sessionToken" = excluded."sessionToken",
  55. "expiresAt"=excluded."expiresAt";
  56. `
  57. let params = [sessionObjectId,user?.id,user?.token,user?.tokenExpiredAt,new Date(),new Date(),username,user?.phone]
  58. if(user?.id&&user?.token){
  59. try {
  60. // 查询:数据库版本信息
  61. const data = await pgClient().any(syncSessionSQL,params);
  62. // console.log(data)
  63. return {
  64. sid:sessionObjectId,
  65. uid:user?.id,
  66. sessionToken:user?.token
  67. };
  68. } catch (error) {
  69. console.error('Error executing query:', error);
  70. return error;
  71. }
  72. }
  73. }
  74. module.exports.syncSessionWithIdToken = syncSessionWithIdToken
  75. const crypto = require('crypto');
  76. function generateObjectId(inputString) {
  77. const hash = crypto.createHash('sha256').update(inputString).digest('hex');
  78. const objectId = hash;
  79. return objectId;
  80. }