forked from electerious/Ackee
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisAuthenticated.js
More file actions
59 lines (44 loc) · 1.36 KB
/
isAuthenticated.js
File metadata and controls
59 lines (44 loc) · 1.36 KB
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
'use strict'
const KnownError = require('../utils/KnownError')
const isExpired = require('../utils/isExpired')
const tokens = require('../database/tokens')
const permanentTokens = require('../database/permanentTokens')
const config = require('../utils/config')
module.exports = async (authorization, ttl) => {
// username/password authentication is disabled
if (!config.username && !config.password) {
return true
}
// Token not in request
if (authorization == null) {
return new KnownError('Token missing')
}
const key = authorization.split(' ')[0]
const token = authorization.split(' ')[1]
// Token not in header
if (key !== 'Bearer' || token == null) {
return new KnownError('Token missing')
}
const tokenEntry = await tokens.get(token)
const permanentTokenEntry = await permanentTokens.get(token)
if (tokenEntry != null) {
// Tokens can expire
const valid = isExpired(tokenEntry.updated, ttl) === false
// Token too old
if (valid === false) {
return new KnownError('Token invalid')
}
// Update token to ensure that the token stays valid
await tokens.update(token)
return true
}
if (permanentTokenEntry != null) {
// Update token to indicate the last time it was used
await permanentTokens.update(token, {
title: permanentTokenEntry.title
})
return true
}
// Token not in database
return new KnownError('Token invalid')
}