(feur)
This commit is contained in:
parent
60133a4a08
commit
c70202e5d1
6 changed files with 117 additions and 8 deletions
0
routes/feur.tsx
Normal file
0
routes/feur.tsx
Normal file
|
@ -2,16 +2,14 @@ import { useSignal } from "@preact/signals";
|
|||
import Counter from "../islands/Counter.tsx";
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
import { getCookies } from "$std/http/cookie.ts";
|
||||
import { User } from "../storage/models/User.ts";
|
||||
|
||||
interface Data {
|
||||
user: User;
|
||||
}
|
||||
import { db, User } from "../storage/store.ts";
|
||||
import { auth } from "../auth/auth.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
GET(req, ctx) {
|
||||
const cookies = getCookies(req.headers);
|
||||
return ctx.render!({ allowed: cookies.auth === "bar" });
|
||||
const user = get_session_user(cookies);
|
||||
return ctx.render!({ user });
|
||||
},
|
||||
};
|
||||
|
||||
|
|
40
routes/middleware.ts
Normal file
40
routes/middleware.ts
Normal file
|
@ -0,0 +1,40 @@
|
|||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { deleteCookie, getCookies, setCookie } from "$std/http/cookie.ts";
|
||||
import { auth, Token } from "../auth/auth.ts";
|
||||
|
||||
type State = {
|
||||
user_id: string | null;
|
||||
};
|
||||
|
||||
export async function handler(
|
||||
req: Request,
|
||||
ctx: FreshContext<State>,
|
||||
) {
|
||||
const cookies = getCookies(req.headers);
|
||||
const token = get_session_token(cookies);
|
||||
|
||||
ctx.state.user_id = token?.user_id ?? null;
|
||||
|
||||
const resp = await ctx.next();
|
||||
set_session_token(resp.headers, token);
|
||||
return resp;
|
||||
}
|
||||
|
||||
function get_session_token(cookies: Record<string, string>) {
|
||||
const stored = cookies["auth_token"];
|
||||
if (stored === undefined) return null;
|
||||
const token = auth.tokens.get(stored);
|
||||
if (token === null) return null;
|
||||
return token;
|
||||
}
|
||||
|
||||
function set_session_token(headers: Headers, token: Token | null) {
|
||||
if (token === null) {
|
||||
deleteCookie(headers, "auth_token");
|
||||
return;
|
||||
}
|
||||
setCookie(headers, {
|
||||
name: "auth_token",
|
||||
value: token.raw,
|
||||
});
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue