2025-07-29 19:24:12 +00:00
|
|
|
import { S3Client } from "@aws-sdk/client-s3";
|
2025-06-24 19:56:43 +00:00
|
|
|
import { createClient, type User } from "@supabase/supabase-js";
|
|
|
|
|
import type { Context, Next } from "hono";
|
2025-07-05 13:16:42 +00:00
|
|
|
import { StreamChat } from "stream-chat";
|
2025-09-23 20:14:02 +00:00
|
|
|
import { config } from "./config.js";
|
2025-06-23 09:34:30 +00:00
|
|
|
|
|
|
|
|
// 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,
|
2025-07-03 19:42:49 +00:00
|
|
|
process.env.SUPABASE_SERVICE_ROLE_KEY as string
|
2025-06-23 09:34:30 +00:00
|
|
|
);
|
|
|
|
|
c.set("supabase", supabase);
|
|
|
|
|
await next();
|
|
|
|
|
};
|
2025-07-01 20:28:49 +00:00
|
|
|
|
2025-07-05 13:16:42 +00:00
|
|
|
export const streamChatMiddleware = async (c: Context, next: Next) => {
|
|
|
|
|
const serverClient = StreamChat.getInstance(
|
|
|
|
|
process.env.STREAM_CHAT_API_KEY as string,
|
|
|
|
|
process.env.STREAM_CHAT_API_SECRET as string,
|
|
|
|
|
{
|
|
|
|
|
disableCache: true,
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
c.set("streamServerClient", serverClient);
|
|
|
|
|
await next();
|
|
|
|
|
};
|
2025-07-29 19:24:12 +00:00
|
|
|
|
|
|
|
|
export const r2Middleware = async (c: Context, next: Next) => {
|
|
|
|
|
const s3 = new S3Client({
|
|
|
|
|
region: "auto",
|
|
|
|
|
endpoint: `https://${config.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
|
|
|
|
|
credentials: {
|
|
|
|
|
accessKeyId: config.R2_ACCESS_KEY_ID,
|
|
|
|
|
secretAccessKey: config.R2_SECRET_ACCESS_KEY,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
c.set("s3_client", s3);
|
|
|
|
|
await next();
|
|
|
|
|
};
|