2020-12-13 14:36:07 +00:00
|
|
|
import { AccessDenied, Forbidden } from './error'
|
2020-06-05 15:18:23 +00:00
|
|
|
import wrap from './wrap'
|
2017-08-23 20:13:45 +00:00
|
|
|
|
2020-12-13 14:36:07 +00:00
|
|
|
export const middleware = wrap(async function (req, res, next) {
|
2017-08-23 20:13:45 +00:00
|
|
|
console.debug('Parsing bearer token')
|
|
|
|
let token = null
|
|
|
|
|
|
|
|
// Look for token in header
|
|
|
|
if (req.headers.authorization) {
|
|
|
|
const pieces = req.headers.authorization.split(' ', 2)
|
|
|
|
|
|
|
|
// Check authorization header
|
|
|
|
if (!pieces || pieces.length !== 2) {
|
2020-12-13 14:36:07 +00:00
|
|
|
throw new AccessDenied('Wrong authorization header')
|
2017-08-23 20:13:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Only bearer auth is supported
|
|
|
|
if (pieces[0].toLowerCase() !== 'bearer') {
|
2020-12-13 14:36:07 +00:00
|
|
|
throw new AccessDenied('Unsupported authorization method in header')
|
2017-08-23 20:13:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
token = pieces[1]
|
|
|
|
console.debug('Bearer token parsed from authorization header:', token)
|
2020-05-28 18:30:21 +00:00
|
|
|
} else if (req.query && req.query.access_token) {
|
|
|
|
token = req.query.access_token
|
2017-08-23 20:13:45 +00:00
|
|
|
console.debug('Bearer token parsed from query params:', token)
|
2020-05-28 18:30:21 +00:00
|
|
|
} else if (req.body && req.body.access_token) {
|
|
|
|
token = req.body.access_token
|
2017-08-23 20:13:45 +00:00
|
|
|
console.debug('Bearer token parsed from body params:', token)
|
|
|
|
} else {
|
2020-12-13 14:36:07 +00:00
|
|
|
throw new AccessDenied('Bearer token not found')
|
2017-08-23 20:13:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Try to fetch access token
|
2020-05-28 18:30:21 +00:00
|
|
|
const object = await req.oauth2.model.accessToken.fetchByToken(token)
|
2017-08-23 20:13:45 +00:00
|
|
|
if (!object) {
|
2020-12-13 14:36:07 +00:00
|
|
|
throw new Forbidden('Token not found or has expired')
|
2017-08-23 20:13:45 +00:00
|
|
|
} else if (!req.oauth2.model.accessToken.checkTTL(object)) {
|
2020-12-13 14:36:07 +00:00
|
|
|
throw new Forbidden('Token is expired')
|
2017-08-23 20:13:45 +00:00
|
|
|
} else {
|
|
|
|
req.oauth2.accessToken = object
|
|
|
|
console.debug('AccessToken fetched', object)
|
|
|
|
next()
|
|
|
|
}
|
|
|
|
})
|