Skip to content

About

ASP.NET Core Web API powering Forma, a connected fitness platform for workout tracking, nutrition, hydration, and AI-powered insights.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

🧠 Forma — AI-Assisted Fitness Backend API

Forma is an ASP.NET Core Web API backend for a fitness tracking mobile app (Flutter frontend), built with Clean Architecture. It manages workouts, nutrition, hydration, and user profiles, with planned AI-driven coaching features that reason over a user's training and nutrition history.

Status: early stage. Authentication, profile pictures, and workout creation work. Nutrition and hydration are modeled but not exposed through the API yet. For a detailed, code-verified description of the project and its known issues, see Forma.md.


🏗️ Architecture

The solution follows Clean Architecture, split into four projects:

Forma.Api             → Controllers, Middleware, Program.cs (Presentation Layer)
Forma.Application     → Services, DTOs, Validators, Interfaces, Business Logic
Forma.Domain          → Entities, Enums, Repository Interfaces, Core Business Rules
Forma.Infrastructure  → EF Core, Repositories, Security, Email, File Storage

Dependencies point inward: Domain references nothing, Application references only Domain, and Infrastructure implements the interfaces declared in Application and Domain. Api references Application and Infrastructure (only so Program.cs can register the implementations). This keeps business logic decoupled from frameworks, databases, and external services.


⚙️ Tech Stack

  • Framework: ASP.NET Core Web API (.NET 10, controllers)
  • Database: PostgreSQL + Entity Framework Core (Npgsql)
  • Authentication: JWT Bearer tokens
  • Password Hashing: BCrypt
  • Validation: FluentValidation
  • Email: MailKit (Gmail SMTP) for OTP delivery
  • File Storage: Local static file storage (wwwroot/uploads), abstracted behind an interface for future cloud storage support
  • Caching: IMemoryCache for transient OTP storage
  • API Docs: OpenAPI + Scalar UI (Development only)

🚀 Getting Started

Prerequisites

  • .NET 10 SDK
  • PostgreSQL (expected at localhost:5432, database forma_db)
  • A Gmail account with an app password, if you want real OTP emails

1. Clone

git clone https://github.com/FormaOrga/FormaBackend.git
cd FormaBackend

2. Configure secrets

Real values are never stored in appsettings.json (it contains empty placeholders). Set them with .NET User Secrets, from the Forma.Api folder. The project already has a UserSecretsId, so no init is needed:

cd Forma.Api
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Host=localhost;Port=5432;Database=forma_db;Username=postgres;Password=<your-db-password>"
dotnet user-secrets set "JwtSettings:Secret" "<long-random-string, 32+ characters>"
dotnet user-secrets set "EmailSettings:SenderEmail" "<your-gmail-address>"
dotnet user-secrets set "EmailSettings:AppPassword" "<your-gmail-app-password>"

Notes:

  • The key is ConnectionStrings (with an s). A misspelled key silently gives an empty connection string.
  • User Secrets are only loaded in the Development environment. The https launch profile sets it for you.

3. Run

dotnet build
dotnet run --project Forma.Api --launch-profile https

In Development, the app applies pending database migrations automatically at startup and seeds the exercise data (12 chest exercises) on an empty database. In other environments, apply migrations yourself:

dotnet ef database update --project Forma.Infrastructure --startup-project Forma.Api

The API listens on https://localhost:7167 and http://localhost:5106. The Scalar API reference is available in Development at https://localhost:7167/scalar/v1.


✅ Current Features

Authentication & Email Verification

  • OTP-based email verification flow (Pattern A — verify before account creation):
    1. POST /api/auth/send-otp — sends a 6-digit OTP to the provided email
    2. POST /api/auth/verify-otp — verifies the OTP (single-use, 10-minute expiry)
    3. POST /api/auth/register — creates the account only if the email was verified
    4. POST /api/auth/login — authenticates and returns a JWT
  • Passwords hashed with BCrypt, never stored or returned in plain text
  • JWT generation with configurable issuer, audience, secret, and expiry (JwtSettings:ExpiryMinutes, default 60)
  • Request validation with FluentValidation (registration, login, OTP, and workout requests)
  • Global exception handling middleware maps custom exceptions (ConflictException, UnauthorizedException, NotFoundException, ForbiddenException, ArgumentException) to proper HTTP status codes

User Profile

  • POST /api/profile/upload-picture (authenticated) — uploads a profile picture, stores it on disk, and saves the relative URL on the User record
  • Returns the picture's relative URL in the response (for example /uploads/profile-pictures/<userId>.jpg); the file is served as a static file by the API
  • File validation: allowed extensions (.jpg, .jpeg, .png, .webp), 5MB max size
  • Re-uploading overwrites the previous picture (filename keyed by UserId)
  • Uploaded files are git-ignored (wwwroot/uploads/)

