2017-08-23 20:13:45 +00:00
|
|
|
import query from 'querystring'
|
2020-12-13 14:36:07 +00:00
|
|
|
import { OAuth2Error, ServerError } from './error'
|
2017-08-23 20:13:45 +00:00
|
|
|
|
2020-12-13 14:36:07 +00:00
|
|
|
function dataRes (req, res, code, data) {
|
2017-08-23 20:13:45 +00:00
|
|
|
res.header('Cache-Control', 'no-store')
|
|
|
|
res.header('Pragma', 'no-cache')
|
|
|
|
res.status(code).send(data)
|
|
|
|
console.debug('Response: ', data)
|
|
|
|
}
|
|
|
|
|
|
|
|
function redirect (req, res, redirectUri) {
|
|
|
|
res.header('Location', redirectUri)
|
|
|
|
res.status(302).end()
|
|
|
|
console.debug('Redirecting to ', redirectUri)
|
|
|
|
}
|
|
|
|
|
2020-12-13 14:36:07 +00:00
|
|
|
export function error (req, res, err, redirectUri) {
|
2017-08-23 20:13:45 +00:00
|
|
|
// Transform unknown error
|
2020-12-13 14:36:07 +00:00
|
|
|
if (!(err instanceof OAuth2Error)) {
|
2017-08-23 20:13:45 +00:00
|
|
|
console.error(err.stack)
|
2020-12-13 14:36:07 +00:00
|
|
|
err = new ServerError('Uncaught exception')
|
2017-08-23 20:13:45 +00:00
|
|
|
} else {
|
|
|
|
console.error('Exception caught', err.stack)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (redirectUri) {
|
2020-05-28 18:30:21 +00:00
|
|
|
const obj = {
|
2017-08-23 20:13:45 +00:00
|
|
|
error: err.code,
|
|
|
|
error_description: err.message
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.query.state) {
|
|
|
|
obj.state = req.query.state
|
|
|
|
}
|
|
|
|
|
|
|
|
redirectUri += '?' + query.stringify(obj)
|
|
|
|
redirect(req, res, redirectUri)
|
|
|
|
} else {
|
2020-12-13 14:36:07 +00:00
|
|
|
dataRes(req, res, err.status, { error: err.code, error_description: err.message })
|
2017-08-23 20:13:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-13 14:36:07 +00:00
|
|
|
export function data (req, res, obj, redirectUri, fragment) {
|
2017-08-23 20:13:45 +00:00
|
|
|
if (redirectUri) {
|
2020-06-05 15:18:23 +00:00
|
|
|
if (fragment) {
|
2017-08-23 20:13:45 +00:00
|
|
|
redirectUri += '#'
|
|
|
|
} else {
|
|
|
|
redirectUri += (redirectUri.indexOf('?') === -1 ? '?' : '&')
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.query.state) {
|
|
|
|
obj.state = req.query.state
|
|
|
|
}
|
|
|
|
|
|
|
|
redirectUri += query.stringify(obj)
|
|
|
|
redirect(req, res, redirectUri)
|
|
|
|
} else {
|
2020-12-13 14:36:07 +00:00
|
|
|
dataRes(req, res, 200, obj)
|
2017-08-23 20:13:45 +00:00
|
|
|
}
|
|
|
|
}
|