backup: removals of server-side proxies (backup branch)
This commit is contained in:
parent
9244c7d8f1
commit
b2bdc68319
@ -1,42 +0,0 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { ENV_CONFIG } from '@/lib/env-config'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json().catch(() => ({}))
|
||||
const target = `${ENV_CONFIG.SUPABASE_URL}/functions/v1/create-user`
|
||||
const headers: Record<string,string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'apikey': ENV_CONFIG.SUPABASE_ANON_KEY,
|
||||
}
|
||||
const auth = req.headers.get('authorization')
|
||||
if (auth) headers.Authorization = auth
|
||||
|
||||
const r = await fetch(target, { method: 'POST', headers, body: JSON.stringify(body) })
|
||||
if (r.status === 404 || r.status >= 500) {
|
||||
// fallback to signup
|
||||
const email = body.email
|
||||
let password = body.password
|
||||
const full_name = body.full_name
|
||||
const phone = body.phone
|
||||
const role = body.role || (Array.isArray(body.roles) ? body.roles[0] : undefined)
|
||||
if (!password) password = `senha${Math.floor(Math.random()*900)+100}!`
|
||||
const userType = (role && String(role).toLowerCase() === 'paciente') ? 'paciente' : 'profissional'
|
||||
const signupUrl = `${ENV_CONFIG.SUPABASE_URL}/auth/v1/signup`
|
||||
const signupRes = await fetch(signupUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type':'application/json', 'Accept':'application/json', 'apikey': ENV_CONFIG.SUPABASE_ANON_KEY },
|
||||
body: JSON.stringify({ email, password, data: { userType, full_name, phone } })
|
||||
})
|
||||
const text = await signupRes.text()
|
||||
try { return NextResponse.json({ fallback: true, from: 'signup', result: JSON.parse(text) }, { status: signupRes.status }) } catch { return new NextResponse(text, { status: signupRes.status }) }
|
||||
}
|
||||
|
||||
const text = await r.text()
|
||||
try { return NextResponse.json(JSON.parse(text), { status: r.status }) } catch { return new NextResponse(text, { status: r.status }) }
|
||||
} catch (err:any) {
|
||||
console.error('[app/api/create-user] error', err)
|
||||
return NextResponse.json({ error: 'Bad gateway', details: String(err) }, { status: 502 })
|
||||
}
|
||||
}
|
||||
@ -1,46 +0,0 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { ENV_CONFIG } from '@/lib/env-config';
|
||||
|
||||
/**
|
||||
* Proxy server-side route (App Router) to call Supabase OpenAPI /auth/v1/signin
|
||||
* This keeps the Supabase anon key on the server and avoids CORS from browsers.
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const payload = await req.json();
|
||||
|
||||
// Lightweight, non-sensitive debug logging to verify the proxy is hit at runtime.
|
||||
try {
|
||||
console.log('[api/signin-user] POST received', {
|
||||
url: typeof (req as any).url === 'string' ? (req as any).url : undefined,
|
||||
email: payload?.email ?? null,
|
||||
});
|
||||
} catch (e) {
|
||||
// never throw from logging
|
||||
}
|
||||
|
||||
const url = `${ENV_CONFIG.SUPABASE_URL}/auth/v1/signin`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
apikey: ENV_CONFIG.SUPABASE_ANON_KEY,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
const text = await response.text();
|
||||
let data: any = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch (e) {
|
||||
data = text;
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: response.status });
|
||||
} catch (error) {
|
||||
console.error('[api/signin-user] Unexpected error', error);
|
||||
return NextResponse.json({ error: 'Internal proxy error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
1
susconecta/next-env.d.ts
vendored
1
susconecta/next-env.d.ts
vendored
@ -1,6 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
/// <reference types="next/navigation-types/compat/navigation" />
|
||||
/// <reference path="./.next/types/routes.d.ts" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
|
||||
@ -1,70 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ENV_CONFIG } from '@/lib/env-config'
|
||||
|
||||
type Body = {
|
||||
user_id: string
|
||||
role: string
|
||||
}
|
||||
|
||||
async function getRequesterIdFromToken(token: string | null): Promise<string | null> {
|
||||
if (!token) return null
|
||||
try {
|
||||
const url = `${ENV_CONFIG.SUPABASE_URL}/auth/v1/user`
|
||||
const res = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'apikey': ENV_CONFIG.SUPABASE_ANON_KEY, Authorization: `Bearer ${token}` } })
|
||||
if (!res.ok) return null
|
||||
const data = await res.json().catch(() => null)
|
||||
return data?.id ?? null
|
||||
} catch (err) {
|
||||
console.error('[assign-role] erro ao obter requester id', err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const body = (await req.json()) as Body
|
||||
if (!body || !body.user_id || !body.role) return NextResponse.json({ error: 'user_id and role required' }, { status: 400 })
|
||||
|
||||
// Business rule: there is no separate 'paciente' role — patients are any user.
|
||||
// Prevent creation/assignment of a 'paciente' role to avoid confusion.
|
||||
if (body.role === 'paciente') {
|
||||
return NextResponse.json({ error: "role 'paciente' must not be created or assigned; patients are regular users" }, { status: 400 })
|
||||
}
|
||||
|
||||
const authHeader = req.headers.get('authorization')
|
||||
const token = authHeader?.startsWith('Bearer ') ? authHeader.split(' ')[1] : null
|
||||
|
||||
const requesterId = await getRequesterIdFromToken(token)
|
||||
if (!requesterId) return NextResponse.json({ error: 'unauthenticated' }, { status: 401 })
|
||||
|
||||
// Check if requester is administrador
|
||||
const checkUrl = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/user_roles?user_id=eq.${requesterId}&role=eq.administrador`
|
||||
const checkRes = await fetch(checkUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', apikey: ENV_CONFIG.SUPABASE_ANON_KEY, Authorization: `Bearer ${token}` } })
|
||||
if (!checkRes.ok) return NextResponse.json({ error: 'forbidden' }, { status: 403 })
|
||||
const arr = await checkRes.json().catch(() => [])
|
||||
if (!Array.isArray(arr) || arr.length === 0) return NextResponse.json({ error: 'forbidden' }, { status: 403 })
|
||||
|
||||
// Insert role using service role key from environment (must be set on the server)
|
||||
const svcKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
if (!svcKey) return NextResponse.json({ error: 'server misconfigured' }, { status: 500 })
|
||||
|
||||
const insertUrl = `${ENV_CONFIG.SUPABASE_URL}/rest/v1/user_roles`
|
||||
const insertRes = await fetch(insertUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json', apikey: svcKey, Authorization: `Bearer ${svcKey}` },
|
||||
body: JSON.stringify({ user_id: body.user_id, role: body.role }),
|
||||
})
|
||||
|
||||
if (!insertRes.ok) {
|
||||
const errBody = await insertRes.text().catch(() => null)
|
||||
console.error('[assign-role] insert failed', insertRes.status, errBody)
|
||||
return NextResponse.json({ error: 'failed to assign role', details: errBody }, { status: insertRes.status })
|
||||
}
|
||||
|
||||
const result = await insertRes.json().catch(() => null)
|
||||
return NextResponse.json({ ok: true, data: result })
|
||||
} catch (err) {
|
||||
console.error('[assign-role] unexpected error', err)
|
||||
return NextResponse.json({ error: 'internal error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user