|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const Router = require('express').Router |
| 4 | +const passport = require('passport') |
| 5 | +const OpenIDStrategy = require('@passport-next/passport-openid').Strategy |
| 6 | +const config = require('../../../config') |
| 7 | +const models = require('../../../models') |
| 8 | +const logger = require('../../../logger') |
| 9 | +const {urlencodedParser} = require('../../utils') |
| 10 | +const {setReturnToFromReferer} = require('../utils') |
| 11 | + |
| 12 | +let openIDAuth = module.exports = Router() |
| 13 | + |
| 14 | +passport.use(new OpenIDStrategy({ |
| 15 | + returnURL: config.serverURL + '/auth/openid/callback', |
| 16 | + realm: config.serverURL, |
| 17 | + profile: true |
| 18 | +}, function (openid, profile, done) { |
| 19 | + var stringifiedProfile = JSON.stringify(profile) |
| 20 | + models.User.findOrCreate({ |
| 21 | + where: { |
| 22 | + profileid: openid |
| 23 | + }, |
| 24 | + defaults: { |
| 25 | + profile: stringifiedProfile |
| 26 | + } |
| 27 | + }).spread(function (user, created) { |
| 28 | + if (user) { |
| 29 | + var needSave = false |
| 30 | + if (user.profile !== stringifiedProfile) { |
| 31 | + user.profile = stringifiedProfile |
| 32 | + needSave = true |
| 33 | + } |
| 34 | + if (needSave) { |
| 35 | + user.save().then(function () { |
| 36 | + if (config.debug) { logger.info('user login: ' + user.id) } |
| 37 | + return done(null, user) |
| 38 | + }) |
| 39 | + } else { |
| 40 | + if (config.debug) { logger.info('user login: ' + user.id) } |
| 41 | + return done(null, user) |
| 42 | + } |
| 43 | + } |
| 44 | + }).catch(function (err) { |
| 45 | + logger.error('auth callback failed: ' + err) |
| 46 | + return done(err, null) |
| 47 | + }) |
| 48 | +})) |
| 49 | + |
| 50 | +openIDAuth.post('/auth/openid', urlencodedParser, function (req, res, next) { |
| 51 | + setReturnToFromReferer(req) |
| 52 | + passport.authenticate('openid')(req, res, next) |
| 53 | +}) |
| 54 | + |
| 55 | +// openID auth callback |
| 56 | +openIDAuth.get('/auth/openid/callback', |
| 57 | + passport.authenticate('openid', { |
| 58 | + successReturnToOrRedirect: config.serverurl + '/', |
| 59 | + failureRedirect: config.serverurl + '/' |
| 60 | + }) |
| 61 | +) |
0 commit comments