Workouts

  • POST /workouts/sync (authenticated) — creates a workout with its exercises and sets in one request. Every call creates a new workout; it is not idempotent yet
  • Set types: Normal, WarmUp, DropSet, SuperSet, FailureSet, Right, Left (the last two are for single-limb sets), plus optional RPE and rest time per set
  • 12 chest exercises are seeded with fixed ids, each mapped to muscles with percentage contributions
  • GET /workouts/{id} exists but is currently broken (see Forma.md, KI-05); listing workouts and listing exercises are not exposed yet

Domain Model

  • User — profile data, training goal (Goal enum), gender, physical stats
  • Workout / WorkoutExercise / Set — full workout logging structure
  • Exercise / ExerciseMuscleInvolvement — exercises mapped to muscles with percentage contribution, designed for future AI-driven muscle activation analysis
  • Meal / FoodItem / MealFoodItem — nutrition logging model with macro and micronutrient values (no API yet)
  • WaterIntake — hydration logging model (no API yet)
  • HydrationService — calculates a user's daily water target from body weight and workout duration (not exposed yet)

🔐 Security Notes

  • The JWT secret, database password, and email credentials are kept out of source control via .NET User Secrets (local development); appsettings.json contains only empty placeholders
  • Login error messages are intentionally generic ("Invalid email or password") to avoid leaking which accounts exist
  • OTPs are single-use and stored only in memory (no DB persistence), with a short-lived "verified" flag bridging OTP verification and final registration
  • Known security gaps are tracked in Forma.md (for example OTP hardening, a unique email index, refresh tokens, and rate limiting)

🚧 In Progress / Planned

  • Finish workouts: GET /exercises, fix GET /workouts/{id}, GET /workouts, idempotent sync, update and delete
  • HydrationController (expose the existing HydrationService through the API)
  • NutritionService + MealController
  • Refresh token support and OTP hardening
  • IAIService — AI-generated coaching advice based on user training/nutrition data
  • Automated tests (xUnit + integration tests)
  • Docker + CI/CD pipeline

🗂️ Project Structure

Forma/
├── Forma.Api/
│   ├── Controllers/
│   │   ├── AuthController.cs
│   │   ├── ProfileController.cs
│   │   └── WorkoutController.cs
│   ├── Middleware/
│   │   └── ExceptionHandlingMiddleware.cs
│   └── Program.cs
│
├── Forma.Application/
│   ├── DTOs/ (Auth, Workout)
│   ├── Exceptions/
│   ├── Interfaces/
│   ├── Services/
│   ├── Settings/
│   └── Validators/ (Auth, Workout)
│
├── Forma.Domain/
│   ├── Common/ (BaseEntity)
│   ├── Entities/
│   ├── Enums/
│   └── Interfaces/ (repository interfaces)
│
└── Forma.Infrastructure/
    ├── Email/
    ├── Persistence/ (DbContext, Migrations, DataSeeder)
    ├── Repositories/
    ├── Security/ (BCryptPasswordHasher, JwtTokenGenerator, OtpService)
    └── Storage/ (LocalFileStorageService)

🧪 Testing the API

A typical end-to-end flow using Scalar, Postman, or similar:

POST /api/auth/send-otp
{ "email": "user@example.com" }

POST /api/auth/verify-otp
{ "email": "user@example.com", "otp": "123456" }

POST /api/auth/register
{ "fullName": "...", "email": "user@example.com", "password": "...", ... }

POST /api/auth/login
{ "email": "user@example.com", "password": "..." }

POST /api/profile/upload-picture   (Authorization: Bearer <token>, form-data: file)

POST /workouts/sync                (Authorization: Bearer <token>)

Example POST /workouts/sync body, using the seeded "Barbell Bench Press" exercise (there is no endpoint to list exercises yet):

{
  "date": "2026-11-20T00:00:00Z",
  "startTime": "2026-11-20T16:00:00Z",
  "endTime": "2026-11-20T17:10:00Z",
  "notes": "Felt strong today",
  "exercises": [
    {
      "exerciseId": "e283a456-dd15-479d-a680-28edc98e168c",
      "order": 1,
      "sets": [
        {
          "setNumber": 1,
          "reps": 12,
          "weight": 40,
          "setType": 1,
          "rpe": 6,
          "restSeconds": 60
        },
        {
          "setNumber": 2,
          "reps": 8,
          "weight": 80,
          "setType": 0,
          "rpe": 8.5,
          "restSeconds": 120
        }
      ]
    }
  ]
}

Send timestamps in UTC, ending in Z.


👤 Author

Ahmed Abdulrahman Amin Backend Developer | ASP.NET Core Enthusiast LinkedIn

About

ASP.NET Core Web API powering Forma, a connected fitness platform for workout tracking, nutrition, hydration, and AI-powered insights.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages