export function buildApp()

in src/app.ts [102:232]


export function buildApp(
	getPanda: () => PanDomainAuthentication = getPanDomainAuth,
): Express {
	const app = express();

	app.use(
		cors({
			origin: /\.(dev-)?gutools.co.uk$/,
			credentials: true,
		}),
	);

	app.use(jsonBodyParser());

	const uiHandler = (req: express.Request, res: express.Response) => {
		withPandaAuth(
			getPanda,
			req,
			res,
			async () => {
				const panAuthResult = await getPanda().verify(
					getCookieString(req),
				);
				res.contentType('html').send(getUI(panAuthResult));
			},
			() => {
				res.status(403).contentType('html').send(getLoginResponse(req));
			},
		);
	};

	app.get('/', uiHandler);

	app.post(
		'/signed-image-url',
		(req: express.Request, res: express.Response) =>
			withPandaAuth(
				getPanda,
				req,
				res,
				() => {
					handleImageSigning(
						req.body as SignedImageUrlConfig | undefined,
						getPanda,
						req,
						res,
					);
				},
				() => {
					res.status(403).send({
						error: 'Not authorised by pan-domain login',
					});
				},
			),
	);

	app.get(
		'/signed-image-url',
		(req: express.Request, res: express.Response) =>
			withPandaAuth(
				getPanda,
				req,
				res,
				() => {
					const config: SignedImageUrlConfig = {
						url: req.query.url as string,
						profile: {
							width: DEFAULT_WIDTH,
						},
					};
					// The typeof checks below are because of the way express
					// handles multiple query parameters of the same name. I
					// don't think we need to handle this, so if it's not a
					// string, ignore it.
					if (
						config.profile &&
						req.query.width &&
						typeof req.query.width === 'string'
					) {
						config.profile.width = Number.parseInt(req.query.width);
					}
					if (
						config.profile &&
						req.query.height &&
						req.query.height === 'string'
					) {
						config.profile.height = Number.parseInt(
							req.query.height,
						);
					}
					if (
						config.profile &&
						req.query.quality &&
						req.query.quality === 'string'
					) {
						config.profile.quality = Number.parseInt(
							req.query.quality,
						);
					}
					handleImageSigning(config, getPanda, req, res);
				},
				() => {
					res.status(403).send({
						error: 'Not authorised by pan-domain login',
					});
				},
			),
	);

	app.get('/userdetails', (req: express.Request, res: express.Response) =>
		withPandaAuth(
			getPanda,
			req,
			res,
			(authResult) => {
				res.send(authResult);
			},
			() => {
				res.status(403).send({
					error: 'Not authorised by pan-domain login',
				});
			},
		),
	);

	app.get('/healthcheck', (req: express.Request, res: express.Response) => {
		res.status(200).json({ status: 'OK', stage: getStage() });
	});

	return app;
}