forked from tpreusse/auth-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
149 lines (141 loc) · 4.25 KB
/
index.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
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
143
144
145
146
147
148
149
const express = require('express');
const session = require('express-session');
const fetch = require('node-fetch');
const queryString = require('query-string');
const __DEV__ = process.env.NODE_ENV === 'development';
if (__DEV__) {
require('node-env-file')(
require('path').join(__dirname, '.env'),
{raise: false}
);
}
const DEFAULTS = {
PORT: 3000
};
const PARSE = {
CALLBACK_BASE_URLS: (value) => value.split(','),
BASE_URL: (value) => {
if (!__DEV__ && !value.startsWith('https://')) {
throw new Error('BASE_URL should be https');
}
if(!value.endsWith('/')) {
throw new Error('BASE_URL should include a tailing slash');
}
return value;
}
};
const config = [
'NODE_ENV', 'PORT', 'BASE_URL', 'SESSION_SECRET',
'GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET', 'CALLBACK_BASE_URLS'
].reduce(
(reduction, key) => {
let value = process.env[key] || DEFAULTS[key];
if (!value) {
throw new Error(`Environment variable ${key} missing, see README.md#Configuration`);
}
if (PARSE[key]) {
value = PARSE[key](value);
}
reduction[key] = value;
return reduction;
},
{}
);
const app = express();
app.enable('trust proxy');
app.disable('x-powered-by');
app.use(session({
cookie: {
path: '/',
httpOnly: true,
secure: !(__DEV__ && !config.BASE_URL.startsWith('https://')),
maxAge: null
},
secret: config.SESSION_SECRET,
resave: false,
saveUninitialized: true
}));
const verifyCallbackUrl = (url) => {
return config.CALLBACK_BASE_URLS.some((callbackBaseUrl) => url.startsWith(callbackBaseUrl));
};
app.get('/github/callback', (request, response) => {
if (request.query.state !== request.session.githubState) {
response.status(404).send('Not found');
return;
}
if (request.query.error) {
response.status(500).json({
error: request.query.error,
error_description: request.query.error_description,
error_uri: request.query.error_uri
});
return;
}
const parameters = {
client_id: config.GITHUB_CLIENT_ID,
client_secret: config.GITHUB_CLIENT_SECRET,
code: request.query.code,
state: request.session.githubState
};
fetch(
`https://github.com/login/oauth/access_token?${queryString.stringify(parameters)}`,
{method: 'POST', headers: {'Accept': 'application/json'}}
)
.then((response) => response.json().then(
(data) => ({response, data}),
(error) => {
throw new Error(`Failed to parse JSON, ${error}`)
}
))
.then((result) => {
if (result.response.ok) {
const callbackUrl = request.session.callbackUrl;
// reverify callback url in case of an untrustworthy session store
if (verifyCallbackUrl(callbackUrl)) {
response
.status(302)
.set(
'Location',
`${callbackUrl}#${queryString.stringify({
code: result.data.access_token,
scope: result.data.scope,
state: parameters.state
})}`
)
.end();
} else {
response.status(404).send('Not found');
}
} else {
response.status(result.response.status).json(result.data);
}
})
.catch((error) => {
response.status(500).json({
error: error.toString()
})
});
});
app.get('/github/login', (request, response) => {
if (!verifyCallbackUrl(request.query.callbackUrl)) {
response.status(404).send('Not found');
return;
}
if (!request.query.state || request.query.state.length < 12) {
// the client needs to generate a secret to ensure it only accepts real tokens
response.status(400).send('A strong, user specific state parameter is required against CSRF attacks');
}
const parameters = {
client_id: config.GITHUB_CLIENT_ID,
state: request.query.state,
scope: request.query.scope,
redirect_uri: `${config.BASE_URL}github/callback`
};
request.session.callbackUrl = request.query.callbackUrl;
request.session.githubState = request.query.state;
response
.status(302)
.set('Location', `https://github.com/login/oauth/authorize?${queryString.stringify(parameters)}`)
.end();
});
app.listen(config.PORT, () => console.info(`Listening on ${config.PORT}`)); // eslint-disable-line no-console