Skip to content

Commit

Permalink
refactor: split the auth and ui routers into their own routes (#42)
Browse files Browse the repository at this point in the history
* refactor(ui): split the ui out of the auth routing

* chore: bump package to 2.3.4
  • Loading branch information
SeanCassiere authored Jul 1, 2024
1 parent 4ea33a2 commit f8ae0ed
Show file tree
Hide file tree
Showing 19 changed files with 56 additions and 54 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "simple-logging-server",
"license": "MIT",
"version": "2.3.3",
"version": "2.3.4",
"description": "This is a simple API for logging messages",
"author": "Sean Cassiere",
"keywords": [],
Expand Down
25 changes: 0 additions & 25 deletions src/routers/app/auth/index.mts

This file was deleted.

File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 3 additions & 0 deletions src/routers/app/ui/index.tsx → src/routers/app/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Hono } from "hono";

import { sessionMiddleware } from "@/routers/auth/middleware.mjs";
import { db } from "@/config/db/index.mjs";

import { NoOrganizationPage } from "./pages/app.index.js";
Expand All @@ -15,6 +16,8 @@ import type { ServerContext } from "@/types/hono.mjs";

const app = new Hono<ServerContext>();

app.use("*", sessionMiddleware);

app.get("/", checkUserAuthed, async (c) => {
const user = c.var.user!;
const view_all = c.req.query("view_all") || "false";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const AppContainer: FC<PropsWithChildren<AppContainerProps>> = ({
<span class="border-t" />
</div>
<div class="p-2">
<a href="/app/logout">👋🏼 Logout</a>
<a href="/auth/logout">👋🏼 Logout</a>
</div>
</aside>
<main className={["md:col-span-3 lg:col-span-4", mainClass].filter(Boolean).join(" ")}>{children}</main>
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const LoginPage: FC = () => {
<p class="text-gray-700 lg:text-sm">You must first sign in with GitHub to access the application.</p>
</div>
<div class="p-4">
<a class={[getButtonStyles("primary"), "w-full gap-3"].join(" ")} href="/app/login/github">
<a class={[getButtonStyles("primary"), "w-full gap-3"].join(" ")} href="/auth/login/github">
<span>Login with GitHub</span>
<icons.Github class="h-5 w-5 fill-white" />
</a>
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { setCookie } from "hono/cookie";
import { createMiddleware } from "hono/factory";
import { HTTPException } from "hono/http-exception";

import { db } from "@/config/db/index.mjs";
import { env } from "@/config/env.mjs";

import type { ServerContext } from "@/types/hono.mjs";

export const checkUserAuthed = createMiddleware<ServerContext>(async (c, next) => {
const user = c.var.user;

if (!user) {
setCookie(c, "post_login_redirect", c.req.url, {
path: "/",
secure: env.NODE_ENV === "production",
httpOnly: true,
maxAge: 60 * 10,
sameSite: "Lax",
});

return c.redirect("/app/login");
}

Expand Down
47 changes: 34 additions & 13 deletions src/routers/app/auth/github.mts → src/routers/auth/index.mts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { OAuth2RequestError, generateState } from "arctic";
import type { ServerContext } from "@/types/hono.mjs";
import { Hono } from "hono";

import { OAuth2RequestError, generateState } from "arctic";
import { getCookie, setCookie } from "hono/cookie";
import { z } from "zod";

Expand All @@ -13,11 +15,25 @@ import { env } from "@/config/env.mjs";
import { github, lucia } from "@/config/lucia/index.mjs";
import { createDbId } from "@/utils/db.mjs";

import type { ServerContext } from "@/types/hono.mjs";
import { sessionMiddleware } from "./middleware.mjs";

const app = new Hono<ServerContext>();

app.get("/", async (c) => {
app.use("*", sessionMiddleware);

app.get("/login/github", async (c) => {
const post_login_redirect = getCookie(c).post_login_redirect || "/app";

if (post_login_redirect.length === 0 || post_login_redirect === "/app") {
setCookie(c, "post_login_redirect", "/app", {
path: "/",
secure: env.NODE_ENV === "production",
httpOnly: true,
maxAge: 60 * 10,
sameSite: "Lax",
});
}

const state = generateState();
const url = await github.createAuthorizationURL(state);

Expand All @@ -29,14 +45,6 @@ app.get("/", async (c) => {
sameSite: "Lax",
});

setCookie(c, "post_login_redirect", "/app", {
path: "/",
secure: env.NODE_ENV === "production",
httpOnly: true,
maxAge: 60 * 10,
sameSite: "Lax",
});

return c.redirect(url.toString());
});

Expand All @@ -45,7 +53,7 @@ const githubUserSchema = z.object({
login: z.string(),
});

app.get("/callback", async (c) => {
app.get("/login/github/callback", async (c) => {
const code = c.req.query("code")?.toString() ?? null;
const state = c.req.query("state")?.toString() ?? null;
const storedState = getCookie(c).github_oauth_state ?? null;
Expand All @@ -54,7 +62,7 @@ app.get("/callback", async (c) => {
return c.body(null, 400);
}

const postLoginRedirect = getCookie(c).post_login_redirect ?? "/app";
const postLoginRedirect = getCookie(c).post_login_redirect || "/app";

try {
const tokens = await github.validateAuthorizationCode(code);
Expand Down Expand Up @@ -105,4 +113,17 @@ app.get("/callback", async (c) => {
}
});

app.get("/logout", async (c) => {
const session = c.get("session");
if (!session) {
return c.body(null, 401);
}

await lucia.invalidateSession(session.id);

c.header("Set-Cookie", lucia.createBlankSessionCookie().serialize(), { append: true });

return c.redirect("/app");
});

export default app;
15 changes: 3 additions & 12 deletions src/routers/app/index.mts → src/routers/auth/middleware.mts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import type { ServerContext } from "@/types/hono.mjs";
import { Hono } from "hono";
import { createMiddleware } from "hono/factory";

import { lucia } from "@/config/lucia/index.mjs";

import authRouter from "./auth/index.mjs";
import uiRouter from "./ui/index.js";

const app = new Hono<ServerContext>();
import type { ServerContext } from "@/types/hono.mjs";

app.use("*", async (c, next) => {
export const sessionMiddleware = createMiddleware<ServerContext>(async (c, next) => {
const sessionId = lucia.readSessionCookie(c.req.header("Cookie") ?? "");
if (!sessionId) {
c.set("user", null);
Expand All @@ -30,8 +26,3 @@ app.use("*", async (c, next) => {

return await next();
});

app.route("", authRouter);
app.route("", uiRouter);

export default app;
4 changes: 3 additions & 1 deletion src/server.mts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import { secureHeaders } from "hono/secure-headers";
import { timeout } from "hono/timeout";
import { trimTrailingSlash } from "hono/trailing-slash";

import appRouter from "@/routers/app/index.mjs";
import appRouter from "@/routers/app/index.js";
import authRouter from "@/routers/auth/index.mjs";
import docsRouter from "@/routers/docs/index.mjs";
import v2Router from "@/routers/v2/index.mjs";

Expand Down Expand Up @@ -43,6 +44,7 @@ app.use("/api/", timeout(5000));
app.route("/api/v2", v2Router);

app.use(limiter);
app.route("/auth", authRouter);
app.route("/docs", docsRouter);
app.route("/app", appRouter);

Expand Down

0 comments on commit f8ae0ed

Please sign in to comment.