diff --git a/src/pages/api/health.ts b/src/pages/api/health.ts index cb1cd2b..d308aa4 100644 --- a/src/pages/api/health.ts +++ b/src/pages/api/health.ts @@ -1,20 +1,22 @@ -// Next.js API route support: https://nextjs.org/docs/api-routes/introduction -import type { NextApiRequest, NextApiResponse } from "next"; -import { env } from "@/env/server.mjs"; +import { env } from '@/env/server.mjs'; +import { authorized } from '@/utils/server'; +import type { NextApiRequest, NextApiResponse } from 'next'; type ResponseData = { - now: number; - status: string; - timezone: string; + now: number; + status: string; + timezone: string; }; export default async function handler( - req: NextApiRequest, - res: NextApiResponse + req: NextApiRequest, + res: NextApiResponse ) { - res.status(200).json({ - now: new Date().getTime(), - status: req.query.key == env.API_KEY ? "Authorized" : "Unauthorized", - timezone: env.TIMEZONE - }); + const isAuthorized = authorized(req, null); + + res.status(200).json({ + now: new Date().getTime(), + status: isAuthorized ? 'authorized' : 'unauthorized', + timezone: env.TIMEZONE + }); } diff --git a/src/utils/server.ts b/src/utils/server.ts index 4aaafcc..3ea47b4 100644 --- a/src/utils/server.ts +++ b/src/utils/server.ts @@ -2,14 +2,38 @@ import { env } from '@/env/server.mjs'; import logger from '@/logger'; import { NextApiRequest, NextApiResponse } from 'next'; +/** + * Check if the request is authorized. If response is provided, send a 401 response if unauthorized. + + * @param req The request object to check. + * @param res Optional response object to send a 401 response if unauthorized. + * @returns A boolean indicating if the request is authorized. + */ export function unauthorized( req: NextApiRequest, - res: NextApiResponse + res: NextApiResponse | null ): boolean { if (req.query.key != env.API_KEY) { logger.debug('Unauthorized request'); - res.status(401).json({ status: 'unauthorized' }); + if (res) res.status(401).json({ status: 'unauthorized' }); return true; } + logger.debug('Authorized request'); return false; +} + +/** + * Check if the request is authorized. + * Performs identically to `unauthorized`, but returns the opposite value. + * + * @param req The request object to check. + * @param res Optional response object to send a 401 response if unauthorized. + * @returns A boolean indicating if the request is authorized. + * @see unauthorized + */ +export function authorized( + req: NextApiRequest, + res: NextApiResponse | null +): boolean { + return !unauthorized(req, res); } \ No newline at end of file