forked from CVCEeu-dh/histograph
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.js
168 lines (145 loc) · 4.54 KB
/
auth.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
const jwt = require('express-jwt')
const jwtAuthz = require('express-jwt-authz')
const jwksRsa = require('jwks-rsa')
const createError = require('http-errors')
const request = require('request')
const decypher = require('decypher')
const { isString, get } = require('lodash')
const { executeQuery } = require('./lib/util/neo4j')
const { generateApiKey } = require('./lib/util/crypto')
const { generateUuid } = require('./lib/util/text')
const userQueries = decypher('./queries/user.cyp')
const AnonymousUser = Object.freeze({
is_authentified: true,
firstname: 'User',
lastname: 'Anonymous',
email: '[email protected]',
username: 'anonymous',
id: 'anon',
picture: '',
apiKey: 'apikey'
})
/**
* Authentication middleware. When used, the
* Access Token must exist and be verified against
* the Auth0 JSON Web Key Set
*/
const checkJwt = jwt({
// Dynamically provide a signing key
// based on the kid in the header and
// the signing keys provided by the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: 'https://c2dh.eu.auth0.com/.well-known/jwks.json'
}),
// Validate the audience and the issuer.
audience: 'c2dh-histograph',
issuer: 'https://c2dh.eu.auth0.com/',
algorithms: ['RS256']
})
const readOnly = jwtAuthz(['read:data'])
const AuthHeaderTokenRegex = /^Bearer\s+(.*)$/i
function getBearerToken(req) {
return get(get(req.headers, 'authorization', '').match(AuthHeaderTokenRegex), 1)
}
async function fetchUserProfile(profileUrl, jwtToken) {
return new Promise((res, rej) => {
request.get(profileUrl, { auth: { bearer: jwtToken }, json: true }, (err, response, body) => {
if (err) return rej(err)
if (response.statusCode !== 200) return rej(createError(response.statusCode, body))
return res(body)
})
})
}
function auth0UserProfileAsHistographUser(userProfile) {
return {
uuid: generateUuid(),
status: 'enabled',
username: userProfile.name,
authId: userProfile.sub,
picture: userProfile.picture,
apiKey: generateApiKey()
}
}
function presentHistographUser(user) {
return {
is_authentified: true,
firstname: user.props.firstname,
lastname: user.props.lastname,
email: user.props.email,
username: user.username,
id: user.id,
picture: user.props.picture,
apiKey: user.props.apiKey
}
}
async function getUserFromDbByApiKey(apiKey) {
const result = await executeQuery(userQueries.get_by_api_key, { apiKey })
return result[0]
}
async function getUserFromDb(authId) {
const result = await executeQuery(userQueries.get_by_auth_id, { id: authId })
return result[0]
}
async function saveUserInDb(user) {
const result = await executeQuery(userQueries.save_user_by_auth_id, user)
return result[0]
}
async function fetchAndSaveUser(profileUrl, jwtToken) {
const userProfile = await fetchUserProfile(profileUrl, jwtToken)
const user = auth0UserProfileAsHistographUser(userProfile)
return saveUserInDb(user)
}
function getUserProfile(req, res, next) {
const jwtData = req.user
const profileUrl = get(jwtData, 'aud.1')
const userId = get(jwtData, 'sub')
const jwtToken = getBearerToken(req)
if (!isString(profileUrl) || !isString(userId)) {
throw createError(404, `JWT Token malformed or not present. Could not find Profile URL (${profileUrl}) and/or User ID (${userId}).`)
}
getUserFromDb(userId)
.then(user => {
if (!user) return fetchAndSaveUser(profileUrl, jwtToken)
return user
})
.then(user => {
req.user = presentHistographUser(user)
next()
})
.catch(next)
}
function getAnonymousUserProfile(req, res, next) {
req.user = AnonymousUser
next()
}
/**
* Middleware for authenticating user with an API Key.
* API Key can be provided as a bearer token or
* a query parameter (overrides token).
* @param {Request} req request
* @param {Response} res response
* @param {function} next callback
*/
function apiKeyAuthMiddleware(req, res, next) {
const { apiKey: apiKeyQueryParameterValue } = req.query
const apiKeyHeaderValue = getBearerToken(req)
const apiKey = apiKeyQueryParameterValue || apiKeyHeaderValue
if (!isString(apiKey)) return next(createError(403, 'No API Key Provided ("apiKey")'))
return getUserFromDbByApiKey(apiKey)
.then(user => {
if (!user) return next(createError(403, 'Invalid API Key'))
req.user = presentHistographUser(user)
return next()
})
.catch(next)
}
module.exports = {
apiKeyAuthMiddleware,
checkJwt,
readOnly,
getUserProfile,
getAnonymousUserProfile
}