UNPKG

supabase-node-kit

Version:

A backend utility package for Supabase authentication and database functionality.

1 lines 13.9 kB
{"version":3,"sources":["../src/config/supabaseClient.ts","../src/auth/authService.ts","../src/db/dbservice.ts"],"sourcesContent":["import { createClient } from \"@supabase/supabase-js\";\n\n// Public variables (safe for client-side)\nconst SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL || \"\";\nconst SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY || \"\";\n\n// Private variable (server-side only)\nconst SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || \"\";\n\n// Determine if we're on server side\nconst isServerSide = typeof window === 'undefined';\n\nif (!SUPABASE_URL) {\n throw new Error(\"Supabase URL is missing\");\n}\n\n// Create two different clients for different use cases\nexport const supabaseClient = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {\n auth: { persistSession: true },\n});\n\n// Only create service role client on server-side\nexport const supabaseAdmin = isServerSide\n ? createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, {\n auth: { persistSession: false },\n })\n : null;\n\n ","import { supabaseClient, supabaseAdmin } from \"../config/supabaseClient\";\nimport { Provider, Session } from \"@supabase/supabase-js\";\n\n// Client-side auth operations\nexport const authService = {\n /**\n * Authenticates a user with email and password\n * @param email - User's email address\n * @param password - User's password\n * @returns Promise containing the sign in response\n * @example\n * const { data, error } = await authService.signIn('user@example.com', 'password123')\n */\n async signIn(email: string, password: string) {\n return await supabaseClient.auth.signInWithPassword({ email, password });\n },\n\n /**\n * Signs out the currently authenticated user\n * @returns Promise containing the sign out response\n * @example\n * await authService.signOutCurrentUser()\n */\n async signOutCurrentUser() {\n return await supabaseClient.auth.signOut();\n },\n\n /**\n * Retrieves the currently authenticated user's details\n * @returns Promise containing the current user data\n * @example\n * const { data: { user }, error } = await authService.getCurrentUser()\n */\n async getCurrentUser() {\n return await supabaseClient.auth.getUser();\n },\n\n async signUp(email: string, password: string) {\n // Check if user exists\n const { data: existingUser } = await supabaseClient\n .from('users')\n .select()\n .eq('email', email)\n .single();\n\n if (existingUser) {\n throw new Error('User with this email already exists');\n }\n\n return await supabaseClient.auth.signUp({\n email,\n password,\n options: {\n emailRedirectTo: `${window.location.origin}/auth/callback`,\n },\n });\n },\n\n /**\n * Signs in with a third-party provider\n * @param provider - The authentication provider (google, github, etc.)\n * @returns Promise containing the sign in response\n * @example\n * await authService.signInWithProvider('google')\n */\n async signInWithProvider(provider: Provider) {\n return await supabaseClient.auth.signInWithOAuth({\n provider,\n options: {\n redirectTo: `${window.location.origin}/auth/callback`,\n scopes: 'email profile',\n },\n });\n },\n\n /**\n * Sends a password reset email\n * @param email - User's email address\n * @returns Promise containing the reset response\n * @example\n * const { data, error } = await authService.resetPassword('user@example.com')\n */\n async resetPassword(email: string) {\n return await supabaseClient.auth.resetPasswordForEmail(email, {\n redirectTo: `${window.location.origin}/auth/reset-password`,\n });\n },\n\n /**\n * Updates user's password\n * @param newPassword - New password\n * @returns Promise containing the update response\n * @example\n * const { data, error } = await authService.updatePassword('newPassword123')\n */\n async updatePassword(newPassword: string) {\n return await supabaseClient.auth.updateUser({\n password: newPassword,\n });\n },\n};\n\n// Server-side admin auth operations\nexport const authAdminService = {\n /**\n * Creates a new user account (Server-side only)\n * @param email - New user's email address\n * @param password - New user's password\n * @returns Promise containing the created user data\n * @throws Error if called from client-side\n * @example\n * // Only in API routes or server-side code\n * const { data, error } = await authAdminService.createUser('newuser@example.com', 'password123')\n */\n async createUser(email: string, password: string) {\n if (!supabaseAdmin) {\n throw new Error(\"Admin operations can only be performed server-side\");\n }\n return await supabaseAdmin.auth.admin.createUser({ \n email, \n password, \n email_confirm: true \n });\n },\n\n /**\n * Deletes a user account by ID (Server-side only)\n * @param userId - The UUID of the user to delete\n * @returns Promise containing the deletion response\n * @throws Error if called from client-side\n * @example\n * // Only in API routes or server-side code\n * await authAdminService.deleteUser('user-uuid-here')\n */\n async deleteUser(userId: string) {\n if (!supabaseAdmin) {\n throw new Error(\"Admin operations can only be performed server-side\");\n }\n return await supabaseAdmin.auth.admin.deleteUser(userId);\n },\n\n /**\n * Retrieves user details by ID (Server-side only)\n * @param userId - The UUID of the user to fetch\n * @returns Promise containing the user data\n * @throws Error if called from client-side\n * @example\n * // Only in API routes or server-side code\n * const { data: { user }, error } = await authAdminService.getUserById('user-uuid-here')\n */\n async getUserById(userId: string) {\n if (!supabaseAdmin) {\n throw new Error(\"Admin operations can only be performed server-side\");\n }\n return await supabaseAdmin.auth.admin.getUserById(userId);\n },\n\n /**\n * Forces sign out for a specific user (Server-side only)\n * @param userId - The UUID of the user to sign out\n * @returns Promise containing the sign out response\n * @throws Error if called from client-side\n * @example\n * // Only in API routes or server-side code\n * await authAdminService.signOutUser('user-uuid-here')\n */\n async signOutUser(userId: string) {\n if (!supabaseAdmin) {\n throw new Error(\"Admin operations can only be performed server-side\");\n }\n return await supabaseAdmin.auth.admin.signOut(userId);\n },\n\n async checkUserExists(email: string) {\n if (!supabaseAdmin) {\n throw new Error(\"Admin operations can only be performed server-side\");\n }\n const { data, error } = await supabaseAdmin\n .from('users')\n .select('id')\n .eq('email', email)\n .single();\n \n return { exists: !!data, error };\n },\n\n /**\n * Updates user's email verification status (Server-side only)\n * @param userId - The UUID of the user\n * @param verified - Boolean indicating verification status\n * @throws Error if called from client-side\n * @example\n * await authAdminService.updateEmailVerification('user-uuid', true)\n */\n async updateEmailVerification(userId: string, verified: boolean) {\n if (!supabaseAdmin) {\n throw new Error(\"Admin operations can only be performed server-side\");\n }\n return await supabaseAdmin.auth.admin.updateUserById(userId, {\n email_confirm: verified,\n });\n },\n\n /**\n * Initialize auth session from existing session data\n * @returns Promise containing the session data\n * @example\n * const { data: { session }, error } = await authService.initializeSession()\n */\n async initializeSession() {\n return await supabaseClient.auth.getSession();\n },\n\n /**\n * Set up an auth state change listener\n * @param callback - Function to handle auth state changes\n * @returns Cleanup function to remove the listener\n * @example\n * const unsubscribe = authService.onAuthStateChange((event, session) => {\n * console.log('Auth event:', event, session)\n * })\n */\n onAuthStateChange(callback: (event: string, session: Session | null) => void) {\n return supabaseClient.auth.onAuthStateChange(callback);\n },\n};","import { supabaseClient, supabaseAdmin } from \"../config/supabaseClient\";\nimport { SupabaseClient } from \"@supabase/supabase-js\";\n\n// Helper to determine which client to use\nconst getClient = (useAdmin: boolean = false): SupabaseClient => {\n if (useAdmin && !supabaseAdmin) {\n throw new Error(\"Admin operations can only be performed server-side\");\n }\n return useAdmin ? supabaseAdmin! : supabaseClient;\n};\n\nexport const dbService = {\n async getAll(table: string, useAdmin: boolean = false) {\n const client = getClient(useAdmin);\n return await client.from(table).select(\"*\");\n },\n\n async getById(table: string, id: number, useAdmin: boolean = false) {\n const client = getClient(useAdmin);\n return await client.from(table).select(\"*\").eq(\"id\", id).single();\n },\n\n async insert(table: string, values: object, useAdmin: boolean = false) {\n const client = getClient(useAdmin);\n return await client.from(table).insert(values);\n },\n\n async update(table: string, id: number, values: object, useAdmin: boolean = false) {\n const client = getClient(useAdmin);\n return await client.from(table).update(values).eq(\"id\", id);\n },\n\n async remove(table: string, id: number, useAdmin: boolean = false) {\n const client = getClient(useAdmin);\n return await client.from(table).delete().eq(\"id\", id);\n },\n};"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAG7B,IAAM,eAAe,QAAQ,IAAI,4BAA4B,QAAQ,IAAI,gBAAgB;AACzF,IAAM,oBAAoB,QAAQ,IAAI,iCAAiC,QAAQ,IAAI,qBAAqB;AAGxG,IAAM,4BAA4B,QAAQ,IAAI,6BAA6B;AAG3E,IAAM,eAAe,OAAO,WAAW;AAEvC,IAAI,CAAC,cAAc;AACjB,QAAM,IAAI,MAAM,yBAAyB;AAC3C;AAGO,IAAM,iBAAiB,aAAa,cAAc,mBAAmB;AAAA,EAC1E,MAAM,EAAE,gBAAgB,KAAK;AAC/B,CAAC;AAGM,IAAM,gBAAgB,eACzB,aAAa,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