forked from RiseUP/riseup-squad21
merge fix
This commit is contained in:
parent
07f6eca41a
commit
65087a9f51
@ -6,6 +6,9 @@ import "./globals.css";
|
|||||||
import { Toaster } from "@/components/ui/toaster";
|
import { Toaster } from "@/components/ui/toaster";
|
||||||
// [PASSO 1.2] - Importando o nosso provider
|
// [PASSO 1.2] - Importando o nosso provider
|
||||||
import { AppointmentsProvider } from "./context/AppointmentsContext";
|
import { AppointmentsProvider } from "./context/AppointmentsContext";
|
||||||
|
import { AccessibilityProvider } from "./context/AccessibilityContext";
|
||||||
|
import { AccessibilityModal } from "@/components/accessibility-modal";
|
||||||
|
import { ThemeInitializer } from "@/components/theme-initializer";
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
children,
|
children,
|
||||||
@ -13,10 +16,14 @@ export default function RootLayout({
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}>) {
|
}>) {
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en" suppressHydrationWarning>
|
||||||
<body className={`font-sans ${GeistSans.variable} ${GeistMono.variable}`}>
|
<body className={`font-sans ${GeistSans.variable} ${GeistMono.variable}`}>
|
||||||
{/* [PASSO 1.2] - Envolvendo a aplicação com o provider */}
|
{/* [PASSO 1.2] - Envolvendo a aplicação com o provider */}
|
||||||
<AppointmentsProvider>{children}</AppointmentsProvider>
|
<ThemeInitializer />
|
||||||
|
<AccessibilityProvider>
|
||||||
|
<AppointmentsProvider>{children}</AppointmentsProvider>
|
||||||
|
<AccessibilityModal />
|
||||||
|
</AccessibilityProvider>
|
||||||
<Analytics />
|
<Analytics />
|
||||||
<Toaster />
|
<Toaster />
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@ -1,247 +1,223 @@
|
|||||||
// Caminho: components/LoginForm.tsx
|
// Caminho: components/LoginForm.tsx
|
||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import type React from "react"
|
import type React from "react";
|
||||||
import { useState } from "react"
|
import { useState } from "react";
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation";
|
||||||
import Link from "next/link"
|
import Link from "next/link";
|
||||||
import Cookies from "js-cookie"
|
import Cookies from "js-cookie";
|
||||||
import { jwtDecode } from "jwt-decode"
|
import { jwtDecode } from "jwt-decode";
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
// Componentes Shadcn UI
|
// Componentes Shadcn UI
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Separator } from "@/components/ui/separator"
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import { apikey } from "@/services/api.mjs";
|
||||||
|
|
||||||
// Hook customizado
|
// Hook customizado
|
||||||
import { useToast } from "@/hooks/use-toast"
|
import { useToast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
// Ícones
|
// Ícones
|
||||||
import { Eye, EyeOff, Mail, Lock, Loader2, UserCheck, Stethoscope, IdCard, Receipt } from "lucide-react"
|
import { Eye, EyeOff, Mail, Lock, Loader2, UserCheck, Stethoscope, IdCard, Receipt } from "lucide-react";
|
||||||
|
|
||||||
interface LoginFormProps {
|
interface LoginFormProps {
|
||||||
title: string
|
title: string;
|
||||||
description: string
|
description: string;
|
||||||
role: "secretary" | "doctor" | "patient" | "admin" | "manager" | "finance"
|
role: "secretary" | "doctor" | "patient" | "admin" | "manager" | "finance";
|
||||||
themeColor: "blue" | "green" | "orange"
|
themeColor: "blue" | "green" | "orange";
|
||||||
redirectPath: string
|
redirectPath: string;
|
||||||
children?: React.ReactNode
|
children?: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FormState {
|
interface FormState {
|
||||||
email: string
|
email: string;
|
||||||
password: string
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Supondo que o payload do seu token tenha esta estrutura
|
// Supondo que o payload do seu token tenha esta estrutura
|
||||||
interface DecodedToken {
|
interface DecodedToken {
|
||||||
name: string
|
name: string;
|
||||||
email: string
|
email: string;
|
||||||
role: string
|
role: string;
|
||||||
exp: number
|
exp: number;
|
||||||
// Adicione outros campos que seu token possa ter
|
// Adicione outros campos que seu token possa ter
|
||||||
}
|
}
|
||||||
|
|
||||||
const themeClasses = {
|
const themeClasses = {
|
||||||
blue: {
|
blue: {
|
||||||
iconBg: "bg-blue-100",
|
iconBg: "bg-blue-100",
|
||||||
iconText: "text-blue-600",
|
iconText: "text-blue-600",
|
||||||
button: "bg-blue-600 hover:bg-blue-700",
|
button: "bg-blue-600 hover:bg-blue-700",
|
||||||
link: "text-blue-600 hover:text-blue-700",
|
link: "text-blue-600 hover:text-blue-700",
|
||||||
focus: "focus:border-blue-500 focus:ring-blue-500",
|
focus: "focus:border-blue-500 focus:ring-blue-500",
|
||||||
},
|
},
|
||||||
green: {
|
green: {
|
||||||
iconBg: "bg-green-100",
|
iconBg: "bg-green-100",
|
||||||
iconText: "text-green-600",
|
iconText: "text-green-600",
|
||||||
button: "bg-green-600 hover:bg-green-700",
|
button: "bg-green-600 hover:bg-green-700",
|
||||||
link: "text-green-600 hover:text-green-700",
|
link: "text-green-600 hover:text-green-700",
|
||||||
focus: "focus:border-green-500 focus:ring-green-500",
|
focus: "focus:border-green-500 focus:ring-green-500",
|
||||||
},
|
},
|
||||||
orange: {
|
orange: {
|
||||||
iconBg: "bg-orange-100",
|
iconBg: "bg-orange-100",
|
||||||
iconText: "text-orange-600",
|
iconText: "text-orange-600",
|
||||||
button: "bg-orange-600 hover:bg-orange-700",
|
button: "bg-orange-600 hover:bg-orange-700",
|
||||||
link: "text-orange-600 hover:text-orange-700",
|
link: "text-orange-600 hover:text-orange-700",
|
||||||
focus: "focus:border-orange-500 focus:ring-orange-500",
|
focus: "focus:border-orange-500 focus:ring-orange-500",
|
||||||
},
|
},
|
||||||
}
|
|
||||||
|
|
||||||
const roleIcons = {
|
|
||||||
secretary: UserCheck,
|
|
||||||
patient: Stethoscope,
|
|
||||||
doctor: Stethoscope,
|
|
||||||
admin: UserCheck,
|
|
||||||
manager: IdCard,
|
|
||||||
finance: Receipt,
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LoginForm({ title, description, role, themeColor, redirectPath, children }: LoginFormProps) {
|
|
||||||
const [form, setForm] = useState<FormState>({ email: "", password: "" })
|
|
||||||
const [showPassword, setShowPassword] = useState(false)
|
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
|
||||||
const router = useRouter()
|
|
||||||
const { toast } = useToast()
|
|
||||||
|
|
||||||
const currentTheme = themeClasses[themeColor]
|
|
||||||
const Icon = roleIcons[role]
|
|
||||||
|
|
||||||
// ==================================================================
|
|
||||||
// AJUSTE PRINCIPAL NA LÓGICA DE LOGIN
|
|
||||||
// ==================================================================
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setIsLoading(true);
|
|
||||||
|
|
||||||
const LOGIN_URL = "https://yuanqfswhberkoevtmfr.supabase.co/auth/v1/token?grant_type=password";
|
|
||||||
const API_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
|
||||||
|
|
||||||
if (!API_KEY) {
|
|
||||||
toast({
|
|
||||||
title: "Erro de Configuração",
|
|
||||||
description: "A chave da API não foi encontrada.",
|
|
||||||
variant: "destructive",
|
|
||||||
});
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(LOGIN_URL, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"apikey": API_KEY,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ email: form.email, password: form.password }),
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(data.error_description || "Credenciais inválidas. Tente novamente.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const accessToken = data.access_token;
|
|
||||||
const user = data.user;
|
|
||||||
|
|
||||||
/* =================== Verificação de Role Desativada Temporariamente =================== */
|
|
||||||
// if (user.user_metadata.role !== role) {
|
|
||||||
// toast({ title: "Acesso Negado", ... });
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
/* ===================================================================================== */
|
|
||||||
|
|
||||||
Cookies.set("access_token", accessToken, { expires: 1, secure: true });
|
|
||||||
localStorage.setItem('user_info', JSON.stringify(user));
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Login bem-sucedido!",
|
|
||||||
description: `Bem-vindo(a), ${user.user_metadata.full_name || 'usuário'}! Redirecionando...`,
|
|
||||||
});
|
|
||||||
|
|
||||||
router.push(redirectPath);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
toast({
|
|
||||||
title: "Erro no Login",
|
|
||||||
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// O JSX do return permanece exatamente o mesmo, preservando seus ajustes.
|
const roleIcons = {
|
||||||
return (
|
secretary: UserCheck,
|
||||||
<Card className="w-full max-w-md shadow-xl border-0 bg-white/80 backdrop-blur-sm">
|
patient: Stethoscope,
|
||||||
<CardHeader className="text-center space-y-4 pb-8">
|
doctor: Stethoscope,
|
||||||
<div className={cn("mx-auto w-16 h-16 rounded-full flex items-center justify-center", currentTheme.iconBg)}>
|
admin: UserCheck,
|
||||||
<Icon className={cn("w-8 h-8", currentTheme.iconText)} />
|
manager: IdCard,
|
||||||
</div>
|
finance: Receipt,
|
||||||
<div>
|
};
|
||||||
<CardTitle className="text-2xl font-bold text-gray-900">{title}</CardTitle>
|
|
||||||
<CardDescription className="text-gray-600 mt-2">{description}</CardDescription>
|
export function LoginForm({ title, description, role, themeColor, redirectPath, children }: LoginFormProps) {
|
||||||
</div>
|
const [form, setForm] = useState<FormState>({ email: "", password: "" });
|
||||||
</CardHeader>
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
<CardContent className="px-8 pb-8">
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
const router = useRouter();
|
||||||
{/* Inputs e Botão */}
|
const { toast } = useToast();
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="email">E-mail</Label>
|
const currentTheme = themeClasses[themeColor];
|
||||||
<div className="relative">
|
const Icon = roleIcons[role];
|
||||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
|
||||||
<Input
|
// ==================================================================
|
||||||
id="email"
|
// AJUSTE PRINCIPAL NA LÓGICA DE LOGIN
|
||||||
type="email"
|
// ==================================================================
|
||||||
placeholder="seu.email@clinica.com"
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
value={form.email}
|
e.preventDefault();
|
||||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
setIsLoading(true);
|
||||||
className={cn("pl-11 h-12 border-slate-200", currentTheme.focus)}
|
|
||||||
required
|
const LOGIN_URL = "https://yuanqfswhberkoevtmfr.supabase.co/auth/v1/token?grant_type=password";
|
||||||
disabled={isLoading}
|
const API_KEY = apikey;
|
||||||
/>
|
|
||||||
</div>
|
if (!API_KEY) {
|
||||||
</div>
|
toast({
|
||||||
<div className="space-y-2">
|
title: "Erro de Configuração",
|
||||||
<Label htmlFor="password">Senha</Label>
|
description: "A chave da API não foi encontrada.",
|
||||||
<div className="relative">
|
});
|
||||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
setIsLoading(false);
|
||||||
<Input
|
return;
|
||||||
id="password"
|
}
|
||||||
type={showPassword ? "text" : "password"}
|
|
||||||
placeholder="Digite sua senha"
|
try {
|
||||||
value={form.password}
|
const response = await fetch(LOGIN_URL, {
|
||||||
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
method: "POST",
|
||||||
className={cn("pl-11 pr-12 h-12 border-slate-200", currentTheme.focus)}
|
headers: {
|
||||||
required
|
"Content-Type": "application/json",
|
||||||
disabled={isLoading}
|
apikey: API_KEY,
|
||||||
/>
|
},
|
||||||
<button
|
body: JSON.stringify({ email: form.email, password: form.password }),
|
||||||
type="button"
|
});
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
|
||||||
className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-gray-400 hover:text-gray-600"
|
const data = await response.json();
|
||||||
disabled={isLoading}
|
|
||||||
>
|
if (!response.ok) {
|
||||||
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
throw new Error(data.error_description || "Credenciais inválidas. Tente novamente.");
|
||||||
</button>
|
}
|
||||||
</div>
|
|
||||||
</div>
|
const accessToken = data.access_token;
|
||||||
<Button type="submit" className={cn("w-full h-12 text-base font-semibold", currentTheme.button)} disabled={isLoading}>
|
const user = data.user;
|
||||||
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
|
||||||
</Button>
|
/* =================== Verificação de Role Desativada Temporariamente =================== */
|
||||||
</form>
|
// if (user.user_metadata.role !== role) {
|
||||||
{/* Conteúdo Extra (children) */}
|
// toast({ title: "Acesso Negado", ... });
|
||||||
<div className="mt-8">
|
// return;
|
||||||
{children ? (
|
// }
|
||||||
<div className="space-y-4">
|
/* ===================================================================================== */
|
||||||
<div className="relative">
|
|
||||||
<div className="absolute inset-0 flex items-center">
|
Cookies.set("access_token", accessToken, { expires: 1, secure: true });
|
||||||
<div className="w-full border-t border-slate-200"></div>
|
localStorage.setItem("user_info", JSON.stringify(user));
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Login bem-sucedido!",
|
||||||
|
description: `Bem-vindo(a), ${user.user_metadata.full_name || "usuário"}! Redirecionando...`,
|
||||||
|
});
|
||||||
|
|
||||||
|
router.push(redirectPath);
|
||||||
|
} catch (error) {
|
||||||
|
toast({
|
||||||
|
title: "Erro no Login",
|
||||||
|
description: error instanceof Error ? error.message : "Ocorreu um erro inesperado.",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// O JSX do return permanece exatamente o mesmo, preservando seus ajustes.
|
||||||
|
return (
|
||||||
|
<Card className="w-full max-w-md shadow-xl border-0 bg-white/80 backdrop-blur-sm">
|
||||||
|
<CardHeader className="text-center space-y-4 pb-8">
|
||||||
|
<div className={cn("mx-auto w-16 h-16 rounded-full flex items-center justify-center", currentTheme.iconBg)}>
|
||||||
|
<Icon className={cn("w-8 h-8", currentTheme.iconText)} />
|
||||||
</div>
|
</div>
|
||||||
<div className="relative flex justify-center text-sm">
|
<div>
|
||||||
<span className="px-4 bg-white text-slate-500">Novo por aqui?</span>
|
<CardTitle className="text-2xl font-bold text-gray-900">{title}</CardTitle>
|
||||||
|
<CardDescription className="text-gray-600 mt-2">{description}</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</CardHeader>
|
||||||
{children}
|
<CardContent className="px-8 pb-8">
|
||||||
</div>
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
) : (
|
{/* Inputs e Botão */}
|
||||||
<>
|
<div className="space-y-2">
|
||||||
<div className="relative">
|
<Label htmlFor="email">E-mail</Label>
|
||||||
<Separator className="my-6" />
|
<div className="relative">
|
||||||
<span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-white px-3 text-sm text-gray-500">ou</span>
|
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
</div>
|
<Input id="email" type="email" placeholder="seu.email@clinica.com" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className={cn("pl-11 h-12 border-slate-200", currentTheme.focus)} required disabled={isLoading} />
|
||||||
<div className="text-center">
|
</div>
|
||||||
<Link href="/" className={cn("text-sm font-medium hover:underline", currentTheme.link)}>
|
</div>
|
||||||
Voltar à página inicial
|
<div className="space-y-2">
|
||||||
</Link>
|
<Label htmlFor="password">Senha</Label>
|
||||||
</div>
|
<div className="relative">
|
||||||
</>
|
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
)}
|
<Input id="password" type={showPassword ? "text" : "password"} placeholder="Digite sua senha" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} className={cn("pl-11 pr-12 h-12 border-slate-200", currentTheme.focus)} required disabled={isLoading} />
|
||||||
</div>
|
<button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-2 top-1/2 -translate-y-1/2 h-8 w-8 p-0 text-gray-400 hover:text-gray-600" disabled={isLoading}>
|
||||||
</CardContent>
|
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
|
||||||
</Card>
|
</button>
|
||||||
)
|
</div>
|
||||||
}
|
</div>
|
||||||
|
<Button type="submit" className={cn("w-full h-12 text-base font-semibold", currentTheme.button)} disabled={isLoading}>
|
||||||
|
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Entrar"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
{/* Conteúdo Extra (children) */}
|
||||||
|
<div className="mt-8">
|
||||||
|
{children ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="relative">
|
||||||
|
<div className="absolute inset-0 flex items-center">
|
||||||
|
<div className="w-full border-t border-slate-200"></div>
|
||||||
|
</div>
|
||||||
|
<div className="relative flex justify-center text-sm">
|
||||||
|
<span className="px-4 bg-white text-slate-500">Novo por aqui?</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="relative">
|
||||||
|
<Separator className="my-6" />
|
||||||
|
<span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-white px-3 text-sm text-gray-500">ou</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-center">
|
||||||
|
<Link href="/" className={cn("text-sm font-medium hover:underline", currentTheme.link)}>
|
||||||
|
Voltar à página inicial
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
144
services/api.mjs
144
services/api.mjs
@ -1,90 +1,84 @@
|
|||||||
|
|
||||||
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
const BASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||||||
const API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
const API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
||||||
|
export const apikey = API_KEY;
|
||||||
var tempToken;
|
var tempToken;
|
||||||
|
|
||||||
export async function login() {
|
export async function login() {
|
||||||
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/auth/v1/token?grant_type=password", {
|
const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/auth/v1/token?grant_type=password", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Prefer: "return=representation",
|
Prefer: "return=representation",
|
||||||
"apikey": API_KEY, // valor fixo
|
apikey: API_KEY, // valor fixo
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ email: "riseup@popcode.com.br", password: "riseup" }),
|
body: JSON.stringify({ email: "riseup@popcode.com.br", password: "riseup" }),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
localStorage.setItem("token", data.access_token);
|
localStorage.setItem("token", data.access_token);
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
let loginPromise = login();
|
let loginPromise = login();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async function request(endpoint, options = {}) {
|
async function request(endpoint, options = {}) {
|
||||||
|
if (loginPromise) {
|
||||||
if (loginPromise) {
|
try {
|
||||||
try {
|
await loginPromise;
|
||||||
await loginPromise;
|
} catch (error) {
|
||||||
} catch (error) {
|
console.error("Falha na autenticação inicial:", error);
|
||||||
console.error("Falha na autenticação inicial:", error);
|
|
||||||
}
|
|
||||||
|
|
||||||
loginPromise = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = localStorage.getItem("token");
|
|
||||||
|
|
||||||
const headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"apikey": API_KEY,
|
|
||||||
...(token ? { "Authorization": `Bearer ${token}` } : {}),
|
|
||||||
...options.headers,
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(`${BASE_URL}${endpoint}`, {
|
|
||||||
...options,
|
|
||||||
headers,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
|
|
||||||
let errorBody = `Status: ${response.status}`;
|
|
||||||
try {
|
|
||||||
const contentType = response.headers.get("content-type");
|
|
||||||
if (contentType && contentType.includes("application/json")) {
|
|
||||||
const jsonError = await response.json();
|
|
||||||
|
|
||||||
errorBody = jsonError.message || JSON.stringify(jsonError);
|
|
||||||
} else {
|
|
||||||
errorBody = await response.text();
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
|
||||||
|
loginPromise = null;
|
||||||
errorBody = `Status: ${response.status} - Falha ao ler corpo do erro.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${errorBody}`);
|
|
||||||
}
|
}
|
||||||
const contentType = response.headers.get("content-type");
|
|
||||||
if (response.status === 204 || (contentType && !contentType.includes("application/json")) || !contentType) {
|
const token = localStorage.getItem("token");
|
||||||
return {};
|
|
||||||
|
const headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
apikey: API_KEY,
|
||||||
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||||
|
...options.headers,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${BASE_URL}${endpoint}`, {
|
||||||
|
...options,
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
let errorBody = `Status: ${response.status}`;
|
||||||
|
try {
|
||||||
|
const contentType = response.headers.get("content-type");
|
||||||
|
if (contentType && contentType.includes("application/json")) {
|
||||||
|
const jsonError = await response.json();
|
||||||
|
|
||||||
|
errorBody = jsonError.message || JSON.stringify(jsonError);
|
||||||
|
} else {
|
||||||
|
errorBody = await response.text();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
errorBody = `Status: ${response.status} - Falha ao ler corpo do erro.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Erro HTTP: ${response.status} - Detalhes: ${errorBody}`);
|
||||||
|
}
|
||||||
|
const contentType = response.headers.get("content-type");
|
||||||
|
if (response.status === 204 || (contentType && !contentType.includes("application/json")) || !contentType) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro na requisição:", error);
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
return await response.json();
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erro na requisição:", error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
export const api = {
|
export const api = {
|
||||||
get: (endpoint) => request(endpoint, { method: "GET" }),
|
get: (endpoint) => request(endpoint, { method: "GET" }),
|
||||||
post: (endpoint, data) => request(endpoint, { method: "POST", body: JSON.stringify(data) }),
|
post: (endpoint, data) => request(endpoint, { method: "POST", body: JSON.stringify(data) }),
|
||||||
patch: (endpoint, data) => request(endpoint, { method: "PATCH", body: JSON.stringify(data) }),
|
patch: (endpoint, data) => request(endpoint, { method: "PATCH", body: JSON.stringify(data) }),
|
||||||
delete: (endpoint) => request(endpoint, { method: "DELETE" }),
|
delete: (endpoint) => request(endpoint, { method: "DELETE" }),
|
||||||
};
|
};
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user