This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
IcyNet.eu/server/api/oauth2/response.js

61 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-08-23 20:13:45 +00:00
import query from 'querystring'
import { OAuth2Error, ServerError } from './error'
2017-08-23 20:13:45 +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)
}
export function error (req, res, err, redirectUri) {
2017-08-23 20:13:45 +00:00
// Transform unknown error
if (!(err instanceof OAuth2Error)) {
2017-08-23 20:13:45 +00:00
console.error(err.stack)
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 {
dataRes(req, res, err.status, { error: err.code, error_description: err.message })
2017-08-23 20:13:45 +00:00
}
}
export function data (req, res, obj, redirectUri, fragment) {
2017-08-23 20:13:45 +00:00
if (redirectUri) {
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 {
dataRes(req, res, 200, obj)
2017-08-23 20:13:45 +00:00
}
}