906a0041a4
- Add + New User form on Companies page (name, email, password, company) - Create-user Supabase edge function with role verification - Remove public signup route and login page link Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
66 lines
2.4 KiB
TypeScript
66 lines
2.4 KiB
TypeScript
// deno-lint-ignore-file
|
|
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
|
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
|
|
|
const corsHeaders = {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
}
|
|
|
|
const ok = (body: Record<string, unknown>) => new Response(JSON.stringify(body), {
|
|
status: 200,
|
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
})
|
|
|
|
serve(async (req) => {
|
|
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
|
|
|
|
try {
|
|
const authHeader = req.headers.get('Authorization') ?? ''
|
|
if (!authHeader) return ok({ error: 'No authorization header' })
|
|
|
|
const callerClient = createClient(
|
|
Deno.env.get('SUPABASE_URL') ?? '',
|
|
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
{ global: { headers: { Authorization: authHeader } } }
|
|
)
|
|
|
|
const { data: userData, error: userError } = await callerClient.auth.getUser()
|
|
if (userError || !userData?.user) return ok({ error: `Auth failed: ${userError?.message ?? 'no user'}` })
|
|
|
|
const { data: profile, error: profileError } = await callerClient
|
|
.from('profiles').select('role').eq('id', userData.user.id).single()
|
|
if (profileError) return ok({ error: `Profile error: ${profileError.message}` })
|
|
if (profile?.role !== 'team') return ok({ error: 'Forbidden: team only' })
|
|
|
|
const body = await req.json()
|
|
const { name, email, password, company_id } = body
|
|
if (!name || !email || !password) return ok({ error: 'name, email and password are required' })
|
|
|
|
const admin = createClient(
|
|
Deno.env.get('SUPABASE_URL') ?? '',
|
|
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
|
)
|
|
|
|
const { data: created, error: createError } = await admin.auth.admin.createUser({
|
|
email,
|
|
password,
|
|
email_confirm: true,
|
|
user_metadata: { name, role: 'client' },
|
|
})
|
|
|
|
if (createError) return ok({ error: `Create user failed: ${createError.message}` })
|
|
|
|
if (company_id && created?.user) {
|
|
const { error: assignError } = await admin
|
|
.from('profiles').update({ company_id }).eq('id', created.user.id)
|
|
if (assignError) return ok({ error: `User created but company assign failed: ${assignError.message}` })
|
|
}
|
|
|
|
return ok({ success: true })
|
|
|
|
} catch (err) {
|
|
return ok({ error: `Unexpected: ${String(err)}` })
|
|
}
|
|
})
|