diff --git a/src/components/auth/LoginForm.tsx b/src/components/auth/LoginForm.tsx
index de81849..301f043 100644
--- a/src/components/auth/LoginForm.tsx
+++ b/src/components/auth/LoginForm.tsx
@@ -37,11 +37,27 @@ const LoginForm = ({ isLoading, setIsLoading }: LoginFormProps) => {
// Se encontrou um usuário válido
if (data) {
+ // Fetch user details to get the WhatsApp number
+ const { data: userData, error: userError } = await supabase
+ .from('usuarios')
+ .select('nome, email, whatsapp')
+ .eq('id', data)
+ .single();
+
+ if (userError) {
+ console.error("Erro ao buscar dados do usuário:", userError);
+ }
+
// Armazenar informações de sessão
localStorage.setItem('autenticado', 'true');
localStorage.setItem('userId', data);
localStorage.setItem('userEmail', loginEmail);
+ if (userData) {
+ localStorage.setItem('userName', userData.nome);
+ localStorage.setItem('userWhatsapp', userData.whatsapp);
+ }
+
toast({
title: "Login realizado com sucesso",
description: "Bem-vindo de volta!"
diff --git a/src/components/auth/RegisterForm.tsx b/src/components/auth/RegisterForm.tsx
index cf307d4..dd1a7da 100644
--- a/src/components/auth/RegisterForm.tsx
+++ b/src/components/auth/RegisterForm.tsx
@@ -29,7 +29,7 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => {
e.preventDefault();
// Validações básicas
- if (!nome || !email || !senha) {
+ if (!nome || !email || !senha || !whatsapp) {
toast({
title: "Campos obrigatórios",
description: "Por favor preencha todos os campos obrigatórios",
@@ -55,7 +55,8 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => {
nome,
empresa,
email,
- senha
+ senha,
+ whatsapp
});
if (error) throw error;
@@ -92,9 +93,10 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => {
localStorage.setItem('userId', loginData);
localStorage.setItem('userEmail', email);
localStorage.setItem('userName', nome);
+ localStorage.setItem('userWhatsapp', whatsapp);
- // Redirecionamento para o dashboard após cadastro bem-sucedido
- navigate('/dashboard');
+ // Redirecionamento para a página principal após cadastro bem-sucedido
+ navigate('/');
}
}
} catch (error: any) {
@@ -149,6 +151,7 @@ const RegisterForm = ({ isLoading, setIsLoading }: RegisterFormProps) => {
value={whatsapp}
onChange={(e) => setWhatsapp(e.target.value)}
disabled={isLoading}
+ required
/>
diff --git a/src/integrations/supabase/types.ts b/src/integrations/supabase/types.ts
index b65977b..704fd77 100644
--- a/src/integrations/supabase/types.ts
+++ b/src/integrations/supabase/types.ts
@@ -295,6 +295,7 @@ export type Database = {
id: string
nome: string
senha: string
+ whatsapp: string
}
Insert: {
created_at?: string
@@ -303,6 +304,7 @@ export type Database = {
id?: string
nome: string
senha: string
+ whatsapp: string
}
Update: {
created_at?: string
@@ -311,6 +313,7 @@ export type Database = {
id?: string
nome?: string
senha?: string
+ whatsapp?: string
}
Relationships: []
}
diff --git a/supabase/config.toml b/supabase/config.toml
index 46af35f..7ba7ad5 100644
--- a/supabase/config.toml
+++ b/supabase/config.toml
@@ -1 +1,79 @@
-project_id = "tnurlgbvfsxwqgwxamni"
\ No newline at end of file
+
+# A string used to distinguish different Supabase projects on the same host. Defaults to the working
+# directory name when running `supabase init`.
+project_id = "tnurlgbvfsxwqgwxamni"
+
+[api]
+# Port to use for the API URL.
+port = 54321
+# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
+# endpoints. public and storage are always included.
+schemas = ["public", "storage", "graphql_public"]
+# Extra schemas to add to the search_path of every request. public is always included.
+extra_search_path = ["public", "extensions"]
+# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
+# for accidental or malicious requests.
+max_rows = 1000
+
+[db]
+# Port to use for the local database URL.
+port = 54322
+# The database major version to use. This has to be the same as your remote database's. Run `SHOW
+# server_version;` on the remote database to check.
+major_version = 15
+
+[studio]
+# Port to use for Supabase Studio.
+port = 54323
+
+# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
+# are monitored, and you can view the emails that would have been sent from the web interface.
+[inbucket]
+# Port to use for the email testing server web interface.
+port = 54324
+smtp_port = 54325
+pop3_port = 54326
+
+[storage]
+# The maximum file size allowed (e.g. "5MB", "500KB").
+file_size_limit = "50MiB"
+
+[auth]
+# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
+# in emails.
+site_url = "http://localhost:3000"
+# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
+additional_redirect_urls = ["https://localhost:3000"]
+# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 seconds (one
+# week).
+jwt_expiry = 3600
+# Allow/disallow new user signups to your project.
+enable_signup = true
+# If disabled, the config sender_name, sender_email, forgot_password_template, invite_template and confirmation_template are used instead.
+enable_confirmations = false
+
+[auth.email]
+# Allow/disallow new user signups via email to your project.
+enable_signup = true
+# If enabled, a user will be required to confirm any email change on both the old, and new email
+# addresses. If disabled, only the new email is required to confirm.
+double_confirm_changes = true
+# If enabled, users need to confirm their email address before signing in.
+enable_confirmations = false
+
+# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
+# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin`, `notion`, `twitch`,
+# `twitter`, `slack`, `spotify`, `workos`, `zoom`.
+[auth.external.apple]
+enabled = false
+client_id = ""
+secret = ""
+# Overrides the default auth redirectUrl.
+redirect_uri = ""
+# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
+# or any other third-party OIDC providers.
+url = ""
+
+[functions]
+[functions.update-register-function]
+verify_jwt = true
diff --git a/supabase/functions/update-register-function-sql/index.ts b/supabase/functions/update-register-function-sql/index.ts
new file mode 100644
index 0000000..911718e
--- /dev/null
+++ b/supabase/functions/update-register-function-sql/index.ts
@@ -0,0 +1,26 @@
+
+// This is a temporary solution to update the database function
+// You can run this SQL in the Supabase SQL Editor:
+//
+// CREATE OR REPLACE FUNCTION public.registrar_usuario(
+// nome text,
+// empresa text,
+// email text,
+// senha text,
+// whatsapp text
+// ) RETURNS uuid
+// LANGUAGE plpgsql
+// SECURITY DEFINER
+// AS $function$
+// DECLARE
+// novo_usuario_id UUID;
+// BEGIN
+// -- Inserir novo usuário com senha hash
+// INSERT INTO public.usuarios (nome, empresa, email, senha, whatsapp)
+// VALUES (nome, empresa, email, crypt(senha, gen_salt('bf')), whatsapp)
+// RETURNING id INTO novo_usuario_id;
+//
+// -- Retorna o ID do usuário criado sem criar tabela individual
+// RETURN novo_usuario_id;
+// END;
+// $function$
diff --git a/supabase/functions/update-register-function/index.ts b/supabase/functions/update-register-function/index.ts
new file mode 100644
index 0000000..08d0ae1
--- /dev/null
+++ b/supabase/functions/update-register-function/index.ts
@@ -0,0 +1,49 @@
+
+// This is an Edge Function that will update the registrar_usuario database function
+// to include the WhatsApp parameter
+
+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',
+};
+
+serve(async (req) => {
+ // Handle CORS preflight requests
+ if (req.method === 'OPTIONS') {
+ return new Response(null, { headers: corsHeaders });
+ }
+
+ try {
+ // Create a Supabase client with the Auth context of the logged in user
+ const supabaseClient = createClient(
+ // Supabase API URL - env var exported by default.
+ Deno.env.get('SUPABASE_URL') ?? '',
+ // Supabase API ANON KEY - env var exported by default.
+ Deno.env.get('SUPABASE_ANON_KEY') ?? '',
+ // Create client with Auth context of the user that called the function.
+ {
+ global: {
+ headers: { Authorization: req.headers.get('Authorization')! },
+ },
+ }
+ );
+
+ // Update the registrar_usuario function to include the whatsapp parameter
+ const { data, error } = await supabaseClient.rpc('update_register_function');
+
+ if (error) throw error;
+
+ return new Response(JSON.stringify({ success: true, data }), {
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ status: 200,
+ });
+ } catch (error) {
+ return new Response(JSON.stringify({ error: error.message }), {
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ status: 400,
+ });
+ }
+});