Skip to content
/ Calog Public

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.

Notifications You must be signed in to change notification settings

hha297/Calog

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Calog

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.

πŸ“‹ Table of Contents

πŸš€ Introduction

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.

⚑ Tech Stack

Frontend (React Native)

React Native React TypeScript NativeWind Zustand TanStack Query

Backend (Node.js)

Express.js MongoDB Mongoose JWT Google OAuth Cloudinary

External Services

Open Food Facts

✨ Key Features

πŸ“± QR Code & Food Tracking

  • 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

πŸ” Authentication & Security

  • 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

πŸ“Š Advanced Body Composition Analysis

  • 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)

🎯 Personalized Fitness Goals & Diet Plans

  • 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

πŸš€ User Onboarding Experience

  • 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

πŸ“± Modern UI/UX & Navigation

  • 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

πŸ“Š Analytics & Tracking

  • 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

🌍 Multi-Language Support

  • 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

πŸ“± Cross-Platform Features

  • 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

πŸ–₯️ Backend Features

  • 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

πŸ“ Project Structure

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

πŸ”§ Environment Variables

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_here

πŸƒβ€β™‚οΈ Getting Started

1. Clone the repository

git clone https://github.com/hha297/Calog.git
cd calog

2. Install dependencies

# Install React Native dependencies
npm install

# Install server dependencies
cd server
npm install
cd ..

3. Configure Google OAuth

  1. Go to Google Cloud Console
  2. Create a new project or select existing project
  3. Enable Google+ API
  4. Create OAuth 2.0 credentials:
    • Application type: Web application
    • Authorized redirect URIs: http://localhost:4000/auth/google/callback
  5. Save Client ID and Client Secret

4. Configure MongoDB

Option 1: MongoDB Atlas (Recommended)

  1. Go to MongoDB Atlas
  2. Create a free account and new cluster
  3. Get your connection string and add to .env file

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

5. Configure Cloudinary

  1. Sign up at Cloudinary
  2. Get your Cloud Name, API Key, and API Secret from the Dashboard
  3. Add them to your server .env file

6. Update React Native OAuth Configuration

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
};

7. Configure Deep Linking

Android

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>

iOS

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>

8. Run the application

# 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 + Backend

πŸ”— API Endpoints

Base URL: https://calog.onrender.com (Production) | http://localhost:4000 (Development)

Authentication

  • GET /auth/google - Initiate Google OAuth flow
  • GET /auth/google/callback - Handle Google OAuth callback
  • GET /auth/me - Get current user info
    • Headers: Authorization: Bearer <token>
  • POST /auth/refresh - Refresh JWT token
    • Body: { refreshToken }
  • POST /auth/logout - Logout
    • Headers: Authorization: Bearer <token>

Profile Management

  • GET /api/profile - Get user profile
    • Headers: Authorization: Bearer <token>
  • PUT /api/profile - Update user profile
    • Headers: Authorization: Bearer <token>
    • Body: { profileData }
  • POST /api/profile/upload-avatar - Upload profile avatar
    • Headers: Authorization: Bearer <token>
    • Body: FormData: { image }
  • PUT /api/profile/user-info - Update user info (name, email)
    • Headers: Authorization: Bearer <token>
    • Body: { name, email }
  • POST /api/profile/calculate-calories - Calculate daily calorie goal
    • Headers: Authorization: Bearer <token>
    • Body: { profileData }

Food Tracking

  • GET /api/food - Get user's food entries (with pagination, filtering by mealType/date)
    • Headers: Authorization: Bearer <token>
    • Query: page, limit, mealType, date
  • POST /api/food - Add new food entry
    • Headers: Authorization: Bearer <token>
    • Body: { foodEntry }
  • PUT /api/food/:id - Update food entry
    • Headers: Authorization: Bearer <token>
    • Body: { updatedFoodEntry }
  • DELETE /api/food/:id - Delete food entry (soft delete)
    • Headers: Authorization: Bearer <token>

Meal Logs

  • 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, ... } }
  • GET /api/meal-logs?date=ISOString - Get daily meals for specific date
    • Headers: Authorization: Bearer <token>
    • Query: date (ISO string)
  • 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
  • PUT /api/meal-logs/update - Update meal entry by index
    • Headers: Authorization: Bearer <token>
    • Body: { date: ISOString, mealType, index: number, entry: { ...updates } }
  • DELETE /api/meal-logs/remove?date=ISOString&mealType=...&index=... - Remove meal entry
    • Headers: Authorization: Bearer <token>
    • Query: date, mealType, index

Body Measurements

  • GET /api/measurement-logs - Get user's measurement logs
    • Headers: Authorization: Bearer <token>
  • POST /api/measurement-logs - Add new measurement log
    • Headers: Authorization: Bearer <token>
    • Body: { measurements }
  • PUT /api/measurement-logs/:id - Update measurement log
    • Headers: Authorization: Bearer <token>
    • Body: { updatedMeasurements }
  • DELETE /api/measurement-logs/:id - Delete measurement log
    • Headers: Authorization: Bearer <token>

πŸ”’ Security Features

  • 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

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

About

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.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published