summaryrefslogtreecommitdiff
path: root/lib/web/auth/ldap
diff options
context:
space:
mode:
authorBoHong Li2017-04-12 05:41:14 +0800
committerRaccoon Li2017-05-08 19:24:38 +0800
commit69a9f7ca38875dc110697960a8f9db5ac2bcd97c (patch)
tree4d61c1e2541e661e0cfcce833f7941d0fd1066c6 /lib/web/auth/ldap
parent766022378a2f276df2f2d2f003e2124044ab2df0 (diff)
refactor(app.js, auth.js): Extract all auth method to individual modules
Diffstat (limited to 'lib/web/auth/ldap')
-rw-r--r--lib/web/auth/ldap/index.js74
1 files changed, 74 insertions, 0 deletions
diff --git a/lib/web/auth/ldap/index.js b/lib/web/auth/ldap/index.js
new file mode 100644
index 00000000..766c5cbc
--- /dev/null
+++ b/lib/web/auth/ldap/index.js
@@ -0,0 +1,74 @@
+'use strict'
+
+const Router = require('express').Router
+const passport = require('passport')
+const LDAPStrategy = require('passport-ldapauth')
+const config = require('../../../config')
+const models = require('../../../models')
+const logger = require('../../../logger')
+const {setReturnToFromReferer} = require('../utils')
+const {urlencodedParser} = require('../../utils')
+const response = require('../../../response')
+
+let ldapAuth = module.exports = Router()
+
+passport.use(new LDAPStrategy({
+ server: {
+ url: config.ldap.url || null,
+ bindDn: config.ldap.bindDn || null,
+ bindCredentials: config.ldap.bindCredentials || null,
+ searchBase: config.ldap.searchBase || null,
+ searchFilter: config.ldap.searchFilter || null,
+ searchAttributes: config.ldap.searchAttributes || null,
+ tlsOptions: config.ldap.tlsOptions || null
+ }
+}, function (user, done) {
+ var profile = {
+ id: 'LDAP-' + user.uidNumber,
+ username: user.uid,
+ displayName: user.displayName,
+ emails: user.mail ? [user.mail] : [],
+ avatarUrl: null,
+ profileUrl: null,
+ provider: 'ldap'
+ }
+ var stringifiedProfile = JSON.stringify(profile)
+ models.User.findOrCreate({
+ where: {
+ profileid: profile.id.toString()
+ },
+ defaults: {
+ profile: stringifiedProfile
+ }
+ }).spread(function (user, created) {
+ if (user) {
+ var needSave = false
+ if (user.profile !== stringifiedProfile) {
+ user.profile = stringifiedProfile
+ needSave = true
+ }
+ if (needSave) {
+ user.save().then(function () {
+ if (config.debug) { logger.debug('user login: ' + user.id) }
+ return done(null, user)
+ })
+ } else {
+ if (config.debug) { logger.debug('user login: ' + user.id) }
+ return done(null, user)
+ }
+ }
+ }).catch(function (err) {
+ logger.error('ldap auth failed: ' + err)
+ return done(err, null)
+ })
+}))
+
+ldapAuth.post('/auth/ldap', urlencodedParser, function (req, res, next) {
+ if (!req.body.username || !req.body.password) return response.errorBadRequest(res)
+ setReturnToFromReferer(req)
+ passport.authenticate('ldapauth', {
+ successReturnToOrRedirect: config.serverurl + '/',
+ failureRedirect: config.serverurl + '/',
+ failureFlash: true
+ })(req, res, next)
+})