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:
2026-03-14 23:38:15 -03:00
parent f5f4e878b4
commit d5af338ee1
38 changed files with 1146 additions and 75 deletions
+120 -7
View File
@@ -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``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.