mirror of
https://github.com/Xevion/bus-reminder.git
synced 2025-12-07 09:14:35 -06:00
Optional response object in authorized(), switch to 'authorized' in /api/health
This commit is contained in:
@@ -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
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user