Repository navigation
Expand file tree
/
Copy pathauth.ts
More file actions
86 lines (72 loc) · 2.64 KB
/
Copy pathauth.ts
File metadata and controls
86 lines (72 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { createClient, type SupabaseClient, type User } from "https://esm.sh/@supabase/supabase-js@2.114.0";
function requiredEnv(name: string) {
const value = Deno.env.get(name);
if (!value) throw new Error(`Missing required env: ${name}`);
return value;
}
const supabaseUrl = requiredEnv("SUPABASE_URL");
const supabaseServiceRoleKey = requiredEnv("SUPABASE_SERVICE_ROLE_KEY");
const supabaseAnonKey = requiredEnv("SUPABASE_ANON_KEY");
export type AuthContext = {
token: string;
user: User;
userClient: SupabaseClient;
adminClient: SupabaseClient;
};
export class HttpError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = "HttpError";
this.status = status;
}
}
export function createAdminClient() {
return createClient(supabaseUrl, supabaseServiceRoleKey, {
auth: { persistSession: false, autoRefreshToken: false },
});
}
export function createUserClient(authHeader: string) {
return createClient(supabaseUrl, supabaseAnonKey, {
global: { headers: { Authorization: authHeader } },
auth: { persistSession: false, autoRefreshToken: false },
});
}
export function getBearerToken(req: Request) {
const authHeader = req.headers.get("authorization") || req.headers.get("Authorization");
if (!authHeader?.startsWith("Bearer ")) {
throw new HttpError(401, "Authentication required");
}
const token = authHeader.slice("Bearer ".length).trim();
if (!token) {
throw new HttpError(401, "Authentication required");
}
return { authHeader, token };
}
export async function requireUser(req: Request, adminKey = supabaseServiceRoleKey): Promise<AuthContext> {
const { authHeader, token } = getBearerToken(req);
const adminClient = createClient(supabaseUrl, adminKey, {
auth: { persistSession: false, autoRefreshToken: false },
});
const { data: { user }, error } = await adminClient.auth.getUser(token);
if (error || !user) {
throw new HttpError(401, "Invalid authentication token");
}
return {
token,
user,
userClient: createUserClient(authHeader),
adminClient,
};
}
export function jsonError(error: unknown, corsHeaders: Record<string, string>) {
const status = error instanceof HttpError ? error.status : 500;
if (!(error instanceof HttpError)) {
console.error("[AUTH] Internal error:", error instanceof Error ? error.message.slice(0, 2000) : String(error).slice(0, 2000));
}
const message = error instanceof HttpError ? error.message : "Internal server error";
return new Response(JSON.stringify({ error: message }), {
status,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}