Skip to main content

Configuration Guide

This guide covers all configuration aspects of the Happy Habitat backend, including database setup, JWT configuration, CORS, environment settings, and deployment considerations.

Configuration Files

The main configuration file is appsettings.json located in the API project: Path: HappyHabitat.API/appsettings.json

Development Configuration

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(local);Database=HappyHabitat;Trusted_Connection=True;TrustServerCertificate=True;"
  },
  "Database": {
    "RecreateOnStartup": false
  },
  "Jwt": {
    "Key": "YourSuperSecretKeyThatShouldBeAtLeast32CharactersLong!",
    "Issuer": "HappyHabitat",
    "Audience": "HappyHabitatUsers"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Production Configuration

Create appsettings.Production.json for production-specific settings:
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=prod-server;Database=HappyHabitat;User Id=dbuser;Password=***;TrustServerCertificate=False;Encrypt=True;"
  },
  "Database": {
    "RecreateOnStartup": false
  },
  "Jwt": {
    "Key": "<use-environment-variable>",
    "Issuer": "HappyHabitat",
    "Audience": "HappyHabitatUsers"
  },
  "Cors": {
    "Origins": "https://app.happyhabitat.com;https://www.happyhabitat.com"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.AspNetCore": "Error"
    }
  },
  "AllowedHosts": "*.happyhabitat.com"
}
Never commit production secrets to version control! Use environment variables or secure secret management systems.

Database Configuration

Connection String

The connection string format depends on your authentication method: Windows Authentication (Development):
Server=(local);Database=HappyHabitat;Trusted_Connection=True;TrustServerCertificate=True;
SQL Server Authentication:
Server=server-name;Database=HappyHabitat;User Id=username;Password=password;TrustServerCertificate=True;
Azure SQL Database:
Server=tcp:server.database.windows.net,1433;Database=HappyHabitat;User Id=username@server;Password=password;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

Database Recreation (Development Only)

DANGEROUS: This setting will delete and recreate the database on every startup!
{
  "Database": {
    "RecreateOnStartup": true
  }
}
Use cases:
  • Rapid development and schema changes
  • Testing fresh database states
  • Local development environments only
Safety Checks: The application prevents accidental data loss (Program.cs:248-252):
if (isProduction && recreateDatabase)
    throw new InvalidOperationException(
        "Database:RecreateOnStartup cannot be enabled in production."
    );

Database Initialization

On startup, the application automatically:
  1. Applies Migrations - Creates or updates database schema
  2. Seeds Initial Data - Creates roles, vehicle types, default admin
  3. Seeds Dummy Data - (Development only) Creates test users and communities
Source: Program.cs:240-276

Manual Seeding

Run database seeding without starting the server:
dotnet run --project HappyHabitat.API --seed-only

Database Migrations

Creating Migrations

When you modify entity models, create a new migration:
dotnet ef migrations add MigrationName \
  --project HappyHabitat.Infrastructure \
  --startup-project HappyHabitat.API

Applying Migrations

Automatic (on startup): Migrations are applied automatically when the application starts. Manual:
dotnet ef database update \
  --project HappyHabitat.Infrastructure \
  --startup-project HappyHabitat.API

Viewing Migration History

dotnet ef migrations list \
  --project HappyHabitat.Infrastructure \
  --startup-project HappyHabitat.API

Rolling Back Migrations

dotnet ef database update PreviousMigrationName \
  --project HappyHabitat.Infrastructure \
  --startup-project HappyHabitat.API

Removing Last Migration

dotnet ef migrations remove \
  --project HappyHabitat.Infrastructure \
  --startup-project HappyHabitat.API
Only remove migrations that haven’t been applied to production databases.

JWT Configuration

Settings

{
  "Jwt": {
    "Key": "secret-key-at-least-32-characters-long",
    "Issuer": "HappyHabitat",
    "Audience": "HappyHabitatUsers"
  }
}

Key Requirements

