xpeditis2.0/apps/frontend/lib/context/auth-context.tsx
David e6b9b42f6c
Some checks failed
CI/CD Pipeline - Xpeditis PreProd / Backend - Build & Test (push) Failing after 5m51s
CI/CD Pipeline - Xpeditis PreProd / Backend - Docker Build & Push (push) Has been skipped
CI/CD Pipeline - Xpeditis PreProd / Frontend - Build & Test (push) Successful in 10m57s
CI/CD Pipeline - Xpeditis PreProd / Frontend - Docker Build & Push (push) Failing after 12m28s
CI/CD Pipeline - Xpeditis PreProd / Deploy to PreProd Server (push) Has been skipped
CI/CD Pipeline - Xpeditis PreProd / Run Smoke Tests (push) Has been skipped
fix
2025-11-13 00:15:45 +01:00

125 lines
2.9 KiB
TypeScript

/**
* Auth Context
*
* Provides authentication state and methods to the application
*/
'use client';
import React, { createContext, useContext, useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { authApi, User } from '../api';
interface AuthContextType {
user: User | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (data: {
email: string;
password: string;
firstName: string;
lastName: string;
organizationId: string;
}) => Promise<void>;
logout: () => Promise<void>;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const router = useRouter();
useEffect(() => {
// Check if user is already logged in
const checkAuth = async () => {
try {
if (authApi.isAuthenticated()) {
const storedUser = authApi.getStoredUser();
if (storedUser) {
// Verify token is still valid by fetching current user
const currentUser = await authApi.me();
setUser(currentUser);
}
}
} catch (error) {
console.error('Auth check failed:', error);
// Token invalid, clear storage
if (typeof window !== 'undefined') {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
localStorage.removeItem('user');
}
} finally {
setLoading(false);
}
};
checkAuth();
}, []);
const login = async (email: string, password: string) => {
try {
const response = await authApi.login({ email, password });
setUser({
...response.user,
isEmailVerified: false,
isActive: true
} as User);
router.push('/dashboard');
} catch (error) {
throw error;
}
};
const register = async (data: {
email: string;
password: string;
firstName: string;
lastName: string;
organizationId: string;
}) => {
try {
const response = await authApi.register(data);
setUser({
...response.user,
isEmailVerified: false,
isActive: true
} as User);
router.push('/dashboard');
} catch (error) {
throw error;
}
};
const logout = async () => {
try {
await authApi.logout();
} finally {
setUser(null);
router.push('/login');
}
};
const value = {
user,
loading,
login,
register,
logout,
isAuthenticated: !!user,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}