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 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<ResponseData>
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
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
});
}

View File

@@ -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);
}