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

import query from 'querystring'
import { OAuth2Error, ServerError } from './error'
function dataRes (req, res, code, data) {
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) {
// Transform unknown error
if (!(err instanceof OAuth2Error)) {
console.error(err.stack)
err = new ServerError('Uncaught exception')
} else {
console.error('Exception caught', err.stack)
}
if (redirectUri) {
const obj = {
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 })
}
}
export function data (req, res, obj, redirectUri, fragment) {
if (redirectUri) {
if (fragment) {
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)
}
}