| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- 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,
- 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]
- )
- 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
|