Security Requirements

  • Minimum length: 32 characters
  • Complexity: Use random, cryptographically secure strings
  • Uniqueness: Different key for each environment
  • Rotation: Change periodically (invalidates existing tokens)

Generating a Secure Key

PowerShell:
$bytes = New-Object byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($bytes)
[Convert]::ToBase64String($bytes)
Bash:
openssl rand -base64 32
Node.js:
require('crypto').randomBytes(32).toString('base64')

Environment Variables

Recommended for production:
export JWT__KEY="your-secure-key-here"
export JWT__ISSUER="HappyHabitat"
export JWT__AUDIENCE="HappyHabitatUsers"
Double underscores (__) in environment variables map to nested JSON configuration.

Token Lifetime

Token lifetime is configured in the JWT service. Default is typically 24 hours. To customize, modify JwtService in HappyHabitat.Infrastructure/Services/JwtService.cs.

CORS Configuration

Development

Default development origins (Program.cs:56):
corsOrigins = new[] { 
    "http://localhost:4200", 
    "https://localhost:4200", 
    "http://localhost:5080", 
    "https://localhost:7177" 
};

Production

Configuration:
{
  "Cors": {
    "Origins": "https://app.example.com;https://www.example.com"
  }
}
Multiple origins: Separate with semicolons (;) Safety Checks: The application enforces CORS configuration in production (Program.cs:54-56):
if (isProduction)
    throw new InvalidOperationException(
        "In production, Cors:Origins must be configured with allowed frontend origins."
    );

CORS Policy

Current policy (Program.cs:60-66):
policy.WithOrigins(corsOrigins)
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials();

File Upload Configuration

Request Size Limits

Global Limit (Program.cs:18-21):
options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10 MB
Document Upload Limit:
[RequestSizeLimit(20 * 1024 * 1024)] // 20 MB

Upload Directory

Uploaded files are stored in: Path: {ContentRoot}/uploads/documents/{communityId}/{category}/{residentId}/{fileName} Configuration (Program.cs:226-233):
var uploadsPath = Path.Combine(app.Environment.ContentRootPath, "uploads");
if (!Directory.Exists(uploadsPath))
    Directory.CreateDirectory(uploadsPath);
    
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(uploadsPath),
    RequestPath = "/uploads"
});
Ensure the application has write permissions to the uploads directory.

Logging Configuration

Log Levels

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore": "Information"
    }
  }
}
Available Levels:
  • Trace - Most detailed
  • Debug - Debugging information
  • Information - General information
  • Warning - Warning messages
  • Error - Error messages
  • Critical - Critical failures
  • None - Disable logging

Production Logging

Recommended production configuration:
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.AspNetCore": "Error",
      "Microsoft.EntityFrameworkCore": "Error"
    }
  }
}

Logging Providers

Add additional logging providers for production: Application Insights:
builder.Services.AddApplicationInsightsTelemetry();
Serilog:
builder.Host.UseSerilog();

Seed Data

Initial Seeder

Location: HappyHabitat.Infrastructure/Seeders/InitialSeeder.cs Creates:
  • 6 roles (SYSTEM_ADMIN, ADMIN_COMPANY, etc.)
  • 5 vehicle types
  • Default admin user (elgrandeahc)
  • 10 ticket categories
  • 6 ticket statuses

Dummy Seeder (Development Only)

Location: HappyHabitat.Infrastructure/Seeders/DummySeeder.cs Creates:
  • 10 test users with different roles
  • 13 communities with realistic data
  • 10 residents per community
  • 3 company administrators
  • Vehicles, pets, and visits for test users
  • 11 seasonal banners
  • Community announcements
Dummy data is only seeded in Development environment (Program.cs:270-275).

Authorization Policies

Authorization policies are configured in Program.cs:113-119:
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminCompanyOrSystemAdmin", policy =>
        policy.RequireRole("ADMIN_COMPANY", "SYSTEM_ADMIN"));
    options.AddPolicy("SystemAdminOnly", policy =>
        policy.RequireRole("SYSTEM_ADMIN"));
});
Usage in Controllers:
[Authorize(Policy = "AdminCompanyOrSystemAdmin")]
public class CommunitiesController : ControllerBase
{
    // ...
}

