Skip to content

Commit

Permalink
Add a middleware, refactors outline.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
koechkevin committed Sep 9, 2024
1 parent 0761993 commit f850c30
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 39 deletions.
2 changes: 1 addition & 1 deletion apps/codeforafrica/next-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.
File renamed without changes.
3 changes: 0 additions & 3 deletions apps/vpnmanager/src/lib/outline/index.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { NextApiRequest } from "next/types";
import { OutlineVPN } from "./outline";
import { Filters, Model, Record } from "@/vpnmanager/lib/data/database";

Expand All @@ -16,17 +17,22 @@ function calculateDailyDataUsage(userData: UserDataUsage) {
}

const { usage, outlineId } = userData;
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);

const lastWeek = new Date();
lastWeek.setDate(yesterday.getDate() - 7);
const [res] = Model.getAll({
orderBy: "date DESC",
date: {
start: `${lastWeek.getFullYear()}-${lastWeek.getMonth() + 1}-${lastWeek.getDate()}`,
end: `${yesterday.getFullYear()}-${yesterday.getMonth() + 1}-${yesterday.getDate()}`,
},
userId: outlineId?.toString(),
}) as Record[];
return usage - (res?.cumulativeData || 0);
}

function addUserStatsToDb(record: Omit<Record, "ID">) {
Model.createOrUpdate(record);
}
// Process Daily user stats. Doesn't matter the time of the day, it just updates.
export async function processUserStats() {
const date = `${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()}`;
const { bytesTransferredByUserId = {} } = await vpnManager.getDataUsage();
Expand All @@ -45,15 +51,17 @@ export async function processUserStats() {
cumulativeData: bytesTransferredByUserId[key],
email: userDetails?.name || "",
};
addUserStatsToDb({ ...newData, createdAt: new Date().toISOString() });
Model.createOrUpdate({ ...newData, createdAt: new Date().toISOString() });
return newData;
});
return unprocessedUsers;
}

export async function getStats(
filters: Partial<Filters> & { "date.start"?: string; "date.end"?: string },
) {
export async function getStats(req: NextApiRequest) {
const filters: Partial<Filters> & {
"date.start"?: string;
"date.end"?: string;
} = req.query;
const validFilters = {
email: filters.email,
ID: filters.ID,
Expand Down
17 changes: 17 additions & 0 deletions apps/vpnmanager/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { NextRequest } from "next/server";

// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: "/api/:function*",
};

export function middleware(req: NextRequest) {
const key: string = req.headers.get("x-api-key") as string;
const API_SECRET_KEY = process.env.API_SECRET_KEY;
if (!(key && key === API_SECRET_KEY)) {
return Response.json(
{ success: false, message: "INVALID_API_KEY" },
{ status: 403 },
);
}
}
9 changes: 3 additions & 6 deletions apps/vpnmanager/src/pages/api/processGsheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@ import { processNewUsers } from "@/vpnmanager/lib/processUsers";

export async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const key: string = req.headers["x-api-key"] as string;
const API_SECRET_KEY = process.env.API_SECRET_KEY;
if (!(key && key === API_SECRET_KEY)) {
return res.status(403).json({ message: "INVALID_API_KEY" });
}
processNewUsers();
return res.status(200).json({ message: "Process Started" });
} catch (error) {}
} catch (error) {
return res.status(500).json(error);
}
}
export default handler;
22 changes: 22 additions & 0 deletions apps/vpnmanager/src/pages/api/statistics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextApiResponse, NextApiRequest } from "next";
import { processUserStats, getStats } from "@/vpnmanager/lib/statistics";
import { RestMethodFunctions, RestMethods } from "@/vpnmanager/types";

const methodToFunction: RestMethodFunctions = {
POST: processUserStats,
GET: getStats,
};

export async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const statFunc = methodToFunction[req.method as RestMethods];
if (!statFunc) {
return res.status(404).json({ message: "Requested path not found" });
}
const data = await statFunc(req);
return res.status(200).json(data);
} catch (error) {
return res.status(500).json(error);
}
}
export default handler;
21 changes: 0 additions & 21 deletions apps/vpnmanager/src/pages/api/userStatistics.ts

This file was deleted.

8 changes: 8 additions & 0 deletions apps/vpnmanager/src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { NextApiRequest } from "next";

export interface OutlineOptions {
apiUrl: string;
fingerprint?: string;
Expand Down Expand Up @@ -39,3 +41,9 @@ export interface SheetRow {
endDate: string;
keySent: "Yes" | "No";
}

export type RestMethods = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";

export type RestMethodFunctions = {
[K in RestMethods]?: (req: NextApiRequest) => Promise<any>;
};

0 comments on commit f850c30

Please sign in to comment.