Optional response object in authorized(), switch to 'authorized' in /api/health

This commit is contained in:
2023-09-05 14:57:44 -05:00
parent 3d4e82bc45
commit b7d5866fc4
2 changed files with 41 additions and 15 deletions

View File

@@ -1,20 +1,22 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction import { env } from '@/env/server.mjs';
import type { NextApiRequest, NextApiResponse } from "next"; import { authorized } from '@/utils/server';
import { env } from "@/env/server.mjs"; import type { NextApiRequest, NextApiResponse } from 'next';
type ResponseData = { type ResponseData = {
now: number; now: number;
status: string; status: string;
timezone: string; timezone: string;
}; };
export default async function handler( export default async function handler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse<ResponseData> res: NextApiResponse<ResponseData>
) { ) {
res.status(200).json({ const isAuthorized = authorized(req, null);
now: new Date().getTime(),
status: req.query.key == env.API_KEY ? "Authorized" : "Unauthorized", res.status(200).json({
timezone: env.TIMEZONE now: new Date().getTime(),
}); status: isAuthorized ? 'authorized' : 'unauthorized',
timezone: env.TIMEZONE
});
} }

View File

@@ -2,14 +2,38 @@ import { env } from '@/env/server.mjs';
import logger from '@/logger'; import logger from '@/logger';
import { NextApiRequest, NextApiResponse } from 'next'; 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( export function unauthorized(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse | null
): boolean { ): boolean {
if (req.query.key != env.API_KEY) { if (req.query.key != env.API_KEY) {
logger.debug('Unauthorized request'); logger.debug('Unauthorized request');
res.status(401).json({ status: 'unauthorized' }); if (res) res.status(401).json({ status: 'unauthorized' });
return true; return true;
} }
logger.debug('Authorized request');
return false; 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);
}