Add Phase 2 & 3: Web frontend with authentication and tracking features

- Initialize Next.js 14 web application with Material UI and TypeScript
- Implement authentication (login/register) with device fingerprint
- Create mobile-first responsive layout with app shell pattern
- Add tracking pages for feeding, sleep, and diaper changes
- Implement activity history with filtering
- Configure backend CORS for web frontend (port 3030)
- Update backend port to 3020, frontend to 3030
- Fix API response handling for auth endpoints

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
andupetcu
2025-09-30 21:21:22 +03:00
parent 1de21044d6
commit 37227369d3
32 changed files with 11584 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
import axios from 'axios';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
export const apiClient = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
// Request interceptor to add auth token
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('accessToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor to handle token refresh
apiClient.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
// If error is 401 and we haven't tried to refresh yet
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) {
throw new Error('No refresh token');
}
const response = await axios.post(`${API_BASE_URL}/api/v1/auth/refresh`, {
refreshToken,
});
const { accessToken } = response.data;
localStorage.setItem('accessToken', accessToken);
// Retry original request with new token
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
return apiClient(originalRequest);
} catch (refreshError) {
// Refresh failed, clear tokens and redirect to login
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
window.location.href = '/login';
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
export default apiClient;

View File

@@ -0,0 +1,208 @@
'use client';
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import apiClient from '@/lib/api/client';
export interface User {
id: string;
email: string;
name: string;
role: string;
}
export interface LoginCredentials {
email: string;
password: string;
deviceFingerprint?: string;
}
export interface RegisterData {
email: string;
password: string;
name: string;
role?: string;
}
interface AuthContextType {
user: User | null;
isLoading: boolean;
isAuthenticated: boolean;
login: (credentials: LoginCredentials) => Promise<void>;
register: (data: RegisterData) => Promise<void>;
logout: () => Promise<void>;
refreshUser: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
const isAuthenticated = !!user;
// Check authentication status on mount
useEffect(() => {
checkAuth();
}, []);
const checkAuth = async () => {
const token = localStorage.getItem('accessToken');
if (!token) {
setIsLoading(false);
return;
}
try {
const response = await apiClient.get('/api/v1/auth/me');
setUser(response.data.data);
} catch (error) {
console.error('Auth check failed:', error);
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
} finally {
setIsLoading(false);
}
};
const login = async (credentials: LoginCredentials) => {
try {
const deviceInfo = {
deviceId: generateDeviceFingerprint(),
platform: 'web',
model: navigator.userAgent,
osVersion: navigator.platform,
};
const response = await apiClient.post('/api/v1/auth/login', {
email: credentials.email,
password: credentials.password,
deviceInfo,
});
// Backend returns { success, data: { user, tokens } }
const { data: responseData } = response.data;
const { tokens, user: userData } = responseData;
localStorage.setItem('accessToken', tokens.accessToken);
localStorage.setItem('refreshToken', tokens.refreshToken);
setUser(userData);
router.push('/');
} catch (error: any) {
console.error('Login failed:', error);
throw new Error(error.response?.data?.message || 'Login failed');
}
};
const register = async (data: RegisterData) => {
try {
const deviceInfo = {
deviceId: generateDeviceFingerprint(),
platform: 'web',
model: navigator.userAgent,
osVersion: navigator.platform,
};
const response = await apiClient.post('/api/v1/auth/register', {
email: data.email,
password: data.password,
name: data.name,
deviceInfo,
});
// Backend returns { success, data: { user, family, tokens } }
const { data: responseData } = response.data;
const { tokens, user: userData } = responseData;
if (!tokens?.accessToken || !tokens?.refreshToken) {
throw new Error('Invalid response from server');
}
const { accessToken, refreshToken } = tokens;
localStorage.setItem('accessToken', accessToken);
localStorage.setItem('refreshToken', refreshToken);
setUser(userData);
// Redirect to onboarding
router.push('/onboarding');
} catch (error: any) {
console.error('Registration failed:', error);
throw new Error(error.response?.data?.message || error.message || 'Registration failed');
}
};
const logout = async () => {
try {
await apiClient.post('/api/v1/auth/logout');
} catch (error) {
console.error('Logout failed:', error);
} finally {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
setUser(null);
router.push('/login');
}
};
const refreshUser = async () => {
try {
const response = await apiClient.get('/api/v1/auth/me');
setUser(response.data.data);
} catch (error) {
console.error('Failed to refresh user:', error);
}
};
return (
<AuthContext.Provider
value={{
user,
isLoading,
isAuthenticated,
login,
register,
logout,
refreshUser,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
// Helper function to generate a simple device fingerprint
function generateDeviceFingerprint(): string {
const navigator = window.navigator;
const screen = window.screen;
const data = [
navigator.userAgent,
navigator.language,
screen.colorDepth,
screen.width,
screen.height,
new Date().getTimezoneOffset(),
].join('|');
// Simple hash function
let hash = 0;
for (let i = 0; i < data.length; i++) {
const char = data.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash.toString(36);
}

View File

@@ -0,0 +1,140 @@
import apiClient from '@/lib/api/client';
export interface FeedingData {
childId: string;
type: 'breast_left' | 'breast_right' | 'breast_both' | 'bottle' | 'solid';
duration?: number;
amount?: number;
unit?: 'ml' | 'oz';
notes?: string;
timestamp?: string;
}
export interface SleepData {
childId: string;
startTime: string;
endTime: string;
quality: 'excellent' | 'good' | 'fair' | 'poor';
notes?: string;
}
export interface DiaperData {
childId: string;
type: 'wet' | 'dirty' | 'both' | 'clean';
timestamp: string;
rash: boolean;
notes?: string;
}
export interface Activity {
id: string;
childId: string;
type: 'feeding' | 'sleep' | 'diaper';
timestamp: string;
data: Record<string, any>;
createdAt: string;
updatedAt: string;
}
export interface DailySummary {
date: string;
feedingCount: number;
sleepHours: number;
diaperCount: number;
activities: Activity[];
}
class TrackingService {
async logFeeding(data: FeedingData): Promise<Activity> {
const response = await apiClient.post('/api/v1/activities', {
childId: data.childId,
type: 'feeding',
timestamp: data.timestamp || new Date().toISOString(),
data: {
feedingType: data.type,
duration: data.duration,
amount: data.amount,
unit: data.unit,
notes: data.notes,
},
});
return response.data.data;
}
async logSleep(data: SleepData): Promise<Activity> {
const response = await apiClient.post('/api/v1/activities', {
childId: data.childId,
type: 'sleep',
timestamp: data.startTime,
data: {
startTime: data.startTime,
endTime: data.endTime,
quality: data.quality,
duration: this.calculateDuration(data.startTime, data.endTime),
notes: data.notes,
},
});
return response.data.data;
}
async logDiaper(data: DiaperData): Promise<Activity> {
const response = await apiClient.post('/api/v1/activities', {
childId: data.childId,
type: 'diaper',
timestamp: data.timestamp,
data: {
diaperType: data.type,
rash: data.rash,
notes: data.notes,
},
});
return response.data.data;
}
async getActivities(childId: string, filters?: {
type?: string;
startDate?: string;
endDate?: string;
limit?: number;
}): Promise<Activity[]> {
const params = new URLSearchParams({
childId,
...filters,
} as Record<string, string>);
const response = await apiClient.get(`/api/v1/activities?${params.toString()}`);
return response.data.data;
}
async getActivityById(activityId: string): Promise<Activity> {
const response = await apiClient.get(`/api/v1/activities/${activityId}`);
return response.data.data;
}
async updateActivity(activityId: string, data: Partial<Activity>): Promise<Activity> {
const response = await apiClient.patch(`/api/v1/activities/${activityId}`, data);
return response.data.data;
}
async deleteActivity(activityId: string): Promise<void> {
await apiClient.delete(`/api/v1/activities/${activityId}`);
}
async getDailySummary(childId: string, date?: string): Promise<DailySummary> {
const params = new URLSearchParams({
childId,
date: date || new Date().toISOString().split('T')[0],
});
const response = await apiClient.get(`/api/v1/activities/daily-summary?${params.toString()}`);
return response.data.data;
}
private calculateDuration(startTime: string, endTime: string): number {
const start = new Date(startTime);
const end = new Date(endTime);
return Math.floor((end.getTime() - start.getTime()) / 1000 / 60); // duration in minutes
}
}
export const trackingService = new TrackingService();