refactor(lst): refactored to be back to npm from bun
This commit is contained in:
@@ -1,62 +0,0 @@
|
||||
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
|
||||
import {serveStatic} from "hono/bun";
|
||||
import {logger} from "hono/logger";
|
||||
import {cors} from "hono/cors";
|
||||
import {OpenAPIHono} from "@hono/zod-openapi";
|
||||
|
||||
//routes
|
||||
import auth from "./services/auth/authService";
|
||||
import scalar from "./services/general/route/scalar";
|
||||
import apiHits from "./services/general/route/apitHits";
|
||||
import system from "./services/system/systemServer";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
app.use("*", logger());
|
||||
|
||||
const allowedOrigins = ["http://localhost:3000", "http://localhost:4000", "http://localhost:5173"];
|
||||
|
||||
app.use(
|
||||
"*",
|
||||
cors({
|
||||
origin: allowedOrigins,
|
||||
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
|
||||
allowMethods: ["POST", "GET", "OPTIONS"],
|
||||
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
|
||||
maxAge: 600,
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
|
||||
app.doc("/api", {
|
||||
openapi: "3.0.0",
|
||||
info: {
|
||||
version: "1.0.0",
|
||||
title: "LST API",
|
||||
},
|
||||
});
|
||||
|
||||
// as we dont want to change ocme again well use a proxy to this
|
||||
// app.all("/ocme/*", async (c) => {
|
||||
// return ocmeService(c);
|
||||
// });
|
||||
|
||||
const routes = [scalar, auth, apiHits, system] as const;
|
||||
|
||||
routes.forEach((route) => {
|
||||
app.route("/api/", route);
|
||||
});
|
||||
|
||||
//app.basePath("/api/auth").route("/login", login).route("/session", session).route("/register", register);
|
||||
|
||||
//auth stuff
|
||||
// app.get("/api/protected", authMiddleware, (c) => {
|
||||
// return c.json({success: true, message: "is authenticated"});
|
||||
// });
|
||||
|
||||
app.get("*", serveStatic({root: "./frontend/dist"}));
|
||||
app.get("*", serveStatic({path: "./frontend/dist/index.html"}));
|
||||
|
||||
export default app;
|
||||
|
||||
//export type ApiRoute = typeof apiRoute;
|
||||
26
server/src/globalUtils/apiHits.d.ts
vendored
Normal file
26
server/src/globalUtils/apiHits.d.ts
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { Context } from "hono";
|
||||
import { z } from "zod";
|
||||
declare const requestSchema: z.ZodObject<{
|
||||
ip: z.ZodOptional<z.ZodString>;
|
||||
endpoint: z.ZodString;
|
||||
action: z.ZodOptional<z.ZodString>;
|
||||
stats: z.ZodOptional<z.ZodString>;
|
||||
}, "strip", z.ZodTypeAny, {
|
||||
ip?: string;
|
||||
endpoint?: string;
|
||||
action?: string;
|
||||
stats?: string;
|
||||
}, {
|
||||
ip?: string;
|
||||
endpoint?: string;
|
||||
action?: string;
|
||||
stats?: string;
|
||||
}>;
|
||||
type ApiHitData = z.infer<typeof requestSchema>;
|
||||
export declare const apiHit: (c: Context, data: unknown) => Promise<{
|
||||
success: boolean;
|
||||
data?: ApiHitData;
|
||||
errors?: any[];
|
||||
}>;
|
||||
export {};
|
||||
//# sourceMappingURL=apiHits.d.ts.map
|
||||
1
server/src/globalUtils/apiHits.d.ts.map
Normal file
1
server/src/globalUtils/apiHits.d.ts.map
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"apiHits.d.ts","sourceRoot":"","sources":["apiHits.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,MAAM,CAAC;AAClC,OAAO,EAAC,CAAC,EAAW,MAAM,KAAK,CAAC;AAGhC,QAAA,MAAM,aAAa;;;;;;;;;;;;;;;EAKjB,CAAC;AAEH,KAAK,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAEhD,eAAO,MAAM,MAAM,MACZ,OAAO,QACJ,OAAO,KACd,OAAO,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,UAAU,CAAC;IAAC,MAAM,CAAC,EAAE,GAAG,EAAE,CAAA;CAAC,CAuB/D,CAAC"}
|
||||
20
server/src/globalUtils/apiHits.js
Normal file
20
server/src/globalUtils/apiHits.js
Normal file
@@ -0,0 +1,20 @@
|
||||
import { z, ZodError } from "zod";
|
||||
const requestSchema = z.object({
|
||||
ip: z.string().optional(),
|
||||
endpoint: z.string(),
|
||||
action: z.string().optional(),
|
||||
stats: z.string().optional(),
|
||||
});
|
||||
export const apiHit = async (c, data) => {
|
||||
try {
|
||||
const forwarded = c.req.header("host");
|
||||
const validatedData = requestSchema.parse(data);
|
||||
return { success: true, data: validatedData };
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
return { success: false, errors: error.errors };
|
||||
}
|
||||
return { success: false, errors: [{ message: "An unknown error occurred" }] };
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {Context} from "hono";
|
||||
import {z, ZodError} from "zod";
|
||||
import {Context} from "hono";
|
||||
|
||||
// Define the request body schema
|
||||
const requestSchema = z.object({
|
||||
ip: z.string().optional(),
|
||||
71
server/src/index.ts
Normal file
71
server/src/index.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import {serve} from "@hono/node-server";
|
||||
import {OpenAPIHono} from "@hono/zod-openapi";
|
||||
import {serveStatic} from "@hono/node-server/serve-static";
|
||||
import {logger} from "hono/logger";
|
||||
import {cors} from "hono/cors";
|
||||
|
||||
import {db} from "../../database/dbclient.js";
|
||||
import {modules} from "../../database/schema/modules.js";
|
||||
|
||||
// custom routes
|
||||
import scalar from "./services/general/route/scalar.js";
|
||||
import system from "./services/server/systemServer.js";
|
||||
import auth from "./services/auth/authService.js";
|
||||
|
||||
const allowedOrigins = ["http://localhost:3000", "http://localhost:4000", "http://localhost:5173"];
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
// middle ware
|
||||
app.use("*", logger());
|
||||
app.use(
|
||||
"*",
|
||||
cors({
|
||||
origin: allowedOrigins,
|
||||
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
|
||||
allowMethods: ["POST", "GET", "OPTIONS"],
|
||||
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
|
||||
maxAge: 600,
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
|
||||
app.doc("/api/ref", {
|
||||
openapi: "3.0.0",
|
||||
info: {
|
||||
version: "1.0.0",
|
||||
title: "LST API",
|
||||
},
|
||||
});
|
||||
|
||||
const routes = [
|
||||
scalar,
|
||||
auth,
|
||||
// apiHits,
|
||||
system,
|
||||
] as const;
|
||||
|
||||
routes.forEach((route) => {
|
||||
app.route("/api/", route);
|
||||
});
|
||||
|
||||
// the catch all api route
|
||||
app.all("/api/*", (c) => c.json({error: "API route not found"}, 404));
|
||||
|
||||
app.all("/ocme/*", async (c) => {
|
||||
//return ocmeService(c);
|
||||
c.json({error: "Ocme route not found"}, 404);
|
||||
});
|
||||
|
||||
// front end static files
|
||||
app.get("*", serveStatic({root: "../frontend/dist"}));
|
||||
app.get("*", serveStatic({path: "../frontend/dist/index.html"}));
|
||||
|
||||
serve(
|
||||
{
|
||||
fetch: app.fetch,
|
||||
port: Number(process.env.SERVER_PORT),
|
||||
},
|
||||
(info) => {
|
||||
console.log(`Server is running on http://localhost:${info.port}`);
|
||||
}
|
||||
);
|
||||
@@ -1,8 +1,8 @@
|
||||
import {OpenAPIHono} from "@hono/zod-openapi";
|
||||
|
||||
import login from "./routes/login";
|
||||
import register from "./routes/register";
|
||||
import session from "./routes/session";
|
||||
import login from "./routes/login.js";
|
||||
import register from "./routes/register.js";
|
||||
import session from "./routes/session.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
app.route("auth/login", login);
|
||||
|
||||
@@ -4,8 +4,8 @@ in the login route we attach it to user under roles.
|
||||
*/
|
||||
|
||||
import {eq} from "drizzle-orm";
|
||||
import {db} from "../../../../database/dbClient";
|
||||
import {userRoles} from "../../../../database/schema/userRoles";
|
||||
import {db} from "../../../../../database/dbclient.js";
|
||||
import {userRoles} from "../../../../../database/schema/userRoles.js";
|
||||
|
||||
export const roleCheck = async (user_id: any) => {
|
||||
// get the user roles by the user_id
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import {sign, verify} from "jsonwebtoken";
|
||||
import {db} from "../../../../database/dbClient";
|
||||
import {users} from "../../../../database/schema/users";
|
||||
import {eq} from "drizzle-orm";
|
||||
import {checkPassword} from "../utils/checkPassword";
|
||||
import {roleCheck} from "./getUserAccess";
|
||||
import jwt from "jsonwebtoken";
|
||||
import {db} from "../../../../../database/dbclient.js";
|
||||
import {users} from "../../../../../database/schema/users.js";
|
||||
import {eq, sql} from "drizzle-orm";
|
||||
import {checkPassword} from "../utils/checkPassword.js";
|
||||
import {roleCheck} from "./getUserAccess.js";
|
||||
|
||||
/**
|
||||
* Authenticate a user and return a JWT.
|
||||
*/
|
||||
const {sign, verify} = jwt;
|
||||
|
||||
export async function login(
|
||||
username: string,
|
||||
@@ -15,7 +16,7 @@ export async function login(
|
||||
): Promise<{token: string; user: {user_id: string; username: string}}> {
|
||||
const user = await db.select().from(users).where(eq(users.username, username));
|
||||
|
||||
console.log(user);
|
||||
//console.log(user);
|
||||
if (user.length === 0) {
|
||||
throw new Error("Invalid or Missing user");
|
||||
}
|
||||
@@ -27,7 +28,7 @@ export async function login(
|
||||
}
|
||||
|
||||
// Create a JWT
|
||||
const secret: string = process.env.JWT_SECRET! || "bnghsjhsd";
|
||||
const secret: string = process.env.JWT_SECRET!;
|
||||
const expiresIn = Number(process.env.JWT_EXPIRES!) || 60;
|
||||
|
||||
// get the user roles
|
||||
@@ -39,6 +40,15 @@ export async function login(
|
||||
roles: roles || null,
|
||||
role: user[0].role || null, // this should be removed onces full migration to v2 is completed
|
||||
};
|
||||
|
||||
// update the user last login
|
||||
// try {
|
||||
// db.update(users)
|
||||
// .set({lastLogin: sql`NOW()`})
|
||||
// .where(eq(users.user_id, user[0].user_id));
|
||||
// } catch (e) {
|
||||
// console.log(e);
|
||||
// }
|
||||
const token = sign({user: userData}, secret, {expiresIn: expiresIn * 60});
|
||||
|
||||
return {token, user: userData};
|
||||
|
||||
@@ -11,7 +11,7 @@ export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
||||
const token = authHeader.split(" ")[1];
|
||||
|
||||
try {
|
||||
const decoded = verify(token, process.env.JWT_SECRET, {ignoreExpiration: false}) as {
|
||||
const decoded = verify(token, process.env.JWT_SECRET!, {ignoreExpiration: false}) as {
|
||||
userId: number;
|
||||
exp: number;
|
||||
};
|
||||
@@ -22,8 +22,10 @@ export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
||||
// If the token has less than REFRESH_THRESHOLD seconds left, refresh it
|
||||
let newToken = null;
|
||||
|
||||
if (timeLeft < parseInt(process.env.REFRESH_THRESHOLD)) {
|
||||
newToken = sign({userId: decoded.userId}, process.env.JWT_SECRET, {expiresIn: process.env.EXPIRATION_TIME});
|
||||
if (timeLeft < parseInt(process.env.REFRESH_THRESHOLD!)) {
|
||||
newToken = sign({userId: decoded.userId}, process.env.JWT_SECRET!, {
|
||||
expiresIn: parseInt(process.env.EXPIRATION_TIME!),
|
||||
});
|
||||
c.res.headers.set("Authorization", `Bearer ${newToken}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
|
||||
import {login} from "../controllers/login";
|
||||
import {login} from "../controllers/login.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
|
||||
import {db} from "../../../../database/dbClient";
|
||||
import {users} from "../../../../database/schema/users";
|
||||
import {apiHit} from "../../../globalUtils/apitHits";
|
||||
import {createPassword} from "../utils/createPassword";
|
||||
import {db} from "../../../../../database/dbclient.js";
|
||||
import {users} from "../../../../../database/schema/users.js";
|
||||
import {apiHit} from "../../../globalUtils/apiHits.js";
|
||||
import {createPassword} from "../utils/createPassword.js";
|
||||
import {eq} from "drizzle-orm";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import {OpenAPIHono} from "@hono/zod-openapi";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
// the doc endpoint
|
||||
app.doc("/", {
|
||||
openapi: "3.0.0",
|
||||
info: {
|
||||
version: "1.0.0",
|
||||
title: "LST API",
|
||||
},
|
||||
});
|
||||
|
||||
export default app;
|
||||
@@ -1,5 +1,4 @@
|
||||
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
|
||||
import {apiHit} from "../../../globalUtils/apitHits";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
@@ -47,7 +47,7 @@ app.get(
|
||||
"undici",
|
||||
],
|
||||
spec: {
|
||||
url: "/api",
|
||||
url: "/api/ref",
|
||||
},
|
||||
baseServerURL: "https://scalar.com",
|
||||
servers: [
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Context } from "hono";
|
||||
export const ocmeService = async (c: Context) => {
|
||||
const url = new URL(c.req.url);
|
||||
|
||||
const ocmeUrl = `http://localhost:${
|
||||
process.env.OCME_PORT
|
||||
}${url.pathname.replace("/ocme", "")}`;
|
||||
|
||||
console.log(ocmeUrl);
|
||||
const ocmeResponse = await fetch(ocmeUrl, {
|
||||
method: c.req.method,
|
||||
headers: c.req.raw.headers,
|
||||
body:
|
||||
c.req.method !== "GET" && c.req.method !== "HEAD"
|
||||
? await c.req.text()
|
||||
: undefined,
|
||||
});
|
||||
|
||||
return new Response(ocmeResponse.body, {
|
||||
status: ocmeResponse.status,
|
||||
headers: ocmeResponse.headers,
|
||||
});
|
||||
};
|
||||
19
server/src/services/ocme/ocmeService.ts
Normal file
19
server/src/services/ocme/ocmeService.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type {Context} from "hono";
|
||||
|
||||
export const ocmeService = async (c: Context) => {
|
||||
const url = new URL(c.req.url);
|
||||
|
||||
const ocmeUrl = `http://localhost:${process.env.OCME_PORT}${url.pathname.replace("/ocme", "")}`;
|
||||
|
||||
console.log(ocmeUrl);
|
||||
const ocmeResponse = await fetch(ocmeUrl, {
|
||||
method: c.req.method,
|
||||
headers: c.req.raw.headers,
|
||||
body: c.req.method !== "GET" && c.req.method !== "HEAD" ? await c.req.text() : undefined,
|
||||
});
|
||||
|
||||
return new Response(ocmeResponse.body, {
|
||||
status: ocmeResponse.status,
|
||||
headers: ocmeResponse.headers,
|
||||
});
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
|
||||
import {modules} from "../../../../database/schema/modules";
|
||||
import {db} from "../../../../database/dbClient";
|
||||
import {modules} from "../../../../../database/schema/modules.js";
|
||||
import {db} from "../../../../../database/dbclient.js";
|
||||
import {eq} from "drizzle-orm";
|
||||
|
||||
// Define the request body schema
|
||||
@@ -27,7 +27,7 @@ app.openapi(
|
||||
tags: ["server"],
|
||||
summary: "Returns all modules in the server",
|
||||
method: "get",
|
||||
path: "/server/modules",
|
||||
path: "/",
|
||||
responses: {
|
||||
200: {
|
||||
content: {
|
||||
@@ -38,6 +38,7 @@ app.openapi(
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
//console.log("system modules");
|
||||
let module: any = [];
|
||||
try {
|
||||
module = await db.select().from(modules).where(eq(modules.active, true));
|
||||
7
server/src/services/server/systemServer.ts
Normal file
7
server/src/services/server/systemServer.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import {OpenAPIHono} from "@hono/zod-openapi";
|
||||
|
||||
import modules from "./route/modules.js";
|
||||
|
||||
const app = new OpenAPIHono().route("server/modules", modules);
|
||||
|
||||
export default app;
|
||||
@@ -1,7 +0,0 @@
|
||||
import {OpenAPIHono} from "@hono/zod-openapi";
|
||||
|
||||
import modules from "./route/modules";
|
||||
|
||||
const app = new OpenAPIHono().route("system/module", modules);
|
||||
|
||||
export default app;
|
||||
Reference in New Issue
Block a user