| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- const API = require("../../../lib/API")
- const db = require("../../../plugin/DataBase/db")
- const AccessControl = require("../../../lib/AccessControl")
- const { BaseStdResponse } = require("../../../BaseStdResponse")
- const { fetchUniLoginProfile, normalizeSocialType } = require('../../../lib/UniLoginClient')
- const {
- getBindingByIdentity,
- getUserSocialBindings,
- insertSocialBinding,
- updateSocialBindingProfile,
- syncLegacySocialMirror,
- toSocialBindingSummary
- } = require('../../../lib/UserSocialBinding')
- class BindSocial extends API {
- constructor() {
- super()
- this.setPath('/UniLogin/BindSocial')
- this.setMethod('POST')
- }
- async onRequest(req, res) {
- let { uuid, session, type, code } = req.body
- type = normalizeSocialType(type)
- if ([uuid, session, code].some(value => value === '' || value === null || value === undefined))
- return res.json({
- ...BaseStdResponse.MISSING_PARAMETER
- })
- if (!type)
- return res.json({
- ...BaseStdResponse.ERR,
- msg: '不支持的第三方账号类型'
- })
- if (!await AccessControl.checkSession(uuid, session))
- return res.status(401).json({
- ...BaseStdResponse.ACCESS_DENIED
- })
- try {
- const { social_uid, nickname, faceimg } = await fetchUniLoginProfile(type, code)
- const identityBinding = await getBindingByIdentity(type, social_uid)
- if (identityBinding && identityBinding.user_uuid !== uuid)
- return res.json({
- ...BaseStdResponse.ERR,
- msg: '该第三方账号已绑定其他用户'
- })
- const bindings = await getUserSocialBindings(uuid)
- if (bindings.some(binding => binding.social_type === type))
- return res.json({
- ...BaseStdResponse.ERR,
- msg: `当前账号已绑定${type === 'qq' ? 'QQ' : '微信'}`
- })
- const result = await insertSocialBinding(uuid, type, social_uid, nickname, faceimg)
- if (!result || result.affectedRows !== 1)
- return res.json({
- ...BaseStdResponse.ERR,
- msg: '绑定失败,请稍后再试'
- })
- await updateSocialBindingProfile(type, social_uid, nickname, faceimg)
- await db.query(
- 'UPDATE users SET nickname = COALESCE(NULLIF(nickname, ""), ?), avatar = COALESCE(NULLIF(avatar, ""), ?) WHERE uuid = ?',
- [nickname, faceimg, uuid]
- )
- await syncLegacySocialMirror(uuid, type)
- 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.BindSocial = BindSocial
|