File size: 2,216 Bytes
5a7302b 9853b20 5a7302b | 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 | 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']
}
|