Service Registration

All application services are registered in Program.cs:121-150:
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<ICommunityService, CommunityService>();
// ... etc
Services use Scoped lifetime by default, meaning one instance per HTTP request.

Swagger Configuration

Swagger is enabled in Development for API documentation and testing. Configuration (Program.cs:156-198):
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Happy Habitat API",
        Version = "v1",
        Description = "API for Happy Habitat Management System"
    });
    
    // JWT Authentication
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme.",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
});
Access Swagger:
  • URL: http://localhost:5080/ (Development only)
  • JSON: http://localhost:5080/swagger/v1/swagger.json

Environment-Specific Configuration

Detecting Environment

var isProduction = builder.Environment.IsProduction();
var isDevelopment = builder.Environment.IsDevelopment();
var isStaging = builder.Environment.IsStaging();

Setting Environment

Command Line:
dotnet run --environment Production
Environment Variable:
export ASPNETCORE_ENVIRONMENT=Production
dotnet run
launchSettings.json:
{
  "profiles": {
    "Development": {
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Error Handling

Global exception handling middleware is configured (Program.cs:214):
app.UseMiddleware<ExceptionHandlingMiddleware>();
Returns standardized error responses:
{
  "code": "INTERNAL_SERVER_ERROR",
  "message": "An unexpected error occurred.",
  "traceId": "00-abc123..."
}

HTTPS Configuration

Development: HTTPS redirection is disabled to avoid CORS issues (Program.cs:220-223). Production: HTTPS is enforced:
if (!app.Environment.IsDevelopment())
{
    app.UseHttpsRedirection();
}
Certificate Configuration: For production, configure SSL certificates in hosting environment or reverse proxy.

Health Checks

Implement health checks for monitoring:
builder.Services.AddHealthChecks()
    .AddDbContextCheck<ApplicationDbContext>();

app.MapHealthChecks("/health");

Performance Configuration

Response Compression

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
});

Response Caching

builder.Services.AddResponseCaching();
app.UseResponseCaching();

Deployment Checklist

1

Security

  • Change JWT secret key
  • Configure CORS with production origins
  • Use SQL authentication instead of Windows auth
  • Enable HTTPS and SSL certificates
  • Set Database:RecreateOnStartup to false
2

Database

  • Create production database
  • Apply migrations
  • Configure connection string
  • Test database connectivity
  • Set up backup schedule
3

Configuration

  • Set environment to Production
  • Configure logging to appropriate level
  • Set up application insights or monitoring
  • Configure allowed hosts
  • Review all configuration settings
4

Performance

  • Enable response compression
  • Configure response caching
  • Set appropriate request size limits
  • Optimize database indexes
5

Monitoring

  • Set up health checks
  • Configure application monitoring
  • Set up error tracking
  • Configure alerting

Troubleshooting

Database Connection Issues

Symptoms:
  • “Cannot open database” errors
  • “Login failed for user” errors
Solutions:
  1. Verify connection string format
  2. Check SQL Server is running
  3. Verify firewall allows connections
  4. Test credentials with SQL Server Management Studio
  5. Check TrustServerCertificate setting

CORS Errors

Symptoms:
  • “Access to fetch has been blocked by CORS policy”
  • Browser console shows CORS errors
Solutions:
  1. Verify frontend URL is in Cors:Origins
  2. Check CORS policy includes required methods and headers
  3. Ensure CORS middleware is before authentication
  4. Verify credentials are allowed if needed

JWT Validation Errors

Symptoms:
  • “Signature validation failed” errors
  • “Token expired” errors
Solutions:
  1. Verify JWT key matches between environments
  2. Check issuer and audience settings
  3. Verify token hasn’t expired
  4. Check system clock synchronization

Additional Resources

Build docs developers (and LLMs) love