import { mutation } from './_generated/server'; import { v } from 'convex/values'; import { updatePassword } from './auth'; import { authComponent } from './auth'; /** * Alterar senha do usuário autenticado */ export const alterarSenha = mutation({ args: { token: v.string(), // Token não é usado, mas mantido para compatibilidade senhaAtual: v.string(), novaSenha: v.string() }, returns: v.union( v.object({ sucesso: v.literal(true) }), v.object({ sucesso: v.literal(false), erro: v.string() }) ), handler: async (ctx, args) => { try { // Verificar se o usuário está autenticado const authUser = await authComponent.safeGetAuthUser(ctx); if (!authUser) { return { sucesso: false as const, erro: 'Usuário não autenticado' }; } // Validar que a nova senha não está vazia if (!args.novaSenha || args.novaSenha.trim().length === 0) { return { sucesso: false as const, erro: 'A nova senha não pode estar vazia' }; } // Chamar a função de atualização de senha await updatePassword(ctx, { currentPassword: args.senhaAtual, newPassword: args.novaSenha }); return { sucesso: true as const }; } catch (error: any) { // Capturar erros específicos do Better Auth let mensagemErro = 'Erro ao alterar senha'; if (error?.message) { mensagemErro = error.message; } else if (typeof error === 'string') { mensagemErro = error; } // Mensagens de erro mais amigáveis if (mensagemErro.toLowerCase().includes('password') || mensagemErro.toLowerCase().includes('senha') || mensagemErro.toLowerCase().includes('incorrect') || mensagemErro.toLowerCase().includes('incorreta')) { mensagemErro = 'Senha atual incorreta'; } return { sucesso: false as const, erro: mensagemErro }; } } });