aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/auth.js
blob: b56f09fbc9f736d254689b45a09e73309da69ec2 (plain) (blame)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict';

var passport = require('passport'),
    path = require('path'),
    safe = require('safetydance'),
    bcrypt = require('bcryptjs'),
    LdapStrategy = require('passport-ldapjs').Strategy;

var LOCAL_AUTH_FILE = path.resolve(process.env.LOCAL_AUTH_FILE || './.users.json');

passport.serializeUser(function (user, done) {
    console.log('serializeUser', user);
    done(null, user.uid);
});

passport.deserializeUser(function (id, done) {
    console.log('deserializeUser', id);
    done(null, { uid: id });
});

var LDAP_URL = process.env.LDAP_URL;
var LDAP_USERS_BASE_DN = process.env.LDAP_USERS_BASE_DN;

if (LDAP_URL && LDAP_USERS_BASE_DN) {
    console.log('Enable ldap auth');

    exports.verify = passport.authenticate('ldap');
} else {
    console.log('Use local user file:', LOCAL_AUTH_FILE);

    exports.verify = function (req, res, next) {
        var users = safe.JSON.parse(safe.fs.readFileSync(LOCAL_AUTH_FILE));
        if (!users) return res.send(401);
        if (!users[req.query.username]) return res.send(401);

        bcrypt.compare(req.query.password, users[req.query.username].passwordHash, function (error, valid) {
            if (error || !valid) return res.send(401);
            next();
        });
    };
}

var opts = {
    server: {
        url: LDAP_URL,
    },
    base: LDAP_USERS_BASE_DN,
    search: {
        filter: '(|(username={{username}})(mail={{username}}))',
        attributes: ['displayname', 'username', 'mail', 'uid'],
        scope: 'sub'
    },
    uidTag: 'cn',
    usernameField: 'username',
    passwordField: 'password',
};

passport.use(new LdapStrategy(opts, function (profile, done) {
    done(null, profile);
}));