All files / koa/auth/qq passport.js

28.57% Statements 6/21
0% Branches 0/15
50% Functions 1/2
31.58% Lines 6/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46    5x 5x 5x 5x   5x 5x                                                                          
'use strict'
 
const passport = require('koa-passport')
const qqStrategy = require('passport-qq').Strategy
const tools = require('../../util/tools')
const debug = require('../../util/debug')('auth:qq')
 
exports.setup = function (User, config) {
  passport.use(new qqStrategy({
    clientID: config.qq.clientID,
    clientSecret: config.qq.clientSecret,
    callbackURL: config.qq.callbackURL,
    passReqToCallback: true,
  },
  async(req, accessToken, refreshToken, profile, done) => {
    var userId = req.session.passport.userId || null
    // profile._json.token = accessToken
    if (userId) { return done(new Error('you are logined')) }
    try {
      const checkUserId = await User.findOne({ 'qq.id': profile.id })
      if (checkUserId) { return done(null, checkUserId) }
      let newUser = {
        username: profile._json.username || '',
        avatar: profile._json.figureurl_qq_2 || profile._json.figureurl_2 || '',
        provider: 'qq',
        qq: {
          id: profile.id,
          token: accessToken,
          name: profile._json.username || '',
          email: '',
        },
        status: 1,
      }
      const checkUserName = await User.findOne({ username: newUser.username })
      if (checkUserName) {
        newUser.username = tools.randomString()
      }
      const user = await new User(newUser).save()
      return done(null, user)
    } catch (err) {
      debug('qqStrategy error')
      return done(err)
    }
  }
  ))
}