aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/auth.js
blob: 093f2978def17c4d27f4336367ba595485317a6a (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
'use strict';

var passport = require('passport'),
    path = require('path'),
    safe = require('safetydance'),
    fs = require('fs'),
    bcrypt = require('bcryptjs'),
    uuid = require('uuid/v4'),
    BearerStrategy = require('passport-http-bearer').Strategy,
    LdapStrategy = require('passport-ldapjs').Strategy,
    HttpError = require('connect-lastmile').HttpError,
    HttpSuccess = require('connect-lastmile').HttpSuccess;

const LOCAL_AUTH_FILE = path.resolve(process.env.LOCAL_AUTH_FILE || './.users.json');
const TOKENSTORE_FILE = path.resolve(process.env.TOKENSTORE_FILE || './.tokens.json');

var tokenStore = {
    data: {},
    save: function () {
        try {
            fs.writeFileSync(TOKENSTORE_FILE, JSON.stringify(tokenStore.data), 'utf-8');
        } catch (e) {
            console.error(`Unable to save tokenstore file at ${TOKENSTORE_FILE}`, e);
        }
    },
    get: function (token, callback) {
        callback(tokenStore.data[token] ? null : 'not found', tokenStore.data[token]);
    },
    set: function (token, data, callback) {
        tokenStore.data[token] = data;
        tokenStore.save();
        callback(null);
    },
    del: function (token, callback) {
        delete tokenStore.data[token];
        tokenStore.save();
        callback(null);
    }
};

// load token store data if any
try {
    console.log(`Using tokenstore file: ${TOKENSTORE_FILE}`);
    tokenStore.data = JSON.parse(fs.readFileSync(TOKENSTORE_FILE, 'utf-8'));
} catch (e) {
    // start with empty token store
}

function issueAccessToken() {
    return function (req, res, next) {
        var accessToken = uuid();

        tokenStore.set(accessToken, req.user, function (error) {
            if (error) return next(new HttpError(500, error));
            next(new HttpSuccess(201, { accessToken: accessToken, user: req.user }));
        });
    };
}

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('Using ldap auth');

    exports.login = [ passport.authenticate('ldap'), issueAccessToken() ];
} else {
    console.log(`Using local user file: ${LOCAL_AUTH_FILE}`);

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

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

                req.user = {
                    username: req.body.username
                };

                next();
            });
        },
        issueAccessToken()
    ];
}

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);
}));

exports.verify = passport.authenticate('bearer', { session: false });

passport.use(new BearerStrategy(function (token, done) {
    tokenStore.get(token, function (error, result) {
        if (error) {
            console.error(error);
            return done(null, false);
        }

        done(null, result, { accessToken: token });
    });
}));

exports.logout = function (req, res, next) {
    tokenStore.del(req.authInfo.accessToken, function (error) {
        if (error) console.error(error);

        next(new HttpSuccess(200, {}));
    });
};

exports.getProfile = function (req, res, next) {
    next(new HttpSuccess(200, { username: req.user.username }));
};