This repository has been archived by the owner on Dec 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
session.js
71 lines (61 loc) · 2.08 KB
/
session.js
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
var _ = require('lodash'),
redis = require('redis'),
createGithubApi = require('./create-github-api.js');
// Session backed by Redis, but that
// attempts to lookup against GHE if
// the token is not found in the DB.
function SessionGithub(opts) {
_.extend(this, {
client: redis.createClient(process.env.LOGIN_CACHE_REDIS),
githubHost: 'api.github.com',
debug: true,
githubPathPrefix: '/api/v3'
}, require('@npm/enterprise-configurator').Config(), opts)
}
SessionGithub.prototype.get = function(key, cb) {
var _this = this;
// First check if we have the session in Redis.
this.client.get(key, function(err, data) {
if (err) cb(err);
// If we do, simply return the existing session.
else if (data) cb(null, JSON.parse(data));
else {
// If we don't, talk to GHE instance. This can happen when, for example,
// user tries logging into a different npm Enterprise instance with an
// existing, logged in .npmrc.
_this._githubLookup(key, cb);
}
});
};
SessionGithub.prototype._githubLookup = function(key, cb) {
var _this = this,
github = createGithubApi(this),
// extract the GHE key from the user-<token> string.
token = key.split('-').splice(1).join('-');
// the token authenticator creates is a GitHub OAuth token, so we can simply
// try authenticating with it and then fetching the authenticated user.
github.authenticate({
type: 'oauth',
token: token
});
github.users.get({}, function(err, res) {
if (err) cb(err);
else if (res.code < 200 || res.code >= 400) cb(Error('status = ' + res.code));
else {
var session = {
name: res.login,
email: res.email || 'npme@example.com'
};
// If authentication with GitHub succeeded, persist the GitHub login and
// email in our session store.
_this.set(key, session, function(err) {
if (err) cb(err);
else cb(undefined, session);
});
}
});
};
SessionGithub.prototype.set = function(key, session, cb) {
this.client.set(key, JSON.stringify(session), cb);
};
module.exports = SessionGithub;