Login.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. const API = require("../../../lib/API")
  2. const { v4: uuidv4 } = require('uuid')
  3. const db = require("../../../plugin/DataBase/db")
  4. const Redis = require('../../../plugin/DataBase/Redis')
  5. const { BaseStdResponse } = require("../../../BaseStdResponse")
  6. const { fetchUniLoginProfile, normalizeSocialType } = require('../../../lib/UniLoginClient')
  7. const {
  8. getBindingByIdentity,
  9. getLegacyUserByIdentity,
  10. insertSocialBinding,
  11. updateSocialBindingProfile,
  12. syncLegacySocialMirror
  13. } = require('../../../lib/UserSocialBinding')
  14. class Login extends API {
  15. constructor() {
  16. super()
  17. this.setPath('/UniLogin/Login')
  18. this.setMethod('POST')
  19. }
  20. async onRequest(req, res) {
  21. let { type, code } = req.body
  22. type = normalizeSocialType(type)
  23. if ([code].some(value => value === '' || value === null || value === undefined))
  24. return res.json({
  25. ...BaseStdResponse.MISSING_PARAMETER
  26. })
  27. if (!type)
  28. return res.json({
  29. ...BaseStdResponse.ERR,
  30. msg: '不支持的第三方登录类型'
  31. })
  32. try {
  33. let { social_uid, nickname, faceimg, ip } = await fetchUniLoginProfile(type, code)
  34. const session = uuidv4()
  35. const time = new Date().getTime()
  36. let binding = await getBindingByIdentity(type, social_uid)
  37. let uuid = binding?.user_uuid
  38. let selectRows = []
  39. if (uuid) {
  40. selectRows = await db.query('SELECT * FROM users WHERE uuid = ? LIMIT 1', [uuid])
  41. } else {
  42. const legacyUser = await getLegacyUserByIdentity(type, social_uid)
  43. if (legacyUser?.uuid) {
  44. uuid = legacyUser.uuid
  45. await insertSocialBinding(uuid, type, social_uid, nickname, faceimg)
  46. selectRows = await db.query('SELECT * FROM users WHERE uuid = ? LIMIT 1', [uuid])
  47. }
  48. }
  49. if (!uuid) {
  50. uuid = uuidv4()
  51. const username = `用户${uuid.slice(0, 8)}`
  52. let regSql = 'INSERT INTO users (uuid, username, registTime, social_uid, social_type, nickname, avatar, email) VALUES (?,?,?,?,?,?,?,?) '
  53. let regRows = await db.query(regSql, [uuid, username, time, social_uid, type, nickname, faceimg, '未设置'])
  54. if (!regRows || regRows.affectedRows !== 1) {
  55. this.logger.error(`聚合登录用户注册失败!数据库错误`)
  56. return res.json({
  57. ...BaseStdResponse.ERR,
  58. msg: '用户注册失败!'
  59. })
  60. }
  61. await insertSocialBinding(uuid, type, social_uid, nickname, faceimg)
  62. selectRows = await db.query('SELECT * FROM users WHERE uuid = ? LIMIT 1', [uuid])
  63. }
  64. if (!selectRows || selectRows.length === 0)
  65. return res.json({
  66. ...BaseStdResponse.ERR,
  67. msg: '用户登录失败!请稍后再试'
  68. })
  69. const user = selectRows[0]
  70. await Redis.set(`userSession:${uuid}`, session, {
  71. EX: 2592000
  72. })
  73. await db.query(
  74. 'UPDATE users SET lastTime = ?, avatar = ?, nickname = ? WHERE uuid = ?',
  75. [time, faceimg, nickname, uuid]
  76. )
  77. await updateSocialBindingProfile(type, social_uid, nickname, faceimg)
  78. await syncLegacySocialMirror(uuid, type)
  79. res.json({
  80. ...BaseStdResponse.OK,
  81. data: {
  82. uuid,
  83. username: user.username,
  84. session,
  85. nickname,
  86. type,
  87. roles: user.permission || [],
  88. vip: user.vip,
  89. ic_count: user.ic_count,
  90. lepao_count: user.lepao_count,
  91. crouse_count: user.crouse_count,
  92. avatar: faceimg || user.avatar,
  93. email: user.email
  94. }
  95. })
  96. // 增加登录记录
  97. try {
  98. const userAgent = req.headers['user-agent']
  99. let insertSql = 'INSERT INTO login_history (uuid, time, deviceInfo, type, ip) VALUES (?, ?, ?, ?, ?)'
  100. await db.query(insertSql, [uuid, time, { 'ua': userAgent }, type, ip])
  101. } catch (error) {
  102. this.logger.error(`写入登录记录失败!${error}`)
  103. }
  104. } catch (error) {
  105. this.logger.error(`获取用户信息失败!${error.message || 'api接口错误'}`)
  106. return res.json({
  107. ...BaseStdResponse.ERR,
  108. msg: '获取用户信息失败!'
  109. })
  110. }
  111. }
  112. }
  113. module.exports.Login = Login