106 lines
2.7 KiB
TypeScript
106 lines
2.7 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
import { Alert } from 'react-native';
|
|
import * as authService from '../services/auth';
|
|
|
|
interface User {
|
|
userId: number;
|
|
email: string;
|
|
}
|
|
|
|
export const useAuth = () => {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
|
|
|
// Kiểm tra trạng thái đăng nhập khi khởi động
|
|
useEffect(() => {
|
|
checkAuthStatus();
|
|
}, []);
|
|
|
|
const checkAuthStatus = async () => {
|
|
try {
|
|
const authenticated = await authService.isAuthenticated();
|
|
setIsAuthenticated(authenticated);
|
|
|
|
if (authenticated) {
|
|
const userData = await authService.getUser();
|
|
setUser(userData);
|
|
}
|
|
} catch (error) {
|
|
console.error('Check auth status error:', error);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const login = async (email: string, password: string) => {
|
|
try {
|
|
const response = await authService.login(email, password);
|
|
|
|
setUser({
|
|
userId: response.userId,
|
|
email: response.email,
|
|
});
|
|
setIsAuthenticated(true);
|
|
|
|
Alert.alert('Thành công', 'Đăng nhập thành công!');
|
|
return true;
|
|
} catch (error: any) {
|
|
console.error('Login error:', error);
|
|
Alert.alert('Lỗi', error.message || 'Đăng nhập thất bại');
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const register = async (email: string, password: string) => {
|
|
try {
|
|
const response = await authService.register(email, password);
|
|
|
|
// Sau khi đăng ký thành công, tự động đăng nhập
|
|
if (response.token) {
|
|
await authService.saveAuthData(response);
|
|
setUser({
|
|
userId: response.userId,
|
|
email: response.email,
|
|
});
|
|
setIsAuthenticated(true);
|
|
}
|
|
|
|
Alert.alert('Thành công', 'Đăng ký thành công!');
|
|
return true;
|
|
} catch (error: any) {
|
|
console.error('Register error:', error);
|
|
Alert.alert('Lỗi', error.message || 'Đăng ký thất bại');
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const logout = async () => {
|
|
try {
|
|
const token = await authService.getAuthToken();
|
|
if (token) {
|
|
await authService.logout(token);
|
|
}
|
|
|
|
setUser(null);
|
|
setIsAuthenticated(false);
|
|
|
|
Alert.alert('Thành công', 'Đăng xuất thành công!');
|
|
return true;
|
|
} catch (error: any) {
|
|
console.error('Logout error:', error);
|
|
Alert.alert('Lỗi', 'Đăng xuất thất bại');
|
|
return false;
|
|
}
|
|
};
|
|
|
|
return {
|
|
user,
|
|
loading,
|
|
isAuthenticated,
|
|
login,
|
|
register,
|
|
logout,
|
|
checkAuthStatus,
|
|
};
|
|
}; |