Skip to content

Commit 2b8ca43

Browse files
committed
fix: handling of tokens received from the backend
1 parent bc9ebad commit 2b8ca43

7 files changed

Lines changed: 36 additions & 49 deletions

File tree

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.env
2+
13
# Logs
24
logs
35
*.log

src/api/apiClient.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import axios from 'axios';
22

33
const apiClient = axios.create({
4-
baseURL: 'http://localhost:3000/api',
4+
baseURL: import.meta.env.VITE_API_BASE_URL,
55
headers: {
66
'Content-Type': 'application/json',
77
},

src/api/services/auth.service.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,16 @@ import type { User } from '../../types/entities';
44
type LoginPayload = {mail: string; password_plaintext: string};
55
type RegisterPayload = Omit<User, 'password' | 'id' | 'role' | 'studentProfile' | 'professorProfile' | 'profile_picture'> & { password_plaintext: string };
66

7-
interface AuthResponse {
8-
token: string;
9-
user: User;
10-
}
7+
const login = async (payload: LoginPayload): Promise<string> => {
8+
const response = await apiClient.post<{ data: { token: string }}>('/auth/login', payload);
119

12-
const login = async (payload: LoginPayload): Promise<AuthResponse> => {
13-
const response = await apiClient.post<AuthResponse>('/auth/login', payload);
14-
return response.data;
10+
const token = response.data?.data?.token;
11+
12+
if (typeof token !== 'string' || token.length === 0) {
13+
throw new Error('Token no fue recibido en la respuesta del servidor.');
14+
}
15+
16+
return token;
1517
};
1618

1719
const register = async (payload: RegisterPayload): Promise<User> => {

src/contexts/AuthContext.tsx

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,8 @@ export interface AuthContextType {
55
isAuthenticated: boolean;
66
user: User | null;
77
isLoading: boolean;
8-
login: (userData: User, token: string) => void;
8+
login: (userData: User | null, token: string) => void;
99
logout: () => void;
1010
}
1111

12-
export const AuthContext = createContext<AuthContextType>({
13-
isAuthenticated: false,
14-
user: null,
15-
isLoading: true,
16-
login: () => { throw new Error('Login function not implemented'); },
17-
logout: () => { throw new Error('Logout function not implemented'); },
18-
});
12+
export const AuthContext = createContext<AuthContextType | null>(null);

src/contexts/AuthProvider.tsx

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,28 @@
1-
import { useState, useEffect, useMemo } from 'react';
1+
import { useState, useMemo, useCallback } from 'react';
22
import type { ReactNode } from 'react';
33
import type { User } from '../types/entities.ts';
4-
import { authService } from '../api/services/auth.service.ts';
54
import { AuthContext } from './AuthContext';
65

76
export const AuthProvider = ({ children }: { children: ReactNode }) => {
87
const [user, setUser] = useState<User | null>(null);
9-
const [isLoading, setIsLoading] = useState(true);
108

11-
useEffect(() => {
12-
const validateSession = async () => {
13-
const token = localStorage.getItem('authToken');
14-
if (token) {
15-
try {
16-
const userData = await authService.getProfile();
17-
setUser(userData);
18-
} catch (error) {
19-
console.error("Session validation failed:", error);
20-
localStorage.removeItem('authToken');
21-
setUser(null);
22-
}
23-
}
24-
setIsLoading(false);
25-
};
26-
validateSession();
27-
}, []);
28-
29-
const login = (userData: User, token: string) => {
9+
const login = useCallback((userData: User | null, token: string) => {
3010
localStorage.setItem('authToken', token);
3111
setUser(userData);
32-
};
12+
}, []);
3313

34-
const logout = () => {
14+
const logout = useCallback(() => {
3515
localStorage.removeItem('authToken');
3616
setUser(null);
37-
};
17+
}, []);
3818

3919
const value = useMemo(() => ({
40-
isAuthenticated: !!user,
20+
isAuthenticated: !!user || !!localStorage.getItem('authToken'),
4121
user,
42-
isLoading,
22+
isLoading: false,
4323
login,
4424
logout,
45-
}), [user, isLoading]);
25+
}), [user, login, logout]);
4626

4727
return (
4828
<AuthContext.Provider value={value}>

src/hooks/useAuth.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import type { AuthContextType } from '../contexts/AuthContext';
55
export const useAuth = (): AuthContextType => {
66
const context = useContext(AuthContext);
77

8-
if (context === undefined) {
8+
if (context === undefined || context === null) {
99
throw new Error('useAuth must be used within an AuthProvider');
1010
}
1111
return context;

src/pages/Auth/LoginPage.tsx

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useState } from 'react';
22
import { Link, useNavigate } from 'react-router-dom';
33
import type React from 'react';
4+
import axios from 'axios';
45
import { Mail, Lock } from 'lucide-react';
56
import { useAuth } from '../../hooks/useAuth';
67
import { authService } from '../../api/services/auth.service';
@@ -26,12 +27,20 @@ const LoginPage = () => {
2627
mail: credentials.mail,
2728
password_plaintext: credentials.password,
2829
};
29-
const { user, token } = await authService.login(payload);
30-
auth.login(user, token);
30+
const token = await authService.login(payload);
31+
if (!token || typeof token !== 'string') {
32+
throw new Error("No se recibió un token válido del servidor.");
33+
}
34+
auth.login(null, token);
3135
navigate('/');
36+
3237
} catch (err) {
33-
setError('Credenciales incorrectas. Por favor, inténtalo de nuevo.');
34-
console.error(err);
38+
if (axios.isAxiosError(err)) {
39+
setError(err.response?.data?.message || 'Credenciales incorrectas.');
40+
} else {
41+
setError('Ocurrió un error inesperado. Por favor, intenta de nuevo.');
42+
}
43+
console.error(err);
3544
} finally {
3645
setIsLoading(false);
3746
}

0 commit comments

Comments
 (0)