Letschat / src /lib /supabase /auth.ts
HonzaH's picture
Upload 175 files
5a7302b verified
Raw History Blame Contribute Delete
2.22 kB
import { createClient } from '@supabase/supabase-js'
import type { Database } from 'types/database'
import { SUPABASE_SERVICE_ROLE_KEY, SUPABASE_URL } from './env'
export async function createAuthAndProfile({
email,
password,
fname,
sname
}: {
email: string
password: string
fname?: string
sname?: string
}): Promise<Database['public']['Tables']['users']['Row']> {
if (!SUPABASE_URL || !SUPABASE_SERVICE_ROLE_KEY) {
throw new Error('Serverová konfigurace chybí (SUPABASE_SERVICE_ROLE_KEY nebo SUPABASE_URL)')
}
const supabaseAdmin = createClient<Database>(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, {
auth: { persistSession: false }
})
// Create auth user via Admin API
const { data: createAuthData, error: createAuthError } = await supabaseAdmin.auth.admin.createUser({
email,
password,
user_metadata: { fname, sname },
email_confirm: true
})
if (createAuthError) {
throw createAuthError
}
// Normalize admin.createUser response shape and validate presence of user id.
let authUser: { id?: string } | null = null
if (createAuthData && typeof createAuthData === 'object') {
const possibleUser = (createAuthData as any).user ?? createAuthData
if (possibleUser && typeof possibleUser === 'object') {
authUser = possibleUser as { id?: string } | null
}
}
if (!authUser?.id) {
throw new Error('Vytvořený auth uživatel nemá id')
}
// Build profile payload typed as Insert — ensure required string fields are present
const payload: Database['public']['Tables']['users']['Insert'] = {
id: authUser.id,
email,
fname: fname ?? '',
sname: sname ?? '',
status: 1 // Pending verification
}
// Insert profile row into public.users using the service role (no password stored)
const { data: profile, error: profileError } = await supabaseAdmin
.from('users')
.insert(payload as any)
.select()
.single()
if (profileError) {
// Note: in a production migration you may want to rollback the created auth user.
throw profileError
}
return profile as Database['public']['Tables']['users']['Row']
}