Initial commit: Full project structure
- Backend: NestJS with Docker - Frontend: Next.js with Docker - Nginx configuration for reverse proxy - PostgreSQL setup - Docker compose for orchestration - Development environment configuration
This commit is contained in:
40
frontend/src/lib/api/auth.ts
Normal file
40
frontend/src/lib/api/auth.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// src/lib/api/auth.ts
|
||||
import { apiClient } from './client';
|
||||
import { AuthResponse, TrialRegistrationData, LoginData } from '@/types';
|
||||
|
||||
export const authApi = {
|
||||
// Register a new trial organization
|
||||
registerTrial: async (data: TrialRegistrationData): Promise<AuthResponse> => {
|
||||
const response = await apiClient.post('/auth/register', data);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// Login user
|
||||
login: async (data: LoginData): Promise<AuthResponse> => {
|
||||
const response = await apiClient.post('/auth/login', data);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// Get user profile
|
||||
getProfile: async (): Promise<AuthResponse> => {
|
||||
const response = await apiClient.get('/auth/profile');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// Select organization
|
||||
selectOrganization: async (organizationId: string): Promise<any> => {
|
||||
const response = await apiClient.post('/auth/select-organization', { organizationId });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// Logout
|
||||
logout: async (): Promise<void> => {
|
||||
await apiClient.post('/auth/logout');
|
||||
},
|
||||
|
||||
// Refresh token
|
||||
refreshToken: async (refreshToken: string): Promise<{ accessToken: string }> => {
|
||||
const response = await apiClient.post('/auth/refresh', { refreshToken });
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
57
frontend/src/lib/api/client.ts
Normal file
57
frontend/src/lib/api/client.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
// src/lib/api/client.ts
|
||||
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
|
||||
import { ApiError } from '@/types';
|
||||
|
||||
interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
|
||||
_retry?: boolean;
|
||||
}
|
||||
|
||||
export const apiClient = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
||||
withCredentials: true, // ✅ REQUIRED FOR COOKIES
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// ❌ REMOVE request interceptor completely (no Authorization header)
|
||||
|
||||
// ✅ Response interceptor
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error: AxiosError) => {
|
||||
const originalRequest = error.config as CustomAxiosRequestConfig;
|
||||
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
// ✅ refresh via cookie (no body needed ideally)
|
||||
await axios.post(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/auth/refresh`,
|
||||
{},
|
||||
{ withCredentials: true }
|
||||
);
|
||||
|
||||
return apiClient(originalRequest);
|
||||
} catch (refreshError) {
|
||||
if (typeof window !== 'undefined') {
|
||||
return Promise.reject(error); // ✅ just fail silently
|
||||
}
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
|
||||
const apiError: ApiError = {
|
||||
statusCode: error.response?.status || 500,
|
||||
message:
|
||||
(error.response?.data as any)?.message ||
|
||||
error.message ||
|
||||
'An unexpected error occurred',
|
||||
error: (error.response?.data as any)?.error,
|
||||
};
|
||||
|
||||
return Promise.reject(apiError);
|
||||
}
|
||||
);
|
||||
215
frontend/src/lib/hooks/useAuth.tsx
Normal file
215
frontend/src/lib/hooks/useAuth.tsx
Normal file
@@ -0,0 +1,215 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import { User, Organization } from '@/types';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
organizations: Organization[];
|
||||
currentOrganization: Organization | null;
|
||||
isLoading: boolean;
|
||||
isAuthReady: boolean; // ✅ NEW
|
||||
error: string | null;
|
||||
registerTrial: (
|
||||
email: string,
|
||||
password: string,
|
||||
name: string,
|
||||
organizationName: string,
|
||||
organizationType: 'CLINIC' | 'LAB'
|
||||
) => Promise<void>;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
selectOrganization: (orgId: string) => Promise<void>;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
||||
const [currentOrganization, setCurrentOrganization] = useState<Organization | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isAuthReady, setIsAuthReady] = useState(false); // ✅ KEY FIX
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
|
||||
const hasSession = document.cookie.includes('accessToken');
|
||||
|
||||
if (!hasSession) {
|
||||
console.log('No session → skipping auth check');
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await authApi.getProfile();
|
||||
|
||||
if (response.success) {
|
||||
const userData = response.data.user;
|
||||
const orgs = response.data.organizations || [];
|
||||
|
||||
setUser(userData);
|
||||
setOrganizations(orgs);
|
||||
|
||||
const storedOrgId = localStorage.getItem('currentOrganizationId');
|
||||
if (storedOrgId && orgs.length > 0) {
|
||||
const org = orgs.find(o => o.id === storedOrgId);
|
||||
if (org) setCurrentOrganization(org);
|
||||
} else if (orgs.length === 1) {
|
||||
setCurrentOrganization(orgs[0]);
|
||||
localStorage.setItem('currentOrganizationId', orgs[0].id);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Auth check failed:', err);
|
||||
// Only clear state — DO NOT redirect here
|
||||
setUser(null);
|
||||
setOrganizations([]);
|
||||
setCurrentOrganization(null);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsAuthReady(true);
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ REGISTER
|
||||
const registerTrial = async (
|
||||
email: string,
|
||||
password: string,
|
||||
name: string,
|
||||
organizationName: string,
|
||||
organizationType: 'CLINIC' | 'LAB'
|
||||
) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await authApi.registerTrial({
|
||||
email,
|
||||
password,
|
||||
name,
|
||||
organizationName,
|
||||
organizationType,
|
||||
});
|
||||
|
||||
setUser(response.data.user);
|
||||
setOrganizations(response.data.organizations);
|
||||
|
||||
const orgs = response.data.organizations;
|
||||
|
||||
if (orgs.length === 1) {
|
||||
const org = orgs[0];
|
||||
setCurrentOrganization(org);
|
||||
localStorage.setItem('currentOrganizationId', org.id);
|
||||
router.push('/today');
|
||||
} else {
|
||||
router.push('/select-organization');
|
||||
|
||||
}
|
||||
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Registration failed');
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ LOGIN
|
||||
const login = async (email: string, password: string) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await authApi.login({ email, password });
|
||||
|
||||
setUser(response.data.user);
|
||||
setOrganizations(response.data.organizations);
|
||||
|
||||
const orgs = response.data.organizations;
|
||||
|
||||
if (orgs.length === 1) {
|
||||
const org = orgs[0];
|
||||
setCurrentOrganization(org);
|
||||
localStorage.setItem('currentOrganizationId', org.id);
|
||||
router.push('/today');
|
||||
} else {
|
||||
router.push('/select-organization');
|
||||
}
|
||||
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Login failed');
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
localStorage.clear();
|
||||
setUser(null);
|
||||
setOrganizations([]);
|
||||
setCurrentOrganization(null);
|
||||
router.push('/');
|
||||
};
|
||||
|
||||
const selectOrganization = async (orgId: string) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
|
||||
const response = await authApi.selectOrganization(orgId);
|
||||
|
||||
const { organization } = response.data;
|
||||
|
||||
localStorage.setItem('currentOrganizationId', organization.id);
|
||||
|
||||
setCurrentOrganization(organization);
|
||||
|
||||
router.push('/today');
|
||||
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const clearError = () => setError(null);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
organizations,
|
||||
currentOrganization,
|
||||
isLoading,
|
||||
isAuthReady, // ✅ expose it
|
||||
error,
|
||||
registerTrial,
|
||||
login,
|
||||
logout,
|
||||
selectOrganization,
|
||||
clearError,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) throw new Error('useAuth must be used within AuthProvider');
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user