const API = require("../../../lib/API") const axios = require('axios') const { v4: uuidv4 } = require('uuid') const db = require("../../../plugin/DataBase/db") const config = require('../../../config.json') const { BaseStdResponse } = require("../../../BaseStdResponse"); class qqLoginStep1 extends API { constructor() { super() this.setPath('/User/qqLoginStep1') this.setMethod('POST') } async onRequest(req, res) { let { qq, location, deviceInfo } = req.body if ([qq, deviceInfo].some(value => value === '' || value === null || value === undefined)) return res.json({ ...BaseStdResponse.MISSING_PARAMETER }) if(String(qq).length > 10 || String(qq).length < 5) return res.json({ ...BaseStdResponse.ERR, msg: '请输入正确的QQ号' }) const uniConfig = config.unilogin let url = `${uniConfig.url}/connect.php?act=callback&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${type || 'qq'}&code=${code}` try { const r = await axios.get(url, { proxy: false }) if (!r || r.data?.code !== 0) { this.logger.error(`获取用户信息失败!${r.data?.msg || 'api接口错误'}`) return res.json({ ...BaseStdResponse.ERR, msg: '获取用户信息失败!' }) } let { social_uid, nickname, faceimg, ip } = r.data const session = uuidv4() const time = new Date().getTime() let selectSql = 'SELECT uuid, permission FROM users WHERE social_uid = ? AND social_type = ?' let selectRows = await db.query(selectSql, [social_uid, type || 'qq']) let uuid, username, permission // 用户不存在 执行注册操作 if (selectRows.length == 0) { uuid = uuidv4() username = `用户${uuid.slice(0, 8)}` let regSql = 'INSERT INTO users (uuid, username, session, registTime, social_uid, social_type, nickname, avatar, email) VALUES (?,?,?,?,?,?,?,?,?) ' let regRows = await db.query(regSql, [uuid, username, session, time, social_uid, type || 'qq', nickname, faceimg, '未设置']) if (!regRows || regRows.affectedRows !== 1) { this.logger.error(`聚合登录用户注册失败!数据库错误`) return res.json({ ...BaseStdResponse.ERR, msg: '用户注册失败!' }) } } else { let updateSql = 'UPDATE users SET session = ?, lastTime = ?, avatar = ?, nickname = ? WHERE social_uid = ? AND login_type = ?' let updateRows = await db.query(updateSql, [session, time, faceimg, nickname, social_uid, type || 'qq']) if (!updateRows || updateRows.affectedRows !== 1) { this.logger.error(`聚合登录用户登录失败!数据库错误`) return res.json({ ...BaseStdResponse.ERR, msg: '用户登录失败!请稍后再试' }) } username = selectRows[0].username permission = selectRows[0].permission } res.json({ ...BaseStdResponse.OK, data: { uuid, username, session, nickname, type: type || 'qq', roles: permission || [], avatar: faceimg, } }) // 增加登录记录 } catch (error) { this.logger.error(`获取用户信息失败!${error.message || 'api接口错误'}`) return res.json({ ...BaseStdResponse.ERR, msg: '获取用户信息失败!' }) } } } module.exports.qqLoginStep1 = qqLoginStep1