Merge pull request #15 from rede5/Front-back-integracao-task1
feat: (auth) ajuste mensagens de erro
This commit is contained in:
commit
917ad7f0ec
3 changed files with 43 additions and 6 deletions
|
|
@ -47,6 +47,28 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|||
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
|
||||
const getErrorMessage = (errorKey: string): string => {
|
||||
// Map backend error messages to Portuguese
|
||||
const errorMap: { [key: string]: string } = {
|
||||
"email already registered": "Este e-mail já está cadastrado.",
|
||||
"invalid credentials": "E-mail ou senha incorretos.",
|
||||
"user not found": "Usuário não encontrado.",
|
||||
"crypto/bcrypt: hashedPassword is not the hash of the given password": "Senha incorreta.",
|
||||
"password is too short": "A senha é muito curta.",
|
||||
"cpf already registered": "CPF já cadastrado.",
|
||||
};
|
||||
|
||||
// Check for partial matches or exact matches
|
||||
if (errorMap[errorKey]) return errorMap[errorKey];
|
||||
|
||||
// Fallbacks
|
||||
if (errorKey.includes('hashedPassword')) return "Senha incorreta.";
|
||||
if (errorKey.includes('email')) return "Erro relacionado ao e-mail.";
|
||||
if (errorKey.includes('password')) return "Erro relacionado à senha.";
|
||||
|
||||
return "Ocorreu um erro inesperado. Tente novamente.";
|
||||
};
|
||||
|
||||
const login = async (email: string, password?: string) => {
|
||||
// 1. Check for Demo/Mock users first
|
||||
const mockUser = MOCK_USERS.find(u => u.email === email);
|
||||
|
|
@ -65,8 +87,8 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Login failed:', response.statusText);
|
||||
return false;
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(getErrorMessage(errorData.error || 'Falha no login'));
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
|
@ -107,7 +129,9 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || 'Falha no cadastro');
|
||||
const rawError = errorData.error || 'Falha no cadastro';
|
||||
// Allow passing raw error if it's not in map, or map it
|
||||
throw new Error(getErrorMessage(rawError));
|
||||
}
|
||||
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -22,9 +22,16 @@ export const Login: React.FC<LoginProps> = ({ onNavigate }) => {
|
|||
setIsLoading(true);
|
||||
setError('');
|
||||
|
||||
const success = await login(email, password);
|
||||
if (!success) {
|
||||
setError('Usuário não encontrado. Tente um dos e-mails de demonstração.');
|
||||
try {
|
||||
const success = await login(email, password);
|
||||
// If mock login returns true (it doesn't throw), we are good.
|
||||
// If real login throws, we catch it below.
|
||||
if (!success) {
|
||||
// Fallback for mock if it returns false without throwing
|
||||
setError('Credenciais inválidas, tente novamente ou tente um dos e-mails de demonstração.');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Erro ao realizar login');
|
||||
}
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -305,6 +305,12 @@ export const Register: React.FC<RegisterProps> = ({ onNavigate }) => {
|
|||
</label>
|
||||
</div>
|
||||
|
||||
{error && !error.includes('termos') && !error.includes('senha') && !error.includes('coincidem') && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg text-sm mb-4">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" size="lg" isLoading={isLoading}>
|
||||
{formData.wantsToAddInstitution ? 'Continuar para Universidade' : 'Criar Conta'}
|
||||
</Button>
|
||||
|
|
|
|||
Loading…
Reference in a new issue