func-authing-session-sync.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. const { AuthenticationClient } = require('authing-js-sdk')
  2. import { pgClient } from '../../db/pg-instance'
  3. // const { pgClient } = require('../../db/pg-instance')
  4. export function defineAuthingLogin(){
  5. Parse.Cloud.define("authingLogin", async (request) => {
  6. let token = request.params.token;
  7. if(token) {
  8. let result = await syncSessionWithIdToken(token);
  9. return result;
  10. }
  11. return null;
  12. },{
  13. fields : {
  14. token:{
  15. required:true
  16. }
  17. }
  18. });
  19. Parse.Cloud.define("userFind", async (request) => {
  20. let mobile = request.params.mobile;
  21. if(mobile) {
  22. let user = {
  23. mobile:mobile
  24. }
  25. let result = await getParseUserByAuthingUser(user);
  26. return result;
  27. }
  28. return null;
  29. },{
  30. fields : {
  31. mobile:{
  32. required:true
  33. }
  34. }
  35. });
  36. }
  37. /**
  38. * 同步用户登录信息
  39. * @desc
  40. * https://docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html#获取当前登录的用户信息
  41. * @param {*} token
  42. * @returns
  43. */
  44. async function syncSessionWithIdToken(token){
  45. // 通过用户的 id_token 初始化之后获取用户信息
  46. let authenticationClient = new AuthenticationClient({
  47. appId: '6682ab96b7bd5db59d6785a0',
  48. appHost: 'https://textbook.u2-dev.hep.com.cn', // 应用的认证地址
  49. token: token
  50. })
  51. let user = await authenticationClient.getCurrentUser()
  52. // console.log(user)
  53. // 生成Parse库所需_Session记录 objectId唯一
  54. let sessionObjectId = generateObjectId(user?.id+user?.token);
  55. let username = user?.username || user?.phone || user?.email
  56. let ParseExistUser = await getParseUserByAuthingUser(user);
  57. let userId = ParseExistUser?.objectId || user?.id;
  58. console.log("userId",userId);
  59. console.log("authingUser",user);
  60. console.log("ParseExistUser",ParseExistUser);
  61. let syncSessionSQL = `
  62. INSERT INTO "_User" (
  63. "objectId", "username","mobile","phone", "createdAt", "updatedAt",
  64. "lastIP","lastLogin","userSourceType","loginsCount"
  65. )
  66. VALUES
  67. (
  68. $2,$7,$8,$8,$5,$6,
  69. $9,$10,$11,$12
  70. )
  71. ON conflict("objectId") DO UPDATE
  72. SET
  73. "username" = excluded."username",
  74. "updatedAt"=excluded."updatedAt",
  75. "mobile"=excluded."mobile",
  76. "phone"=excluded."phone",
  77. "lastIP"=excluded."lastIP",
  78. "lastLogin"=excluded."lastLogin",
  79. "userSourceType"=excluded."userSourceType",
  80. "loginsCount"=excluded."loginsCount";
  81. INSERT INTO "_Session" ("objectId", "user", "sessionToken","expiresAt", "createdAt")
  82. VALUES
  83. ($1, $2,$3,$4,$5)
  84. ON conflict("objectId") DO UPDATE
  85. SET
  86. "user" = excluded."user",
  87. "sessionToken" = excluded."sessionToken",
  88. "expiresAt"=excluded."expiresAt";
  89. `
  90. let params = [
  91. // 1-4
  92. sessionObjectId,userId,user?.token,user?.tokenExpiredAt,
  93. // 5-8
  94. new Date(),new Date(),username,user?.phone,
  95. // 9-12
  96. user?.lastIP, user?.lastLogin, user?.userSourceType,user?.loginsCount
  97. ]
  98. if(user?.id&&user?.token){
  99. try {
  100. // 查询:数据库版本信息
  101. let data = await pgClient().any(syncSessionSQL,params);
  102. console.log("session sql",data)
  103. return {
  104. sid:sessionObjectId,
  105. uid:user?.id,
  106. sessionToken:user?.token
  107. };
  108. } catch (error) {
  109. console.error('Error executing query:', error);
  110. return error;
  111. }
  112. }
  113. }
  114. module.exports.syncSessionWithIdToken = syncSessionWithIdToken
  115. async function getParseUserByAuthingUser(user){
  116. let sql = `
  117. SELECT * FROM "_User" WHERE
  118. "objectId"=$1 OR
  119. "objectId"=$2 OR
  120. "username"=$3 OR
  121. "username"=$4 OR
  122. "username"=$5 OR
  123. "username"=$6 OR
  124. ("mobile" IS NOT NULL AND "mobile" = $4) OR
  125. ("phone" IS NOT NULL AND "phone" = $4) OR
  126. ("mobile" IS NOT NULL AND "mobile" = $5) OR
  127. ("phone" IS NOT NULL AND "phone" = $5) OR
  128. ("email" IS NOT NULL AND "email" = $6)
  129. `
  130. let params = [
  131. user?.id, //1
  132. user?.externalId,//2
  133. user?.username,//3
  134. user?.phone,//4
  135. user?.mobile,//5
  136. user?.email//6
  137. ]
  138. let data = []
  139. try{
  140. data = await pgClient().any(sql,params);
  141. console.log("data same user:",data)
  142. if(data?.length){
  143. return data[0]
  144. }
  145. }catch(err){
  146. console.error(err)
  147. }
  148. return null
  149. }
  150. const crypto = require('crypto');
  151. function generateObjectId(inputString) {
  152. inputString = inputString || ""
  153. inputString = String(inputString)
  154. const hash = crypto.createHash('sha256').update(inputString).digest('hex');
  155. const objectId = hash;
  156. return objectId;
  157. }