UnbindSocial.js 3.0 KB

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