Login.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. const API = require("../../../lib/API")
  2. const axios = require('axios')
  3. const { v4: uuidv4 } = require('uuid')
  4. const db = require("../../../plugin/DataBase/db")
  5. const Redis = require('../../../plugin/DataBase/Redis')
  6. const config = require('../../../config.json')
  7. const { BaseStdResponse } = require("../../../BaseStdResponse")
  8. class Login extends API {
  9. constructor() {
  10. super()
  11. this.setPath('/UniLogin/Login')
  12. this.setMethod('POST')
  13. }
  14. async onRequest(req, res) {
  15. let { type, code } = req.body
  16. if ([code].some(value => value === '' || value === null || value === undefined))
  17. return res.json({
  18. ...BaseStdResponse.MISSING_PARAMETER
  19. })
  20. const uniConfig = config.unilogin
  21. let url = `${uniConfig.url}/connect.php?act=callback&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${type || 'qq'}&code=${code}`
  22. try {
  23. const r = await axios.get(url, {
  24. proxy: false
  25. })
  26. if (!r || r.data?.code !== 0) {
  27. this.logger.error(`获取用户信息失败!${r.data?.msg || 'api接口错误'}`)
  28. return res.json({
  29. ...BaseStdResponse.ERR,
  30. msg: '获取用户信息失败!'
  31. })
  32. }
  33. let { social_uid, nickname, faceimg, ip } = r.data
  34. const session = uuidv4()
  35. const time = new Date().getTime()
  36. let selectSql = 'SELECT uuid, username, permission FROM users WHERE social_uid = ? AND social_type = ?'
  37. let selectRows = await db.query(selectSql, [social_uid, type || 'qq'])
  38. let uuid, username, permission
  39. // 用户不存在 执行注册操作
  40. if (selectRows.length == 0) {
  41. uuid = uuidv4()
  42. username = `用户${uuid.slice(0, 8)}`
  43. let regSql = 'INSERT INTO users (uuid, username, registTime, social_uid, social_type, nickname, avatar, email) VALUES (?,?,?,?,?,?,?,?) '
  44. let regRows = await db.query(regSql, [uuid, username, time, social_uid, type || 'qq', nickname, faceimg, '未设置'])
  45. if (!regRows || regRows.affectedRows !== 1) {
  46. this.logger.error(`聚合登录用户注册失败!数据库错误`)
  47. return res.json({
  48. ...BaseStdResponse.ERR,
  49. msg: '用户注册失败!'
  50. })
  51. }
  52. }
  53. else {
  54. uuid = selectRows[0].uuid
  55. username = selectRows[0].username
  56. permission = selectRows[0].permission
  57. }
  58. await Redis.set(`userSession:${uuid}`, session, {
  59. exp: 2592000
  60. })
  61. res.json({
  62. ...BaseStdResponse.OK,
  63. data: {
  64. uuid,
  65. username,
  66. session,
  67. nickname,
  68. type: type || 'qq',
  69. roles: permission || [],
  70. avatar: faceimg,
  71. }
  72. })
  73. // 增加登录记录
  74. try {
  75. if (selectRows.length !== 0) {
  76. let updateSql = 'UPDATE users SET lastTime = ?, avatar = ?, nickname = ? WHERE social_uid = ? AND social_type = ?'
  77. await db.query(updateSql, [time, faceimg, nickname, social_uid, type || 'qq'])
  78. }
  79. const userAgent = req.headers['user-agent']
  80. let insertSql = 'INSERT INTO login_history (uuid, time, deviceInfo, type, ip) VALUES (?, ?, ?, ?, ?)'
  81. await db.query(insertSql, [uuid, time, { 'ua': userAgent }, type || 'qq', ip])
  82. } catch (error) {
  83. this.logger.error(`写入登录记录失败!${error}`)
  84. }
  85. } catch (error) {
  86. this.logger.error(`获取用户信息失败!${error.message || 'api接口错误'}`)
  87. return res.json({
  88. ...BaseStdResponse.ERR,
  89. msg: '获取用户信息失败!'
  90. })
  91. }
  92. }
  93. }
  94. module.exports.Login = Login