UnbindSocial.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const API = require("../../../lib/API")
  2. const db = require("../../../plugin/DataBase/db")
  3. const AccessControl = require("../../../lib/AccessControl")
  4. const { BaseStdResponse } = require("../../../BaseStdResponse")
  5. const { normalizeSocialType } = require('../../../lib/UniLoginClient')
  6. const {
  7. getUserSocialBindings,
  8. removeSocialBinding,
  9. syncLegacySocialMirror,
  10. toSocialBindingSummary
  11. } = require('../../../lib/UserSocialBinding')
  12. class UnbindSocial extends API {
  13. constructor() {
  14. super()
  15. this.setPath('/UniLogin/UnbindSocial')
  16. this.setMethod('POST')
  17. }
  18. async onRequest(req, res) {
  19. let { uuid, session, social_type } = req.body
  20. social_type = normalizeSocialType(social_type)
  21. if ([uuid, session].some(value => value === '' || value === null || value === undefined))
  22. return res.json({
  23. ...BaseStdResponse.MISSING_PARAMETER
  24. })
  25. if (!social_type)
  26. return res.json({
  27. ...BaseStdResponse.ERR,
  28. msg: '不支持的第三方账号类型'
  29. })
  30. if (!await AccessControl.checkSession(uuid, session))
  31. return res.status(401).json({
  32. ...BaseStdResponse.ACCESS_DENIED
  33. })
  34. try {
  35. const bindings = await getUserSocialBindings(uuid)
  36. if (!bindings.some(binding => binding.social_type === social_type))
  37. return res.json({
  38. ...BaseStdResponse.ERR,
  39. msg: '当前账号未绑定该第三方账号'
  40. })
  41. const userRows = await db.query('SELECT password FROM users WHERE uuid = ? LIMIT 1', [uuid])
  42. if (!userRows || userRows.length === 0)
  43. return res.json({
  44. ...BaseStdResponse.ERR,
  45. msg: '用户不存在'
  46. })
  47. if (bindings.length <= 1 && !userRows[0].password)
  48. return res.json({
  49. ...BaseStdResponse.ERR,
  50. msg: '请先设置登录密码或绑定其他第三方账号后再解绑'
  51. })
  52. const result = await removeSocialBinding(uuid, social_type)
  53. if (!result || result.affectedRows !== 1)
  54. return res.json({
  55. ...BaseStdResponse.ERR,
  56. msg: '解绑失败,请稍后再试'
  57. })
  58. await syncLegacySocialMirror(uuid)
  59. const newBindings = await getUserSocialBindings(uuid)
  60. return res.json({
  61. ...BaseStdResponse.OK,
  62. data: {
  63. socialBindings: toSocialBindingSummary(newBindings),
  64. boundTypes: newBindings.map(binding => binding.social_type)
  65. }
  66. })
  67. } catch (error) {
  68. this.logger.error(`解绑第三方账号失败!${error.message || error}`)
  69. return res.json({
  70. ...BaseStdResponse.ERR,
  71. msg: '解绑失败,请稍后再试'
  72. })
  73. }
  74. }
  75. }
  76. module.exports.UnbindSocial = UnbindSocial