refactor(all): refactoring to remove monorepo taking to long to get it wokring as intended

This commit is contained in:
2025-02-19 10:06:43 -06:00
parent 5f7a3dd182
commit b15f1d8ae8
28 changed files with 736 additions and 112 deletions

View File

@@ -9,5 +9,8 @@
},
"devDependencies": {
"typescript": "^5.7.3"
},
"dependencies": {
"@scalar/hono-api-reference": "^0.5.174"
}
}

View File

@@ -1,15 +1,16 @@
import {Hono} from "hono";
import {serveStatic} from "hono/bun";
import {logger} from "hono/logger";
import {ocmeService} from "./services/ocmeServer";
import {authMiddleware} from "lst-auth";
import {cors} from "hono/cors";
import {OpenAPIHono} from "@hono/zod-openapi";
//import { expensesRoute } from "./routes/expenses";
import login from "./route/auth/login";
import session from "./route/auth/session";
//routes
import auth from "./services/auth/authService";
import scalar from "./route/scalar";
// services
import {ocmeService} from "./services/ocme/ocmeServer";
const app = new Hono();
const app = new OpenAPIHono();
app.use("*", logger());
app.use(
@@ -24,24 +25,32 @@ app.use(
})
);
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);
});
app.basePath("/api/auth").route("/login", login).route("/session", session);
const routes = [scalar, auth] as const;
routes.forEach((route) => {
app.route("/", 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("/api/test", (c) => {
return c.json({success: true, message: "hello from bun"});
});
// const authRoute = app.basePath("/api/auth").route("*", )
//const apiRoute = app.basePath("/api").route("/expenses", expensesRoute);
app.get("*", serveStatic({root: "../frontend/dist"}));
app.get("*", serveStatic({path: "../frontend/dist/index.html"}));

View File

@@ -1,54 +0,0 @@
import { Context } from "hono";
import { authHandler, initAuthConfig, verifyAuth } from "@hono/auth-js";
import Credentials from "@auth/core/providers/credentials";
import { AuthConfig } from "@auth/core/types";
export const authConfig: AuthConfig = {
secret: process.env.AUTH_SECRET,
providers: [
Credentials({
name: "Credentials",
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
// Add your authentication logic here
const user = { id: "1", name: "John Doe", email: "john@example.com" };
if (
credentials?.username === "john" &&
credentials?.password === "password"
) {
return user;
}
return null;
},
}),
],
session: {
strategy: "jwt",
},
callbacks: {
// async session({ session, token }) {
// session.user.id = token.sub;
// return session;
// },
async jwt({ token, user }) {
if (user) {
token.sub = user.id;
}
return token;
},
},
};
// auth.use("/api/auth/*", authHandler());
// auth.use("/api/*", verifyAuth());
// auth.get("/api/protected", (c) => {
// const auth = c.get("authUser");
// return c.json(auth);
// });
// export default auth;

View File

@@ -0,0 +1,13 @@
import {OpenAPIHono} from "@hono/zod-openapi";
const app = new OpenAPIHono();
// the doc endpoint
app.doc("/api", {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "LST API",
},
});
export default app;

View File

@@ -1,28 +0,0 @@
import {Hono} from "hono";
import {login} from "lst-auth";
const router = new Hono().post("/", async (c) => {
let body = {username: "", password: "", error: ""};
try {
body = await c.req.json();
} catch (error) {
return c.json({success: false, message: "Username and password required"}, 400);
}
if (!body?.username || !body?.password) {
return c.json({message: "Username and password required"}, 400);
}
try {
const {token, user} = login(body?.username, body?.password);
// Set the JWT as an HTTP-only cookie
c.header("Set-Cookie", `auth_token=${token}; HttpOnly; Secure; Path=/; SameSite=None; Max-Age=3600`);
return c.json({message: "Login successful", user});
} catch (err) {
// console.log(err);
return c.json({message: err}, 401);
}
});
export default router;

View File

@@ -0,0 +1,79 @@
import {OpenAPIHono} from "@hono/zod-openapi";
import {apiReference} from "@scalar/hono-api-reference";
const app = new OpenAPIHono();
app.get(
"/api/docs",
apiReference({
theme: "kepler",
layout: "classic",
defaultHttpClient: {targetKey: "node", clientKey: "axios"},
pageTitle: "Lst API Reference",
hiddenClients: [
"libcurl",
"clj_http",
"httpclient",
"restsharp",
"native",
"http1.1",
"asynchttp",
"nethttp",
"okhttp",
"unirest",
"xhr",
"fetch",
"jquery",
"okhttp",
"native",
"request",
"unirest",
"nsurlsession",
"cohttp",
"curl",
"guzzle",
"http1",
"http2",
"webrequest",
"restmethod",
"python3",
"requests",
"httr",
"native",
"curl",
"httpie",
"wget",
"nsurlsession",
"undici",
],
spec: {
url: "/api",
},
baseServerURL: "https://scalar.com",
servers: [
{
url: "http://usday1vms006:3000",
description: "Production",
},
{
url: "http://localhost:4000",
description: "dev server",
},
],
// authentication: {
// preferredSecurityScheme: {'bearerAuth'},
// },
// metaData: {
// title: "Page title",
// description: "My page page",
// ogDescription: "Still about my my page",
// ogTitle: "Page title",
// ogImage: "https://example.com/image.png",
// twitterCard: "summary_large_image",
// // Add more...
// },
})
);
export default app;

View File

@@ -0,0 +1,12 @@
import {OpenAPIHono} from "@hono/zod-openapi";
import login from "./routes/login";
import register from "./routes/register";
import session from "./routes/session";
const app = new OpenAPIHono();
app.route("api/auth/login", login);
app.route("api/auth//register", register);
app.route("api/auth/session", session);
export default app;

View File

@@ -0,0 +1 @@
export const registerUser = async () => {};

View File

@@ -0,0 +1,17 @@
import bcrypt from "bcrypt";
export const passwordUpdate = (password: string) => {
// encypt password
let pass: string = process.env.SECRET;
let salt: string = process.env.SALTING;
if (!pass || !salt) {
pass = "error";
} else {
pass = bcrypt.hashSync(process.env.SECRET + password, parseInt(process.env.SALTING));
pass = btoa(pass);
}
return pass;
};

View File

@@ -0,0 +1,112 @@
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
import {login} from "lst-auth";
const app = new OpenAPIHono();
const UserSchema = z
.object({
username: z.string().min(3).openapi({example: "smith002"}),
password: z.string().openapi({example: "password123"}),
})
.openapi("User");
// Define the response schema for the login endpoint
const LoginResponseSchema = z
.object({
message: z.string().openapi({example: "Login successful"}),
user: z.object({
username: z.string().openapi({example: "smith002"}),
// Add other user fields as needed
}),
})
.openapi("LoginResponse");
const route = createRoute({
tags: ["Auth"],
summary: "Login as user",
description: "Login as a user to get a JWT token",
method: "post",
path: "/",
request: {body: {content: {"application/json": {schema: UserSchema}}}},
responses: {
200: {
content: {
"application/json": {
schema: LoginResponseSchema,
},
},
description: "Login successful",
},
400: {
content: {
"application/json": {
schema: z.object({
success: z.boolean().openapi({example: false}),
message: z.string().openapi({example: "Username and password required"}),
}),
},
},
description: "Bad request",
},
401: {
content: {
"application/json": {
schema: z.object({
message: z.string().openapi({example: "Invalid credentials"}),
}),
},
},
description: "Unauthorized",
},
},
});
app.openapi(route, async (c) => {
let body: {username: string; password: string};
try {
body = await c.req.json();
} catch (error) {
return c.json({success: false, message: "Username and password required"}, 400);
}
if (!body?.username || !body?.password) {
return c.json({success: false, message: "Username and password required"}, 400);
}
try {
const {token, user} = login(body.username, body.password);
// Set the JWT as an HTTP-only cookie
c.header("Set-Cookie", `auth_token=${token}; HttpOnly; Path=/; SameSite=None; Max-Age=3600`);
return c.json({message: "Login successful", user});
} catch (err) {
return c.json({message: err instanceof Error ? err.message : "Invalid credentials"}, 401);
}
});
/*
let body = {username: "", password: "", error: ""};
try {
body = await c.req.json();
} catch (error) {
return c.json({success: false, message: "Username and password required"}, 400);
}
if (!body?.username || !body?.password) {
return c.json({message: "Username and password required"}, 400);
}
try {
const {token, user} = login(body?.username, body?.password);
// Set the JWT as an HTTP-only cookie
c.header("Set-Cookie", `auth_token=${token}; HttpOnly; Secure; Path=/; SameSite=None; Max-Age=3600`);
return c.json({message: "Login successful", user});
} catch (err) {
// console.log(err);
return c.json({message: err}, 401);
}
*/
export default app;

View File

@@ -0,0 +1,33 @@
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
const app = new OpenAPIHono();
const UserSchema = z
.object({
id: z.string().openapi({example: "123"}),
name: z.string().min(3).openapi({example: "John Doe"}),
age: z.number().openapi({example: 42}),
})
.openapi("User");
app.openapi(
createRoute({
tags: ["Auth"],
summary: "Register a new user",
method: "post",
path: "/",
request: {params: UserSchema},
responses: {
200: {
content: {"application/json": {schema: UserSchema}},
description: "Retrieve the user",
},
},
}),
(c) => {
const {id} = c.req.valid("param");
return c.json({id, age: 20, name: "Ultra-man"});
}
);
export default app;

View File

@@ -1,11 +1,29 @@
import {Hono} from "hono";
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
import {verify} from "hono/jwt";
const app = new Hono();
const session = new OpenAPIHono();
const tags = ["Auth"];
const JWT_SECRET = "your-secret-key";
app.get("/", async (c) => {
const route = createRoute({
tags: ["Auth"],
summary: "Checks a user session based on there token",
description: "Can post there via Authentiaction header or cookies",
method: "get",
path: "/",
request: {body: {content: {"application/json": {schema: {username: "", password: ""}}}}},
responses: {
200: {
content: {
"application/json": {
schema: {session: ""},
},
},
description: "Login successful",
},
},
});
session.openapi(route, async (c) => {
const authHeader = c.req.header("Authorization");
const cookies = c.req.header("cookie");
@@ -17,13 +35,6 @@ app.get("/", async (c) => {
if (!authHeader && !cookies) {
return c.json({error: "Unauthorized"}, 401);
}
// if (!cookies || !cookies.startsWith("Bearer ")) {
// return c.json({error: "Unauthorized"}, 401);
// }
// if (!authHeader || !authHeader.startsWith("Bearer ")) {
// return c.json({error: "Unauthorized"}, 401);
// }
const token = cookies?.split("auth_token=")[1].split(";")[0] || authHeader?.split("Bearer ")[1] || "";
@@ -35,4 +46,4 @@ app.get("/", async (c) => {
}
});
export default app;
export default session;