PageSourceSearch

https://www.mindmatch.pt/assets/AuthRouteGuard-DpsPeq6D.js

js mindmatch.pt collected 2026-10-06 07:21:39 UTC 19,367 bytes, 1 lines download raw bytes

1import{b8 as ot,bY as a,bI as e,o,ca as s,c7 as d,bp as nt,bN as u,cs as ct,cc as W,co as lt,a1 as dt,bO as ge,aB as ve,bL as mt,bx as ut,cC as pt}from"./index-Cr7AdIBs.js";import{C as Y,c as Z,d as ft,b as ht,a as gt}from"./card-YCIWu6CA.js";import{I as y}from"./input-JOAwrtew.js";import{L as w}from"./label-BUHxPuh5.js";import{M as ye}from"./mail-CAYzCdF8.js";import{u as vt,C as xt}from"./useTermsAcceptance-Ca_UJuyg.js";import{V as jt}from"./Verify2FADialog-neobR5K7.js";import{A as xe}from"./arrow-left-B0zK2sBl.js";import{E as K}from"./eye-off-BChhaidC.js";import{E as Q}from"./eye-CcnbeK8Z.js";import{L as je}from"./lock-BkzdQ1Vb.js";import{U as yt}from"./user-D7ORoCSN.js";import wt from"./NotFound-DxRM0Wzd.js";import"./input-otp-CckaRwfV.js";import"./refresh-cw-CBCjVXfj.js";import"./shield-CIEQM-ws.js";import"./smartphone-Ct1KtD_4.js";const Nt=ot("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]),bt=({email:c,role:g,onVerified:v})=>{const[l,f]=a.useState(""),[x,j]=a.useState(!1),[r,h]=a.useState(60),[b,T]=a.useState(!1);a.useEffect(()=>{if(r>0){const n=setTimeout(()=>{h(r-1)},1e3);return()=>clearTimeout(n)}else T(!0)},[r]);const C=async()=>{if(!l||l.length!==6){s({title:"Código inválido",description:"Por favor insere um código válido de 6 dígitos.",variant:"warning"});return}j(!0);try{const{error:n}=await d.auth.verifyOtp({email:c,token:l,type:"signup"});if(n)s({title:"Código de verificação inválido",description:"O código introduzido está incorreto ou expirou. Tenta novamente.",variant:"destructive"});else{const{data:{user:p}}=await d.auth.getUser();if(p){if(g==="patient"){const{error:S}=await d.from("profiles").upsert({id:p.id,email:p.email,first_name:"",last_name:"",phone_number:"",tax_id_number:"",postal_code:"",password_set:!0,timezone:nt()},{onConflict:"id"});if(S){try{await d.functions.invoke("delete-user",{body:{userId:p.id}})}catch(P){u.error("Failed to delete user after profile insert error:",P)}await d.auth.signOut(),s({title:"Erro ao criar perfil",description:"A tua conta foi removida. Tenta registar-te novamente.",variant:"destructive"});return}const{error:I}=await d.from("patient_profiles").upsert({id:p.id},{onConflict:"id",ignoreDuplicates:!0});if(I){try{await d.functions.invoke("delete-user",{body:{userId:p.id}})}catch(P){u.error("Failed to delete user after patient_profiles insert error:",P)}await d.auth.signOut(),s({title:"Erro ao criar perfil",description:"Ocorreu um erro ao criar o perfil. A tua conta foi removida.",variant:"destructive"});return}}}else{s({title:"Erro ao criar usuário",description:"Utilizador não encontrado. Tenta novamente.",variant:"destructive"});return}s({title:"Email verificado!",description:"O teu email foi verificado com sucesso.",variant:"success"}),v()}}catch(n){u.error("Verification error:",n),s({title:"Erro ao verificar código",description:"Não foi possível verificar o código. Tenta novamente.",variant:"destructive"})}finally{j(!1)}},z=async()=>{if(b)try{const{error:n}=await d.auth.resend({type:"signup",email:c});n?s({title:"Erro ao reenviar código",description:"Não foi possível reenviar o código. Tenta novamente.",variant:"destructive"}):(s({title:"Código reenviado!",description:"Verifica o teu email para obteres o novo código.",variant:"success"}),h(60),T(!1))}catch(n){u.error("Resend error:",n),s({title:"Erro ao reenviar código",description:"Não foi possível reenviar o código. Tenta novamente.",variant:"destructive"})}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-16 h-16 bg-gradient-hero rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ye,{className:"w-8 h-8 text-primary-foreground"})}),e.jsx("h3",{className:"text-2xl font-semibold",children:"Verificar Email"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Enviámos um código de verificação para"}
1),e.jsx("p",{className:"text-foreground font-medium mt-1",children:c})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{htmlFor:"verification-code",children:"Código de Verificação"}),e.jsx(y,{id:"verification-code",type:"text",placeholder:"000000",maxLength:6,value:l,onChange:n=>f(n.target.value.replace(/\D/g,"")),disabled:x,className:"text-center text-2xl tracking-widest"})]}),e.jsx(o,{onClick:C,className:"w-full",size:"lg",disabled:x||l.length!==6,children:x?"A verificar...":"Verificar Email"}),e.jsx(o,{onClick:z,variant:"ghost",className:"w-full",type:"button",disabled:!b,children:b?"Reenviar código":`Reenviar código (${r}s)`})]})]})},Ct=()=>{const c=ct(),{user:g,signIn:v,signUp:l,signUpConflict:f,clearSignUpConflict:x,refreshProfile:j}=W(),[r,h]=a.useState(!1),[b,T]=a.useState(!1),[C,z]=a.useState(!1),[n,p]=a.useState(!1),[S,I]=a.useState(""),[P,we]=a.useState(""),[X,Ne]=a.useState("patient"),[D,ee]=a.useState(!1),[te,M]=a.useState(null),[F,k]=a.useState(null),[be,ae]=a.useState(null),[_,se]=a.useState(null),[Ce,N]=a.useState(null),[Se,re]=a.useState(null),[Pe,ie]=a.useState(!1),{verifyMfaLogin:ke,triggerSmsChallenge:oe,signOut:Ee,mfaPending:ne,resolvePendingMfaChallenge:Te}=W(),ce=t=>{M(t.factorType??"totp"),re(t.maskedPhone??null),t.factorType==="choice"?(ae(t.totpFactorId??null),se(t.phoneFactorId??null),k(null),N(null)):(k(t.factorId??null),N(t.challengeId??null)),ee(!0)};a.useEffect(()=>{if(!ne||D)return;let t=!0;return(async()=>{try{const i=await Te();t&&i&&ce(i)}catch(i){u.error("Failed to resume MFA challenge:",i)}})(),()=>{t=!1}},[ne,D]);const q=lt(),$=new URLSearchParams(q.search),E=$.get("role"),Ie=$.get("type"),le=$.get("redirect"),[B,Me]=a.useState(""),[de,Fe]=a.useState(""),[A,Ae]=a.useState(""),[R,Re]=a.useState(""),[me,Ue]=a.useState(""),[U,J]=a.useState(E||"patient"),[G,H]=a.useState(Ie==="signup"?"signup":"signin"),{termsAccepted:ue,privacyAccepted:pe,newsletterAccepted:Ve,setNewsletterAccepted:Oe,acceptedDocumentTypes:Le,termsDialogOpen:ze,setTermsDialogOpen:fe,privacyDialogOpen:De,setPrivacyDialogOpen:he,termsSeen:_e,privacySeen:qe,toggleTermsAccepted:$e,togglePrivacyAccepted:Be,termsTitle:Je,termsSections:Ge,privacySections:He,handleTermsAccept:Ye,handlePrivacyAccept:Ze}=vt(),[V,Ke]=a.useState(!1),[O,Qe]=a.useState(!1),[L,We]=a.useState(!1);a.useEffect(()=>{},[g,C,c]),a.useEffect(()=>{const t=new URLSearchParams(q.search),i=t.get("type"),m=t.get("role");H(i==="signup"?"signup":"signin"),m&&J(m)},[q.search]);const Xe=async t=>{t.preventDefault(),h(!0);try{const i=await v(B,de,E||void 0,le||void 0);i&&i.mfaRequired&&ce(i)}catch(i){u.error("Sign in error:",i),s({title:"Erro ao fazer login",description:"Não foi possível iniciar sessão. Tenta novamente.",variant:"destructive"})}finally{h(!1)}},et=async t=>{if(t==="totp")k(be),N(null),M("totp");else{if(!_)return;const{challengeId:i,error:m}=await oe(_);if(m){s({title:"Erro",description:"Não foi possível enviar o SMS. Tenta novamente.",variant:"destructive"});return}k(_),N(i??null),M("phone")}},tt=async()=>{if(!F)return;const{challengeId:t,error:i}=await oe(F);if(i){s({title:"Erro",description:"Não foi possível reenviar o SMS.",variant:"destructive"});return}N(t??null),s({description:"Novo código enviado por SMS."})},at=async t=>{if(F){ie(!0);try{const{error:i}=await ke(F,t,E||void 0,le||void 0,Ce||void 0);i&&(s({title:"Erro na verificação",description:"Código incorreto. Tenta novamente.",variant:"destructive"}),ie(!1))}catch(i){u.error("MFA verification error:",i),s({title:"Erro",description:"Não foi possível verificar o código.",variant:"destructive"})}}},st=()=>{ee(!1),M(null),k(null),ae(null),se(null),N(null),re(null),Ee()},rt=async t=>{if(t.preventDefault(),!/^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]).{8,}$/.test(R)){s({title:"Password insegura",description:"A password deve ter pelo menos 8 caracteres, incluindo uma letra maiúscula, um número e um símbolo.",variant:"destructive"});return}if(u.log("Sign up attempted with email:",A),u.log("handleSignUp called"),!ue||!pe){s({title:"Termos não aceites",description:"É necessário ace
1itar os Termos e a Política de Privacidade para continuar.",variant:"warning"});return}if(R!==me){s({title:"Passwords diferentes",description:"As duas passwords introduzidas não coincidem. Verifica e tenta novamente.",variant:"destructive"});return}h(!0);try{const{error:m}=await l(A,R,U);m?f?s({title:"Email já registado",description:"Já existe uma conta com este email. Verifica as opções abaixo.",variant:"destructive"}):m.message?.includes("already")||m.message?.includes("registado")?s({title:"Email já registado",description:"Já existe uma conta com este endereço de email.",variant:"destructive"}):s({title:"Erro ao criar conta",description:m.message||"Não foi possível criar a conta. Tenta novamente.",variant:"destructive"}):(we(A),Ne(U),z(!0),s({title:"Código enviado!",description:"Verifica a tua caixa de entrada para confirmar o email.",variant:"success"}))}catch(m){u.error("Sign up error:",m),s({title:"Erro ao criar conta",description:"Ocorreu um erro inesperado. Tenta novamente.",variant:"destructive"})}finally{h(!1)}},it=async()=>{T(!0);try{const{data:{user:t}}=await d.auth.getUser();t&&(await mt(t.id,Le()),await j())}catch(t){u.error("Consent logging failed:",t)}if(X==="therapist")c("/therapist/registration");else{const{data:{user:t}}=await d.auth.getUser();if(t){const i=await ut(t.id);c(i)}else c("/patient/onboarding")}};return b?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(dt,{className:"w-8 h-8 animate-spin text-primary"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/5 flex flex-col p-4 md:items-center md:justify-center",children:[e.jsxs("header",{className:"w-full max-w-md mx-auto flex items-center gap-2 shrink-0 md:hidden",children:[e.jsxs(o,{variant:"ghost",size:"sm",className:"-ml-2 shrink-0 text-muted-foreground hover:text-foreground",onClick:()=>c("/"),children:[e.jsx(xe,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Voltar"})]}),e.jsx("img",{src:ge,alt:"MindMatch",className:"h-10 w-auto mx-auto"}),e.jsx("div",{className:"w-9 shrink-0","aria-hidden":!0})]}),e.jsxs(o,{variant:"ghost",className:"hidden md:inline-flex absolute top-4 left-4 text-muted-foreground hover:text-foreground",onClick:()=>c("/"),children:[e.jsx(xe,{className:"mr-2 h-4 w-4"}),"Voltar"]}),e.jsxs("div",{className:"flex-1 flex flex-col justify-center w-full max-w-md mx-auto space-y-4 py-4 md:flex-none md:block md:space-y-8 md:py-0 animate-fade-in",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("img",{src:ge,alt:"MindMatch",className:"hidden md:block h-20 w-auto mx-auto mb-8"}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold text-foreground",children:E==="therapist"?"Área do Profissional":"Área do Paciente"}),e.jsx("p",{className:"hidden md:block text-muted-foreground mt-2",children:G==="signin"?"Acede à tua conta MindMatch":"Cria uma nova conta"})]}),e.jsxs(Y,{children:[e.jsxs(Z,{className:"p-4 md:p-6",children:[e.jsx(ft,{children:G==="signin"?"Entrar":"Registar"}),e.jsx(ht,{children:C?"Confirma o código enviado para o teu email":""})]}),e.jsx(gt,{className:"p-4 pt-0 md:p-6 md:pt-0",children:C?e.jsx(bt,{email:P,role:X,onVerified:it}):G==="signin"?e.jsx(e.Fragment,{children:D?e.jsx(jt,{inline:!0,factorType:te??"totp",maskedPhone:Se??void 0,onVerify:at,onCancel:st,onSelectMethod:et,onResendSms:te==="phone"?tt:void 0,isLoading:Pe}):e.jsxs(e.Fragment,{children:[e.jsxs("form",{onSubmit:Xe,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{htmlFor:"signin-email",children:"Email"}),e.jsx(y,{id:"signin-email",type:"email",value:B,onChange:t=>Me(t.target.value),placeholder:"[email protected]",required:!0,disabled:r})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{htmlFor:"signin-password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(y,{id:"signin-password",type:V?"text":"password",value:de,onChange:t=>Fe(t.target.value),placeholder:"••••••••",className:"pr-10",autoComplete:"current-password",required:!0,disabled:r}),e.jsx(o,{type:"button",variant:"ghost",size:"sm","aria-label":V?"Ocultar palavra-passe":"Mostrar palavra-passe",className:"absolute right-0 top-0 h-full px-3 text-muted-foreground hover:bg-muted/50 hover:text-muted-foreground rounded-full",onClick:()=>Ke(!V),disabled:r,children:V?e.jsx(K,{className:"h-4 w-4"}):e.jsx(Q,{className:"h-4 w-4"})})]})]}),!n&&e.jsx("div",{className:"text-right",children:e.jsx(o,{type:"button",variant:"link",className:"p-0 h-auto text-sm text-muted-foreground hover:text-primary",onClick:()=>{p(!0),I(B)},children:"Esqueci-me da password"})}),n&&e.jsxs("div",{className:"rounded-md border p-4 space-y-3 bg-muted/50",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Introduz o teu email para receber um link de recuperação."}),e.jsx(y,{type:"email",placeholder:"[email protected]",value:S,onChange:t=>I(t.target.value),disabled:r}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(o,{type:"button",variant:"outline",size:"sm",onClick:()=>p(!1),children:"Cancelar"}),e.jsx(o,{type:"button",size:"sm",disabled:r||!S,onClick:async()=>{h(!0);const{error:t}=await d.auth.resetPasswordForEmail(S,{redirectTo:`${window.location.origin}/reset-password`});h(!1),t?s({title:"Erro ao enviar email",description:t.message||"Não foi possível enviar o email de recuperação. Tenta novamente.",variant:"destructive"}):(s({title:"Email enviado!",description:"Verifica a tua caixa de entrada para redefinir a palavra-passe.",variant:"success"}),p(!1))},children:r?"A enviar...":"Enviar"})]})]}),e.jsx(o,{type:"submit",className:"w-full",disabled:r,children:r?"A entrar...":"Entrar"})]}),e.jsxs("div",{className:"mt-4 text-center text-sm text-muted-foreground",children:["Não tem conta?"," ",e.jsx(o,{variant:"link",className:"p-0 h-auto text-primary",onClick:()=>H("signup"),children:"Registar-me"})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("form",{onSubmit:rt,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{htmlFor:"signup-email",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(y,{id:"signup-email",type:"email",placeholder:"[email protected]",className:"pl-10",value:A,onChange:t=>Ae(t.target.value),required:!0,disabled:r})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{htmlFor:"signup-password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(je,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(y,{id:"signup-password",type:O?"text":"password",placeholder:"••••••••",className:"pl-10 pr-10",value:R,onChange:t=>Re(t.target.value),autoComplete:"new-password",required:!0,disabled:r}),e.jsx(o,{type:"button",variant:"ghost",size:"sm","aria-label":O?"Ocultar palavra-passe":"Mostrar palavra-passe",className:"absolute right-0 top-0 h-full px-3 text-muted-foreground hover:bg-muted/50 hover:text-muted-foreground rounded-full",onClick:()=>Qe(!O),disabled:r,children:O?e.jsx(K,{className:"h-4 w-4"}):e.jsx(Q,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{htmlFor:"signup-confirm-password",children:"Confirmar Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(je,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(y,{id:"signup-confirm-password",type:L?"text":"password",placeholder:"••••••••",className:"pl-10 pr-10",value:me,onChange:t=>Ue(t.target.value),autoComplete:"new-password",required:!0,disabled:r}),e.jsx(o,{type:"button",variant:"ghost",size:"sm","aria-label":L?"Ocultar palavra-passe":"Mostrar palavra-passe",className:"absolute right-0 top-0 h-full px-3 text-muted-foreground hover:bg-muted/50 hover:text-muted-foreground rounded-full",onClick:()=>We(!L),disabled:r,children:L?e.jsx(K,{className:"h-4 w-4"}):e.jsx(Q,{className:"h-4 w-4"})})]})]}),e.jsx(xt,{idPrefix:"signup",termsAccepted:ue,privacyAccepted:pe,newsletterAccepted:Ve,termsSeen:_e,privacySeen:qe,onToggleTerms:$e,onTogglePrivacy:Be,onToggleNewsletter:Oe,onOpenTerms:()=>fe(!0),onOpenPrivacy:()=>he(!0)}),!E&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(w,{children:"Tipo de Conta"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Y,{className:`curs
1or-pointer transition-colors ${U==="patient"?"border-primary":""}`,onClick:()=>J("patient"),children:e.jsx(Z,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(yt,{className:"w-6 h-6"}),e.jsx("span",{className:"text-sm font-medium",children:"Paciente"})]})})}),e.jsx(Y,{className:`cursor-pointer transition-colors ${U==="therapist"?"border-primary":""}`,onClick:()=>J("therapist"),children:e.jsx(Z,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Nt,{className:"w-6 h-6"}),e.jsx("span",{className:"text-sm font-medium",children:"Psicólogo"})]})})})]})]}),e.jsx(o,{type:"submit",className:"w-full",disabled:r,children:r?"A criar conta...":"Criar Conta"}),f&&e.jsxs("div",{className:"mt-4 rounded-md border border-destructive/50 bg-destructive/10 p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Já existe uma conta com este email."}),e.jsxs("p",{className:"mb-3",children:["Faz login antes de continuar como"," ",e.jsx("span",{className:"font-semibold",children:f.attemptedRole==="therapist"?"Psicólogo":"Paciente"}),"."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(o,{type:"button",variant:"destructive",onClick:x,children:"Fechar"}),e.jsxs(o,{type:"button",onClick:()=>{x(),c(`/auth?type=login&role=${f.attemptedRole}`)},children:["Ir para Login"," ",f.attemptedRole==="therapist"?"Psicólogo":"Paciente"]})]})]})]}),e.jsxs("div",{className:"mt-4 text-center text-sm text-muted-foreground",children:["Já tem conta?"," ",e.jsx(o,{variant:"link",className:"p-0 h-auto text-primary",onClick:()=>H("signin"),children:"Ir para login"})]})]})})]})]})]}),e.jsx(ve,{open:ze,onClose:()=>fe(!1),onAccept:Ye,title:Je,sections:Ge}),e.jsx(ve,{open:De,onClose:()=>he(!1),onAccept:Ze,title:"Política de Privacidade",sections:He})]})};function qt(){const{mfaPending:c}=W(),[g]=pt(),v=(g.get("type")||"").toLowerCase(),l=(g.get("role")||"").toLowerCase(),f=new Set(["login","signup"]),x=new Set(["therapist","patient"]),j=v&&l&&f.has(v)&&x.has(l);return a.useEffect(()=>{if(j)try{localStorage.setItem("auth_type",v),localStorage.setItem("auth_role",l);const r=g.get("redirect");r?localStorage.setItem("auth_redirect",r):localStorage.removeItem("auth_redirect")}catch{}},[j,v,l,g]),!j&&!c?e.jsx(wt,{}):e.jsx(Ct,{})}export{qt as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.