oauth2-provider/src/utils/response.ts

75 lines
1.9 KiB
TypeScript

import { Request, Response } from 'express';
import { OAuth2Error, ServerError } from '../model/error';
import { OAuth2TokenResponse } from '../model/model';
interface ErrorResponseData {
[x: string]: string | undefined;
error: string;
error_description: string;
state?: string;
}
function dataRes(req: Request, res: Response, code: number, data: any): void {
res.header('Cache-Control', 'no-store');
res.header('Pragma', 'no-cache');
res.status(code).send(data);
console.debug('Response:', data);
}
function redirect(req: Request, res: Response, redirectUri: string): void {
res.header('Location', redirectUri);
res.status(302).end();
console.debug('Redirecting to', redirectUri);
}
export function error(req: Request, res: Response, err: OAuth2Error, redirectUri?: string): void {
// Transform unknown error
if (!(err instanceof OAuth2Error)) {
console.error((err as Error).stack);
err = new ServerError('Uncaught exception');
} else {
console.error('Exception caught', err.stack);
}
if (redirectUri) {
const obj: ErrorResponseData = {
error: err.code,
error_description: err.message
};
if (req.query.state) {
obj.state = req.query.state as string;
}
redirectUri += '?' + (new URLSearchParams(obj as Record<string, string>).toString());
redirect(req, res, redirectUri);
return;
}
dataRes(req, res, err.status, { error: err.code, error_description: err.message });
}
export function data(
req: Request,
res: Response,
obj: OAuth2TokenResponse,
redirectUri?: string,
fragment: boolean = false
): void {
if (redirectUri) {
redirectUri += fragment
? '#'
: (redirectUri.indexOf('?') === -1 ? '?' : '&');
if (req.query.state) {
obj.state = req.query.state as string;
}
redirectUri += new URLSearchParams(obj as Record<string, string>).toString();
redirect(req, res, redirectUri);
return;
}
dataRes(req, res, 200, obj);
}