feat: implement email verification and password reset features
- Add EmailTokenService for handling email verification and password reset tokens. - Create EmailService for sending verification and reset emails via SMTP. - Update AuthService to handle email verification status during login. - Modify user registration to redirect to a check email screen instead of issuing a token. - Implement resend verification email functionality. - Add deep link handling for email verification and password reset in the mobile app. - Update mobile app routes and components to support new email verification flow. - Enhance error handling for unverified emails during login attempts. - Update configuration to include SMTP settings for email service.
This commit is contained in:
+120
-7
@@ -85,11 +85,12 @@ mobile/
|
||||
│ │ ├── login.tsx ← G3-0
|
||||
│ │ ├── register.tsx ← IX-0
|
||||
│ │ ├── forgot-password.tsx ← L2-0
|
||||
│ │ ├── verify-email.tsx ← RU-0
|
||||
│ │ ├── check-email.tsx ← RU-0 Tela informativa pós-cadastro ("Confirme seu e-mail")
|
||||
│ │ ├── reset-password.tsx ← 117-0
|
||||
│ │ └── password-reset-done.tsx ← 135-0
|
||||
│ ├── filament/
|
||||
│ │ └── [id].tsx ← Deep link handler: redireciona meowspool://filament/{id} → /(app)/inventory/{id}
|
||||
│ ├── verify-email.tsx ← Deep link handler: meowspool://verify-email?token=xxx → chama API e exibe resultado
|
||||
│ └── (app)/
|
||||
│ ├── _layout.tsx ← Stack autenticado
|
||||
│ ├── (tabs)/
|
||||
@@ -138,7 +139,7 @@ mobile/
|
||||
│ ├── preset/
|
||||
│ │ └── PresetUseCases.ts ← List, Create, Update, Delete
|
||||
│ ├── auth/
|
||||
│ │ └── AuthUseCases.ts ← Login, Register, Google, Logout, etc.
|
||||
│ │ └── AuthUseCases.ts ← Login, Register, Google, Logout, ForgotPassword, ResendVerification, VerifyEmail, ResetPassword
|
||||
│ └── nfc/
|
||||
│ ├── ReadNFCTagUseCase.ts ← lê URI, valida schema meowspool://, extrai filament ID
|
||||
│ └── WriteNFCTagUseCase.ts ← monta meowspool://filament/{id} e grava na tag
|
||||
@@ -222,12 +223,22 @@ Arquivo: `src/shared/theme.ts`
|
||||
|
||||
### Deep links
|
||||
|
||||
- Scheme: `meowspool://`
|
||||
- Filamento: `meowspool://filament/<id>` → `/(app)/inventory/<id>` (singular, alinhado com backend)
|
||||
- O redirecionamento é feito pela rota `app/filament/[id].tsx` com `<Redirect>` do expo-router — garante que o deep link abrido externamente (QR Code, NFC, link compartilhado) sempre chegue na tela correta
|
||||
- Scheme: `meowspool://` (configurado em `app.json` como `scheme: "meowspool"`)
|
||||
- **Filamento**: `meowspool://filament/<id>` → `/(app)/inventory/<id>`
|
||||
- Handler: `app/filament/[id].tsx` com `<Redirect>` do expo-router
|
||||
- Mesmo link usado em QR Code, NFC e links compartilhados
|
||||
- **Verificação de e-mail**: `meowspool://verify-email?token=<token>`
|
||||
- Handler: `app/verify-email.tsx` — chama `VerifyEmailUseCase.execute(token)` automaticamente
|
||||
- Exibe estados: carregando → sucesso → erro (token inválido/expirado)
|
||||
- Redireciona para `/(auth)/login` ao concluir
|
||||
- **Reset de senha**: `meowspool://reset-password?token=<token>`
|
||||
- Handler: `app/(auth)/reset-password.tsx` — lê `token` via `useLocalSearchParams`
|
||||
- O scanner (`scanner.tsx`) faz match via `/meowspool:\/\/filament\/([^/]+)/` e navega para `/(app)/inventory/<id>`
|
||||
- O QR Code de cada filamento exibe `meowspool://filament/<id>` usando `react-native-qrcode-svg`
|
||||
- As tags NFC NTAG215 gravam a mesma URI `meowspool://filament/<id>` como NDEF URI record — mesmo deep link, infraestrutura compartilhada
|
||||
- As tags NFC NTAG215 gravam a URI `meowspool://filament/<id>` como NDEF URI record
|
||||
|
||||
> **Links de e-mail**: o backend gera links `https://meowspool.felipecncloud.com/api/v1/verify-email?token=xxx` (aceitos por clientes de e-mail). O backend redireciona (302) para `meowspool://verify-email?token=xxx`. O OS reconhece o scheme e abre o app.
|
||||
> - `APP_BASE_URL=https://meowspool.felipecncloud.com/api/v1`
|
||||
> - `APP_SCHEME=meowspool`
|
||||
|
||||
---
|
||||
|
||||
@@ -309,6 +320,7 @@ Base: `EXPO_PUBLIC_API_URL` (padrão: `http://localhost:3000/api/v1`)
|
||||
| POST | `/auth/google` | OAuth Google |
|
||||
| POST | `/auth/refresh` | Refresh token |
|
||||
| POST | `/auth/logout` | Logout |
|
||||
| POST | `/auth/resend-verification` | Reenviar e-mail de verificação |
|
||||
| POST | `/auth/forgot-password` | Solicitar reset de senha |
|
||||
| POST | `/auth/reset-password` | Confirmar reset com token |
|
||||
| POST | `/auth/verify-email` | Verificar e-mail com código |
|
||||
@@ -357,6 +369,7 @@ Base: `EXPO_PUBLIC_API_URL` (padrão: `http://localhost:3000/api/v1`)
|
||||
- [x] NFC gravação NTAG215 → `filaments/[id]/write-nfc.tsx`
|
||||
- [ ] NFC suporte iOS (requer entitlement `com.apple.developer.nfc.readwrite`)
|
||||
- [ ] Expo Notifications para alertas de estoque baixo
|
||||
- [x] Deep link `verify-email?token=` com handler e integração ao backend
|
||||
- [ ] Google OAuth com `expo-auth-session`
|
||||
- [ ] Testes de integração com Jest + Testing Library
|
||||
|
||||
@@ -364,6 +377,106 @@ Base: `EXPO_PUBLIC_API_URL` (padrão: `http://localhost:3000/api/v1`)
|
||||
|
||||
## Mudanças Recentes (14/03/2026)
|
||||
|
||||
### ✅ Reenvio de e-mail de verificação
|
||||
|
||||
**Arquivos modificados**: `src/ports/AuthRepository.ts`, `src/adapters/remote/ApiAuthRepository.ts`, `src/application/auth/AuthUseCases.ts`, `src/infrastructure/container.ts`, `app/(auth)/check-email.tsx`, `app/(auth)/register.tsx`, `app/(auth)/login.tsx`
|
||||
|
||||
**Fluxo**:
|
||||
- `register.tsx` e `login.tsx` passam o email como query param: `/(auth)/check-email?email=xxx`
|
||||
- `check-email.tsx` lê `email` via `useLocalSearchParams` e exibe botão "Reenviar e-mail"
|
||||
- Cooldown de 60s após cada envio para evitar spam
|
||||
- Feedback visual: "E-mail reenviado! Verifique sua caixa de entrada."
|
||||
- Botão só aparece se `email` estiver disponível nos params
|
||||
|
||||
**Cadeia adicionada**:
|
||||
- `AuthRepository.resendVerification(email)` — novo método no port
|
||||
- `ApiAuthRepository.resendVerification` — `POST /auth/resend-verification`
|
||||
- `ResendVerificationUseCase` — valida email não vazio e delega ao repo
|
||||
- `resendVerificationUseCase` exportado do `container.ts`
|
||||
|
||||
---
|
||||
|
||||
### ✅ Verificação de e-mail obrigatória antes do login
|
||||
|
||||
**Arquivos modificados**: `src/ports/AuthRepository.ts`, `src/adapters/remote/ApiAuthRepository.ts`, `src/application/auth/AuthUseCases.ts`, `app/(auth)/register.tsx`, `app/(auth)/login.tsx`, `app/_layout.tsx`
|
||||
|
||||
**Renomeação**: `app/(auth)/verify-email.tsx` → `app/(auth)/check-email.tsx`
|
||||
- **Motivo**: no expo-router, grupos `(auth)` são transparentes na URL. `app/(auth)/verify-email.tsx` e `app/verify-email.tsx` competiam pelo mesmo path `/verify-email`, fazendo o deep link cair na tela informativa em vez do handler de verificação.
|
||||
|
||||
**Mudanças**:
|
||||
|
||||
- `RegisterUseCase.execute` / `ApiAuthRepository.register` / `AuthRepository.register` — retornam `void` (backend não emite mais tokens no registro)
|
||||
- `register.tsx` — remove `setSession`, navega para `/(auth)/check-email` após cadastro (usuário fica não autenticado)
|
||||
- `login.tsx` — detecta `EMAIL_NOT_VERIFIED` (403 do backend) e exibe alerta com link para `/(auth)/check-email`:
|
||||
```ts
|
||||
if (axios.isAxiosError(err) && err.response?.data?.code === 'EMAIL_NOT_VERIFIED') {
|
||||
Alert.alert('E-mail não verificado', '...', [
|
||||
{ text: 'OK', onPress: () => router.push('/(auth)/check-email') },
|
||||
]);
|
||||
}
|
||||
```
|
||||
- `app/_layout.tsx` — auth guard agora exclui rotas públicas da raiz do redirect para login:
|
||||
```ts
|
||||
const inPublicRoute = segments[0] === 'verify-email' || segments[0] === 'filament';
|
||||
// ...
|
||||
} else if (!isAuthenticated && !inAuthGroup && !inPublicRoute) {
|
||||
router.replace('/(auth)/login');
|
||||
}
|
||||
```
|
||||
**Sem esse fix**, o guard redirecionava `verify-email` para login antes de o usuário ver a tela de sucesso.
|
||||
|
||||
**Rotas públicas da raiz** (não sofrem redirect do auth guard):
|
||||
| Rota | Arquivo | Função |
|
||||
|---|---|---|
|
||||
| `/verify-email` | `app/verify-email.tsx` | Handler deep link — verifica e-mail e exibe sucesso/erro |
|
||||
| `/filament` | `app/filament/[id].tsx` | Handler deep link — redireciona para detalhe do filamento |
|
||||
|
||||
---
|
||||
|
||||
### ✅ Redirect HTTP → Deep Link (fix compatibilidade com clientes de e-mail)
|
||||
|
||||
**Contexto**: clientes de e-mail (Gmail) bloqueiam links com scheme customizado (`meowspool://`). O link não abria o app.
|
||||
|
||||
**Solução implementada no backend**: o e-mail agora contém link `https://`. O backend (GET `/api/v1/verify-email?token=xxx`) redireciona 302 → `meowspool://verify-email?token=xxx`. O OS reconhece o scheme e abre o app normalmente.
|
||||
|
||||
**Impacto no mobile**: nenhuma alteração necessária no app — `app/verify-email.tsx` continua recebendo o deep link e chamando o backend via POST como antes.
|
||||
|
||||
---
|
||||
|
||||
### ✅ Deep Link de Verificação de E-mail — `app/verify-email.tsx`
|
||||
|
||||
**Arquivos criados/modificados**: `app/verify-email.tsx`, `app/_layout.tsx`, `src/application/auth/AuthUseCases.ts`, `src/infrastructure/container.ts`
|
||||
|
||||
#### Fluxo
|
||||
|
||||
1. Backend envia e-mail com link `https://meowspool.felipecncloud.com/api/v1/verify-email?token=<token>` após o registro
|
||||
2. Usuário toca no link → browser abre → backend redireciona 302 → `meowspool://verify-email?token=<token>`
|
||||
3. OS reconhece o scheme → expo-router roteia para `app/verify-email.tsx`
|
||||
4. A tela lê `token` via `useLocalSearchParams` e chama `VerifyEmailUseCase.execute(token)` em `useEffect`
|
||||
5. Exibe estado **loading** durante a chamada, **sucesso** ou **erro** (token inválido / expirado / já usado)
|
||||
6. Botão redireciona para `/(auth)/login`
|
||||
|
||||
#### `VerifyEmailUseCase`
|
||||
|
||||
Adicionado em `src/application/auth/AuthUseCases.ts`:
|
||||
|
||||
```ts
|
||||
export class VerifyEmailUseCase {
|
||||
constructor(private readonly authRepo: AuthRepository) {}
|
||||
|
||||
async execute(token: string): Promise<void> {
|
||||
if (!token) throw new Error('Token inválido.');
|
||||
await this.authRepo.verifyEmail(token);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `ApiAuthRepository.verifyEmail(token)` já existia (`POST /auth/verify-email` com `{ token }`)
|
||||
- `verifyEmailUseCase` exportado do `container.ts`
|
||||
- Rota `verify-email` registrada no `Stack` do `app/_layout.tsx`
|
||||
|
||||
---
|
||||
|
||||
### ✅ Deep Link Handler — `app/filament/[id].tsx`
|
||||
|
||||
Criada rota `app/filament/[id].tsx` para tratar deep links abertos externamente (QR Code, NFC, mensagem compartilhada). Sem essa rota, o expo-router exibia "Unmatched Route" ao abrir `meowspool://filament/{id}` fora do app.
|
||||
|
||||
@@ -1,15 +1,43 @@
|
||||
import React from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, Text, StyleSheet } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useLocalSearchParams } from 'expo-router';
|
||||
import { Screen } from '@presentation/components/layout/Screen';
|
||||
import { Header } from '@presentation/components/layout/Header';
|
||||
import { Button } from '@presentation/components/ui/Button';
|
||||
import { colors, typography, spacing, radius } from '@shared/theme';
|
||||
import { resendVerificationUseCase } from '@infrastructure/container';
|
||||
|
||||
const COOLDOWN_SECS = 60;
|
||||
|
||||
/**
|
||||
* Tela de Verificação de E-mail — RU-0
|
||||
* Mostrada após o cadastro bem-sucedido.
|
||||
*/
|
||||
export default function VerifyEmailScreen(): React.ReactElement {
|
||||
export default function CheckEmailScreen(): React.ReactElement {
|
||||
const { email } = useLocalSearchParams<{ email: string }>();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [cooldown, setCooldown] = useState(0);
|
||||
const [sent, setSent] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (cooldown <= 0) return;
|
||||
const timer = setTimeout(() => setCooldown((c) => c - 1), 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [cooldown]);
|
||||
|
||||
async function handleResend(): Promise<void> {
|
||||
if (!email || cooldown > 0) return;
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await resendVerificationUseCase.execute(email);
|
||||
setSent(true);
|
||||
setCooldown(COOLDOWN_SECS);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Screen>
|
||||
<Header title="Verificar e-mail" showBack />
|
||||
@@ -24,6 +52,27 @@ export default function VerifyEmailScreen(): React.ReactElement {
|
||||
Enviamos um link de verificação para o seu e-mail. Clique no link para ativar sua conta e poder fazer login.
|
||||
</Text>
|
||||
|
||||
{email && (
|
||||
<Button
|
||||
label={
|
||||
cooldown > 0
|
||||
? `Reenviar em ${cooldown}s`
|
||||
: sent
|
||||
? 'Reenviar e-mail'
|
||||
: 'Reenviar e-mail'
|
||||
}
|
||||
variant="secondary"
|
||||
onPress={handleResend}
|
||||
isLoading={isLoading}
|
||||
disabled={cooldown > 0}
|
||||
style={styles.resendButton}
|
||||
/>
|
||||
)}
|
||||
|
||||
{sent && cooldown > 0 && (
|
||||
<Text style={styles.sentText}>E-mail reenviado! Verifique sua caixa de entrada.</Text>
|
||||
)}
|
||||
|
||||
<View style={styles.hint}>
|
||||
<Ionicons name="information-circle-outline" size={16} color={colors.textSecondary} />
|
||||
<Text style={styles.hintText}>Não recebeu? Verifique sua pasta de spam.</Text>
|
||||
@@ -64,11 +113,20 @@ const styles = StyleSheet.create({
|
||||
textAlign: 'center',
|
||||
lineHeight: typography.fontSize.base * 1.6,
|
||||
},
|
||||
resendButton: {
|
||||
width: '100%',
|
||||
},
|
||||
sentText: {
|
||||
fontFamily: typography.fontFamily.ui,
|
||||
fontSize: typography.fontSize.sm,
|
||||
color: colors.accent,
|
||||
textAlign: 'center',
|
||||
},
|
||||
hint: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing[2],
|
||||
marginTop: spacing[4],
|
||||
marginTop: spacing[2],
|
||||
},
|
||||
hintText: {
|
||||
fontFamily: typography.fontFamily.ui,
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Alert } from 'react-native';
|
||||
import axios from 'axios';
|
||||
import { Link, useRouter } from 'expo-router';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
@@ -42,8 +43,15 @@ export default function LoginScreen(): React.ReactElement {
|
||||
await setSession(session);
|
||||
router.replace('/(app)/(tabs)/home');
|
||||
} catch (err) {
|
||||
console.error('login error', err);
|
||||
Alert.alert('Erro', 'E-mail ou senha incorretos.');
|
||||
if (axios.isAxiosError(err) && err.response?.data?.code === 'EMAIL_NOT_VERIFIED') {
|
||||
Alert.alert(
|
||||
'E-mail não verificado',
|
||||
'Confirme seu e-mail antes de entrar. Verifique sua caixa de entrada.',
|
||||
[{ text: 'OK', onPress: () => router.push(`/(auth)/check-email?email=${encodeURIComponent(data.email)}`) }],
|
||||
);
|
||||
} else {
|
||||
Alert.alert('Erro', 'E-mail ou senha incorretos.');
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import { Input } from '@presentation/components/ui/Input';
|
||||
import { Button } from '@presentation/components/ui/Button';
|
||||
import { colors, typography, spacing } from '@shared/theme';
|
||||
import { registerUseCase } from '@infrastructure/container';
|
||||
import { useAuthStore } from '@store/authStore';
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email('E-mail inválido'),
|
||||
@@ -31,7 +30,6 @@ type FormData = z.infer<typeof schema>;
|
||||
*/
|
||||
export default function RegisterScreen(): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const setSession = useAuthStore((s) => s.setSession);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const { control, handleSubmit, formState: { errors } } = useForm<FormData>({
|
||||
@@ -42,9 +40,8 @@ export default function RegisterScreen(): React.ReactElement {
|
||||
async function onSubmit(data: FormData): Promise<void> {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const session = await registerUseCase.execute({ email: data.email, password: data.password });
|
||||
await setSession(session);
|
||||
router.replace('/(auth)/verify-email');
|
||||
await registerUseCase.execute({ email: data.email, password: data.password });
|
||||
router.replace(`/(auth)/check-email?email=${encodeURIComponent(data.email)}`);
|
||||
} catch {
|
||||
Alert.alert('Erro', 'Não foi possível criar sua conta.');
|
||||
} finally {
|
||||
|
||||
@@ -19,9 +19,10 @@ export default function RootLayout(): React.ReactElement | null {
|
||||
useEffect(() => {
|
||||
if (isLoading) return;
|
||||
const inAuthGroup = segments[0] === '(auth)';
|
||||
const inPublicRoute = segments[0] === 'verify-email' || segments[0] === 'filament';
|
||||
if (isAuthenticated && inAuthGroup) {
|
||||
router.replace('/(app)/(tabs)/home');
|
||||
} else if (!isAuthenticated && !inAuthGroup) {
|
||||
} else if (!isAuthenticated && !inAuthGroup && !inPublicRoute) {
|
||||
router.replace('/(auth)/login');
|
||||
}
|
||||
}, [isAuthenticated, isLoading, segments, router]);
|
||||
@@ -35,6 +36,8 @@ export default function RootLayout(): React.ReactElement | null {
|
||||
<Stack.Screen name="index" />
|
||||
<Stack.Screen name="(auth)" />
|
||||
<Stack.Screen name="(app)" />
|
||||
<Stack.Screen name="verify-email" />
|
||||
<Stack.Screen name="filament/[id]" />
|
||||
</Stack>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, StyleSheet, ActivityIndicator } from 'react-native';
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { Screen } from '@presentation/components/layout/Screen';
|
||||
import { Button } from '@presentation/components/ui/Button';
|
||||
import { colors, typography, spacing, radius } from '@shared/theme';
|
||||
import { verifyEmailUseCase } from '@infrastructure/container';
|
||||
|
||||
type Status = 'loading' | 'success' | 'error';
|
||||
|
||||
/**
|
||||
* Handler de deep link: meowspool://verify-email?token=xxx
|
||||
* Chama o backend para confirmar o e-mail e exibe o resultado.
|
||||
*/
|
||||
export default function VerifyEmailDeepLink(): React.ReactElement {
|
||||
const { token } = useLocalSearchParams<{ token: string }>();
|
||||
const router = useRouter();
|
||||
const [status, setStatus] = useState<Status>('loading');
|
||||
const [errorMessage, setErrorMessage] = useState('Não foi possível verificar o e-mail.');
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setErrorMessage('Link inválido ou expirado.');
|
||||
setStatus('error');
|
||||
return;
|
||||
}
|
||||
|
||||
verifyEmailUseCase.execute(token)
|
||||
.then(() => setStatus('success'))
|
||||
.catch((e: unknown) => {
|
||||
const msg = e instanceof Error ? e.message : 'Erro desconhecido.';
|
||||
setErrorMessage(msg);
|
||||
setStatus('error');
|
||||
});
|
||||
}, [token]);
|
||||
|
||||
return (
|
||||
<Screen>
|
||||
<View style={styles.content}>
|
||||
{status === 'loading' && (
|
||||
<>
|
||||
<ActivityIndicator size="large" color={colors.accent} />
|
||||
<Text style={styles.message}>Verificando e-mail…</Text>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'success' && (
|
||||
<>
|
||||
<View style={[styles.iconWrapper, styles.iconSuccess]}>
|
||||
<Ionicons name="checkmark-circle-outline" size={64} color={colors.accent} />
|
||||
</View>
|
||||
<Text style={styles.title}>E-mail verificado!</Text>
|
||||
<Text style={styles.message}>Sua conta está ativa. Faça login para continuar.</Text>
|
||||
<Button
|
||||
label="Ir para o login"
|
||||
onPress={() => router.replace('/(auth)/login')}
|
||||
style={styles.cta}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'error' && (
|
||||
<>
|
||||
<View style={[styles.iconWrapper, styles.iconError]}>
|
||||
<Ionicons name="close-circle-outline" size={64} color={colors.error ?? '#FF6B6B'} />
|
||||
</View>
|
||||
<Text style={styles.title}>Falha na verificação</Text>
|
||||
<Text style={styles.message}>{errorMessage}</Text>
|
||||
<Button
|
||||
label="Voltar ao login"
|
||||
onPress={() => router.replace('/(auth)/login')}
|
||||
style={styles.cta}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
content: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing[4],
|
||||
paddingHorizontal: spacing[6],
|
||||
},
|
||||
iconWrapper: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
borderRadius: radius.xl,
|
||||
backgroundColor: colors.bgSurface,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: spacing[2],
|
||||
},
|
||||
iconSuccess: {},
|
||||
iconError: {},
|
||||
title: {
|
||||
fontFamily: typography.fontFamily.ui,
|
||||
fontSize: typography.fontSize.xl,
|
||||
fontWeight: typography.fontWeight.bold,
|
||||
color: colors.textPrimary,
|
||||
textAlign: 'center',
|
||||
},
|
||||
message: {
|
||||
fontFamily: typography.fontFamily.ui,
|
||||
fontSize: typography.fontSize.base,
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
lineHeight: typography.fontSize.base * 1.6,
|
||||
},
|
||||
cta: { marginTop: spacing[2], width: '100%' },
|
||||
});
|
||||
@@ -12,9 +12,8 @@ export class ApiAuthRepository implements AuthRepository {
|
||||
return this.fetchSession(data.access_token as string, data.refresh_token as string);
|
||||
}
|
||||
|
||||
async register(input: RegisterInput): Promise<AuthSession> {
|
||||
const { data } = await httpClient.post('/auth/register', input);
|
||||
return this.fetchSession(data.access_token as string, data.refresh_token as string);
|
||||
async register(input: RegisterInput): Promise<void> {
|
||||
await httpClient.post('/auth/register', input);
|
||||
}
|
||||
|
||||
async loginWithGoogle(input: GoogleOAuthInput): Promise<AuthSession> {
|
||||
@@ -36,6 +35,10 @@ export class ApiAuthRepository implements AuthRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async resendVerification(email: string): Promise<void> {
|
||||
await httpClient.post('/auth/resend-verification', { email });
|
||||
}
|
||||
|
||||
async forgotPassword(email: string): Promise<void> {
|
||||
await httpClient.post('/auth/forgot-password', { email });
|
||||
}
|
||||
|
||||
@@ -21,14 +21,14 @@ export class LoginUseCase {
|
||||
export class RegisterUseCase {
|
||||
constructor(private readonly authRepo: AuthRepository) {}
|
||||
|
||||
async execute(input: RegisterInput): Promise<AuthSession> {
|
||||
async execute(input: RegisterInput): Promise<void> {
|
||||
if (!input.email || !input.password) {
|
||||
throw new Error('E-mail e senha são obrigatórios.');
|
||||
}
|
||||
if (input.password.length < 8) {
|
||||
throw new Error('A senha deve ter ao menos 8 caracteres.');
|
||||
}
|
||||
return this.authRepo.register(input);
|
||||
await this.authRepo.register(input);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,18 @@ export class LogoutUseCase {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Caso de uso: Reenviar e-mail de verificação de conta.
|
||||
*/
|
||||
export class ResendVerificationUseCase {
|
||||
constructor(private readonly authRepo: AuthRepository) {}
|
||||
|
||||
async execute(email: string): Promise<void> {
|
||||
if (!email) throw new Error('E-mail obrigatório.');
|
||||
await this.authRepo.resendVerification(email);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Caso de uso: Solicitar redefinição de senha.
|
||||
*/
|
||||
@@ -65,6 +77,18 @@ export class ForgotPasswordUseCase {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Caso de uso: Verificar e-mail com token recebido por deep link.
|
||||
*/
|
||||
export class VerifyEmailUseCase {
|
||||
constructor(private readonly authRepo: AuthRepository) {}
|
||||
|
||||
async execute(token: string): Promise<void> {
|
||||
if (!token) throw new Error('Token inválido.');
|
||||
await this.authRepo.verifyEmail(token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Caso de uso: Redefinir senha com token.
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
LoginUseCase,
|
||||
RegisterUseCase,
|
||||
ForgotPasswordUseCase,
|
||||
ResendVerificationUseCase,
|
||||
ResetPasswordUseCase,
|
||||
VerifyEmailUseCase,
|
||||
LogoutUseCase,
|
||||
} from '@application/auth/AuthUseCases';
|
||||
import { CreateFilamentUseCase } from '@application/filament/CreateFilamentUseCase';
|
||||
@@ -30,8 +32,10 @@ const presetRepository = new ApiSpoolPresetRepository();
|
||||
// Use cases de autenticação
|
||||
export const loginUseCase = new LoginUseCase(authRepository);
|
||||
export const registerUseCase = new RegisterUseCase(authRepository);
|
||||
export const resendVerificationUseCase = new ResendVerificationUseCase(authRepository);
|
||||
export const forgotPasswordUseCase = new ForgotPasswordUseCase(authRepository);
|
||||
export const resetPasswordUseCase = new ResetPasswordUseCase(authRepository);
|
||||
export const verifyEmailUseCase = new VerifyEmailUseCase(authRepository);
|
||||
export const logoutUseCase = new LogoutUseCase(authRepository);
|
||||
|
||||
// Use cases de filamento
|
||||
|
||||
@@ -6,10 +6,11 @@ import type { AuthSession, LoginInput, RegisterInput, GoogleOAuthInput } from '@
|
||||
*/
|
||||
export interface AuthRepository {
|
||||
login(input: LoginInput): Promise<AuthSession>;
|
||||
register(input: RegisterInput): Promise<AuthSession>;
|
||||
register(input: RegisterInput): Promise<void>;
|
||||
loginWithGoogle(input: GoogleOAuthInput): Promise<AuthSession>;
|
||||
refreshToken(refreshToken: string): Promise<Pick<AuthSession, 'accessToken' | 'refreshToken'>>;
|
||||
logout(accessToken: string): Promise<void>;
|
||||
resendVerification(email: string): Promise<void>;
|
||||
forgotPassword(email: string): Promise<void>;
|
||||
verifyEmail(token: string): Promise<void>;
|
||||
resetPassword(token: string, newPassword: string): Promise<void>;
|
||||
|
||||
Reference in New Issue
Block a user