xtablo-source/api/src/middleware.ts

38 lines
1 KiB
TypeScript
Raw Normal View History

2025-06-23 09:34:30 +00:00
import { createClient, User } from "@supabase/supabase-js";
import { Context, Next } from "hono";
// Create authentication middleware
export const authMiddleware = async (c: Context, next: Next) => {
const supabase = c.get("supabase");
// Extract Bearer token from Authorization header
const authHeader = c.req.header("Authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return c.json({ error: "Missing or invalid authorization header" }, 401);
}
const token = authHeader.substring(7); // Remove "Bearer " prefix
const {
data: { user },
error,
} = await supabase.auth.getUser(token);
if (error || !user) {
return c.json({ error: "Invalid or expired token" }, 401);
}
const userTyped = user as User;
c.set("user", userTyped);
await next();
};
export const supabaseMiddleware = async (c: Context, next: Next) => {
const supabase = createClient(
process.env.SUPABASE_URL as string,
process.env.SUPABASE_ANON_KEY as string
);
c.set("supabase", supabase);
await next();
};