const API = require("../../../lib/API") const db = require("../../../plugin/DataBase/db") const AccessControl = require("../../../lib/AccessControl") const { BaseStdResponse } = require("../../../BaseStdResponse") const { normalizeSocialType } = require('../../../lib/UniLoginClient') const { getUserSocialBindings, removeSocialBinding, syncLegacySocialMirror, toSocialBindingSummary } = require('../../../lib/UserSocialBinding') class UnbindSocial extends API { constructor() { super() this.setPath('/UniLogin/UnbindSocial') this.setMethod('POST') } async onRequest(req, res) { let { uuid, session, type, social_type } = req.body const channelType = normalizeSocialType(type ?? social_type) if ([uuid, session].some(value => value === '' || value === null || value === undefined)) return res.json({ ...BaseStdResponse.MISSING_PARAMETER }) if (!channelType) return res.json({ ...BaseStdResponse.ERR, msg: '不支持的第三方账号类型' }) if (!await AccessControl.checkSession(uuid, session)) return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED }) try { const bindings = await getUserSocialBindings(uuid) if (!bindings.some(binding => binding.social_type === channelType)) return res.json({ ...BaseStdResponse.ERR, msg: '当前账号未绑定该第三方账号' }) const userRows = await db.query('SELECT password FROM users WHERE uuid = ? LIMIT 1', [uuid]) if (!userRows || userRows.length === 0) return res.json({ ...BaseStdResponse.ERR, msg: '用户不存在' }) if (bindings.length <= 1 && !userRows[0].password) return res.json({ ...BaseStdResponse.ERR, msg: '请先设置登录密码或绑定其他第三方账号后再解绑' }) const result = await removeSocialBinding(uuid, channelType) if (!result || result.affectedRows !== 1) return res.json({ ...BaseStdResponse.ERR, msg: '解绑失败,请稍后再试' }) await syncLegacySocialMirror(uuid) const newBindings = await getUserSocialBindings(uuid) return res.json({ ...BaseStdResponse.OK, data: { socialBindings: toSocialBindingSummary(newBindings), boundTypes: newBindings.map(binding => binding.social_type) } }) } catch (error) { this.logger.error(`解绑第三方账号失败!${error.message || error}`) return res.json({ ...BaseStdResponse.ERR, msg: '解绑失败,请稍后再试' }) } } } module.exports.UnbindSocial = UnbindSocial