Calog is a comprehensive fitness tracking and calorie management platform designed for React Native. Built with modern technologies and secure authentication, it provides users with advanced body composition analysis, multi-language support, and personalized fitness goals.
- π Introduction
- β‘ Tech Stack
- β¨ Key Features
- π Project Structure
- π§ Environment Variables
- πββοΈ Getting Started
- π API Endpoints
- π Security Features
- π€ Contributing
- π License
Calog is a full-stack fitness tracking application that combines React Native with a Node.js backend to deliver a comprehensive health and fitness management experience. The platform features advanced body composition analysis using the U.S. Navy Method, multi-language support with Google Translate integration, and secure authentication with persistent login capabilities.
Smart Calorie Tracking: Scan QR codes from food products to instantly log calories and track your daily nutrition intake. Monitor your calorie consumption with real-time tracking and personalized daily calorie goals based on your fitness objectives.
Daily Calorie Management: Set personalized daily calorie targets based on your weight goals (lose, maintain, or gain weight) and activity level. Get real-time feedback on your progress and recommendations to stay on track with your fitness journey.
Monthly Statistics & Calendar Tracking: View comprehensive monthly statistics including diet summary (days within recommended range, below BMR, above required) and calorie statistics (total needed, consumed, deficit needed, deficit achieved). Navigate through months with an interactive calendar to track your progress over time.
- QR Code Scanning: Scan food product barcodes using camera integration
- Open Food Facts Integration: Real-time food database lookup with comprehensive nutrition data
- Food Diary: Track daily food intake with detailed nutrition breakdown
- Manual Food Entry: Add food items manually when scanning isn't available
- Nutrition Analysis: Complete macronutrient tracking (calories, protein, carbs, fat, fiber, etc.)
- Meal Categorization: Organize food by meal types (breakfast, lunch, dinner, snacks)
- Real-time Calorie Tracking: Calories & Nutrition dashboard automatically fetches and displays data from meal logs database
- My Food Section: Access saved foods from database directly in search modal
- Auto-fetch Nutrients: Automatically fetches missing macronutrients (protein, carbs, fat) from OpenFoodFacts API when available
- Visual Feedback: Loading animations on add buttons, progress bars change color when goals exceeded
- Google OAuth Integration: Secure sign-in with Google accounts
- JWT Token Management: Access tokens (15min) and refresh tokens (7 days)
- Keychain Storage: Secure token storage using device keychain
- Biometric Protection: Enhanced security with fingerprint/face recognition
- Persistent Login: Users stay logged in across app restarts
- Auto-refresh: Seamless token renewal for uninterrupted experience
- U.S. Navy Method: Accurate body fat percentage calculation
- Body Measurements Tracking: Comprehensive tracking of neck, waist, hip, bicep, and thigh measurements
- Fitness Metrics: BMI, Body Fat Mass, Lean Body Mass, and FFMI calculations
- Measurement History: Track progress over time with trend analysis
- Measurement Logs: View and manage historical measurement data
- Trend Indicators: Visual indicators showing measurement changes (up/down/same)
- Weight Goals: Lose, gain, or maintain weight with target setting
- Calorie Calculation: TDEE calculation using Mifflin-St Jeor equation
- Activity Level Assessment: Sedentary to very active lifestyle options
- Diet Mode Selection: Choose from 9 predefined diet plans (Balanced, Low Carb, High Protein, Keto, Atkins, Paleo, Mediterranean, DASH, Custom)
- Custom Macronutrient Ratios: Fine-tune carb/protein/fat percentages with wheel picker interface
- Macro Validation: Automatic validation ensuring macronutrients total exactly 100%
- Diet Plan Persistence: Save and sync diet preferences across devices
- Interactive Onboarding: Multi-slide introduction with smooth transitions
- Welcome & Value Proposition: Clear app benefits and features explanation
- Basic Profile Setup: Collect essential user information (age, gender, height, weight)
- Goal Setting: Personalized fitness goal configuration
- Profile Validation: Real-time form validation with user feedback
- Local Storage: Offline profile saving with cloud sync when available
- Dark/Light Mode: Complete theme system with NativeWind v4
- Theme Persistence: User preference saved to AsyncStorage
- Dynamic Components: Theme-aware styling across all screens
- Bottom Tab Navigation: Intuitive navigation between main app sections
- Modal Interfaces: Smooth modal presentations for settings and data entry
- Wheel Picker Components: Intuitive number selection for measurements and macros
- Custom UI Components: Reusable components with consistent styling
- Daily Calorie Tracking: Monitor calorie intake vs. goals with real-time updates from database
- Macronutrient Progress: Visual progress bars for carbs, protein, fat, and fiber with color-coded warnings
- Weekly/Monthly Views: Switch between different time periods
- Calendar Integration: Visual calendar for tracking progress with monthly statistics
- Monthly Statistics Dashboard: Comprehensive monthly tracking with:
- Diet Summary: Days eating within recommended range (Β±5%), days below BMR, days above required amount
- Calorie Statistics: Total calories needed, consumed, deficit needed, and deficit achieved for the month
- Automatic Calculation: Real-time calculation from meal logs with quantity-based calorie adjustments
- Progress Visualization: Charts and graphs for fitness metrics
- Analytics Dashboard: Comprehensive overview of health and fitness data
- Meal Details Overlay: Visual kcal display on meal icons when meals have logged entries
- Static Translations: Dictionary-based translations for UI elements
- Dynamic Translation: Google Translate API integration for dynamic content
- Supported Languages: English, Finnish, Vietnamese
- Language Persistence: User preference saved across sessions
- Deep Linking: Custom URL scheme for authentication callbacks
- Camera Integration: Native camera access for barcode scanning
- Image Picker: Camera and gallery integration for photos
- Permission Handling: Proper camera and photo library permissions
- BootSplash: Custom launch screen with logo animation
- Safe Area Support: Proper handling of device notches and safe areas
- RESTful API: Complete REST API with proper HTTP methods and status codes
- MongoDB Integration: Scalable NoSQL database with Mongoose ODM
- JWT Authentication: Secure token-based authentication with refresh token rotation
- Google OAuth: Server-side Google authentication integration
- Cloudinary Integration: Image upload and management for user avatars
- Rate Limiting: API rate limiting to prevent abuse (100 requests per 15 minutes)
- Security Headers: Helmet.js for additional HTTP security headers
- CORS Protection: Cross-origin request security configuration
- Input Validation: Express-validator for request data validation
- Error Handling: Comprehensive error handling with proper HTTP status codes
- Data Models: Structured data models for Users, Food entries, and Measurements
- Middleware Architecture: Modular middleware for authentication and validation
calog/
βββ src/ # React Native source code
β βββ components/ # Reusable UI components
β β βββ ui/ # Base UI components (Button, TextField, etc.)
β β βββ profile/ # Profile-related components
β β βββ home/ # Home screen components
β β βββ CameraView.tsx # Camera integration for barcode scanning
β β βββ DietModeModal.tsx # Diet plan selection modal
β β βββ MeasurementLogModal.tsx # Body measurements tracking
β β βββ FoodItemCard.tsx # Food item display component
β βββ screens/ # Application screens
β β βββ auth/ # Authentication screens (Login, Signup, etc.)
β β βββ onboarding/ # User onboarding flow (4 slides)
β β βββ home/ # Home screens (Diary, CalendarTracking)
β β βββ account/ # Account management screens
β β βββ ScanScreen.tsx # Barcode scanning interface
β β βββ AnalyticsScreen.tsx # Analytics and progress tracking
β β βββ HelpScreen.tsx # Help and support
β βββ navigation/ # Navigation configuration
β β βββ AppNavigator.tsx # Main app navigation
β β βββ AuthNavigator.tsx # Authentication flow navigation
β β βββ MainNavigator.tsx # Main app tab navigation
β β βββ AccountNavigator.tsx # Account section navigation
β βββ services/ # API and external services
β β βββ api/ # API service modules
β β βββ googleSigninService.ts # Google OAuth integration
β β βββ measurementLogStorage.ts # Local measurement storage
β β βββ onboardingStorage.ts # Onboarding data persistence
β β βββ secureStorage.ts # Secure token storage
β βββ hooks/ # Custom React hooks
β β βββ useAuth.ts # Authentication state management
β β βββ useUserProfile.ts # User profile data
β β βββ useFoodItems.ts # Food tracking functionality
β β βββ useProfileSync.ts # Profile synchronization
β βββ contexts/ # React contexts
β β βββ ThemeContext.tsx # Dark/Light theme management
β β βββ index.ts # Context exports
β βββ utils/ # Utility functions
β β βββ authValidation.ts # Authentication validation
β β βββ measurementUtils.ts # Body measurement calculations
β β βββ helpers.ts # General helper functions
β βββ types/ # TypeScript type definitions
β β βββ dietModes.ts # Diet plan type definitions
β β βββ index.ts # Main type exports
β βββ store/ # State management
β βββ index.ts # Zustand store configuration
βββ server/ # Node.js backend
β βββ controllers/ # Route controllers
β β βββ authController.js # Authentication logic
β β βββ profileController.js # Profile management
β βββ models/ # Database models
β β βββ User.js # User schema
β β βββ Food.js # Food entries schema
β β βββ MeasurementLog.js # Body measurements schema
β βββ routes/ # API routes
β β βββ auth.js # Authentication endpoints
β β βββ profile.js # Profile endpoints
β β βββ food.js # Food tracking endpoints
β β βββ measurementLogs.js # Measurement endpoints
β βββ middleware/ # Express middleware
β β βββ auth.js # JWT authentication middleware
β βββ config/ # Configuration files
β β βββ cloudinary.js # Cloudinary setup
β βββ utils/ # Server utilities
β βββ index.js # Utility functions
βββ android/ # Android-specific configuration
βββ ios/ # iOS-specific configuration
βββ assets/ # Static assets (images, fonts)
βββ bootsplash/ # App launch screen assets
βββ images/ # App images and icons
Create .env file in server directory:
# Server Configuration
PORT=4000
NODE_ENV=development
# MongoDB Configuration
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/calog
# JWT Configuration
JWT_ACCESS_SECRET=your-super-secret-access-key-here-make-it-long-and-random
JWT_REFRESH_SECRET=your-super-secret-refresh-key-here-make-it-long-and-random
JWT_ACCESS_EXPIRES=15m
JWT_REFRESH_EXPIRES=7d
# Google OAuth Configuration
GOOGLE_CLIENT_ID=your-google-client-id-here
GOOGLE_CLIENT_SECRET=your-google-client-secret-here
GOOGLE_REDIRECT_URI=http://localhost:4000/auth/google/callback
# React Native App Configuration
REACT_NATIVE_REDIRECT_URL=calog://auth/callback
# Cloudinary Configuration (for avatar uploads)
CLOUDINARY_CLOUD_NAME=your_cloud_name_here
CLOUDINARY_API_KEY=your_api_key_here
CLOUDINARY_API_SECRET=your_api_secret_heregit clone https://github.com/hha297/Calog.git
cd calog# Install React Native dependencies
npm install
# Install server dependencies
cd server
npm install
cd ..- Go to Google Cloud Console
- Create a new project or select existing project
- Enable Google+ API
- Create OAuth 2.0 credentials:
- Application type: Web application
- Authorized redirect URIs:
http://localhost:4000/auth/google/callback
- Save Client ID and Client Secret
Option 1: MongoDB Atlas (Recommended)
- Go to MongoDB Atlas
- Create a free account and new cluster
- Get your connection string and add to
.envfile
Option 2: Local MongoDB
# Install MongoDB locally (if not installed)
# Windows: Download from MongoDB website
# macOS: brew install mongodb-community
# Ubuntu: sudo apt-get install mongodb
# Start MongoDB service
# Windows: Run MongoDB as service or use MongoDB Compass
# macOS: brew services start mongodb-community
# Ubuntu: sudo systemctl start mongod- Sign up at Cloudinary
- Get your Cloud Name, API Key, and API Secret from the Dashboard
- Add them to your server
.envfile
Update src/services/googleSigninService.ts:
const googleConfig = {
issuer: 'https://accounts.google.com',
clientId: 'YOUR_GOOGLE_CLIENT_ID_HERE', // Replace with actual Client ID
redirectUrl: 'calog://auth/callback',
scopes: ['openid', 'profile', 'email'],
// ... rest of config
};Update android/app/src/main/AndroidManifest.xml:
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="calog" />
</intent-filter>
</activity>Update ios/calog/Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>calog</string>
<key>CFBundleURLSchemes</key>
<array>
<string>calog</string>
</array>
</dict>
</array># Start backend
cd server
npm run dev
# In another terminal, start React Native
npm run android # For Android
npm run ios # For iOS
# Or run both together
npm run dev # Android + Backend
npm run dev:ios # iOS + BackendBase URL: https://calog.onrender.com (Production) | http://localhost:4000 (Development)
GET /auth/google- Initiate Google OAuth flowGET /auth/google/callback- Handle Google OAuth callbackGET /auth/me- Get current user info- Headers:
Authorization: Bearer <token>
- Headers:
POST /auth/refresh- Refresh JWT token- Body:
{ refreshToken }
- Body:
POST /auth/logout- Logout- Headers:
Authorization: Bearer <token>
- Headers:
GET /api/profile- Get user profile- Headers:
Authorization: Bearer <token>
- Headers:
PUT /api/profile- Update user profile- Headers:
Authorization: Bearer <token> - Body:
{ profileData }
- Headers:
POST /api/profile/upload-avatar- Upload profile avatar- Headers:
Authorization: Bearer <token> - Body:
FormData: { image }
- Headers:
PUT /api/profile/user-info- Update user info (name, email)- Headers:
Authorization: Bearer <token> - Body:
{ name, email }
- Headers:
POST /api/profile/calculate-calories- Calculate daily calorie goal- Headers:
Authorization: Bearer <token> - Body:
{ profileData }
- Headers:
GET /api/food- Get user's food entries (with pagination, filtering by mealType/date)- Headers:
Authorization: Bearer <token> - Query:
page,limit,mealType,date
- Headers:
POST /api/food- Add new food entry- Headers:
Authorization: Bearer <token> - Body:
{ foodEntry }
- Headers:
PUT /api/food/:id- Update food entry- Headers:
Authorization: Bearer <token> - Body:
{ updatedFoodEntry }
- Headers:
DELETE /api/food/:id- Delete food entry (soft delete)- Headers:
Authorization: Bearer <token>
- Headers:
POST /api/meal-logs/add- Add meal entry to specific date and meal type- Headers:
Authorization: Bearer <token> - Body:
{ date: ISOString, mealType: 'breakfast'|'lunch'|'dinner'|'snack', entry: { code, name, calories, protein, carbs, fat, fiber, quantityGrams, ... } }
- Headers:
GET /api/meal-logs?date=ISOString- Get daily meals for specific date- Headers:
Authorization: Bearer <token> - Query:
date(ISO string)
- Headers:
GET /api/meal-logs?month=X&year=Y- Get monthly meals for specific month and year- Headers:
Authorization: Bearer <token> - Query:
month(1-12),year(e.g., 2025) - Returns: Array of daily meal logs for the specified month, sorted by date ascending
- Headers:
PUT /api/meal-logs/update- Update meal entry by index- Headers:
Authorization: Bearer <token> - Body:
{ date: ISOString, mealType, index: number, entry: { ...updates } }
- Headers:
DELETE /api/meal-logs/remove?date=ISOString&mealType=...&index=...- Remove meal entry- Headers:
Authorization: Bearer <token> - Query:
date,mealType,index
- Headers:
GET /api/measurement-logs- Get user's measurement logs- Headers:
Authorization: Bearer <token>
- Headers:
POST /api/measurement-logs- Add new measurement log- Headers:
Authorization: Bearer <token> - Body:
{ measurements }
- Headers:
PUT /api/measurement-logs/:id- Update measurement log- Headers:
Authorization: Bearer <token> - Body:
{ updatedMeasurements }
- Headers:
DELETE /api/measurement-logs/:id- Delete measurement log- Headers:
Authorization: Bearer <token>
- Headers:
- JWT Authentication: Secure token-based authentication system
- Keychain Integration: Secure storage using react-native-keychain
- Rate Limiting: 100 requests per 15 minutes
- CORS Protection: Cross-origin request security
- Helmet Security Headers: Additional HTTP security headers
- Biometric Protection: Enhanced security with device biometrics
- Non-rolling Refresh Tokens: Maintains same refresh token for better UX
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.