Skip to content
This repository was archived by the owner on Jan 5, 2023. It is now read-only.

Commit 4be8673

Browse files
committed
add API key session creation mechanism
1 parent ccaa228 commit 4be8673

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

app.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@ app.use(session({
1212
}))
1313

1414
const { login, logout, checkAuth } = require('./express-handlers')
15+
const headerAuth = require('./header-auth-middleware');
1516

1617
app.post('/session', login)
1718
app.delete('/session', logout)
18-
app.get('/session', checkAuth)
19+
app.get('/session', headerAuth, checkAuth)
1920

2021
const PORT = process.env.PORT || 3000
2122
app.listen(PORT, () => {

header-auth-middleware.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const apiKeyToUser = {
2+
'76b1e728-1c14-43f9-aa06-6de5cbc064c2': 'hugo',
3+
};
4+
5+
const apiKeys = new Set(Object.keys(apiKeyToUser))
6+
7+
const isApiKey = key => apiKeys.has(key)
8+
9+
function headerAuth(req, res, next) {
10+
if (req.session.data) {
11+
return next()
12+
}
13+
14+
const authenticationHeader = req.get('authorization')
15+
16+
if(!authenticationHeader) {
17+
return next()
18+
}
19+
20+
const apiKey = authenticationHeader
21+
.replace('Bearer', '')
22+
.trim();
23+
24+
if (!isApiKey(apiKey)) {
25+
return next()
26+
}
27+
28+
req.session.data = { username: apiKeyToUser[apiKey] };
29+
30+
next();
31+
}
32+
33+
module.exports = headerAuth;

0 commit comments

Comments
 (0)