Initial commit, project structure and domain models

This commit is contained in:
2026-04-07 09:14:06 -07:00
commit 7b15086fe5
111 changed files with 19818 additions and 0 deletions

View File

View File

@@ -0,0 +1,13 @@
namespace MicCheck.Api.ApiKeys;
public class ApiKey
{
public int Id { get; init; }
public required string Key { get; set; }
public required string Prefix { get; set; }
public required string Name { get; set; }
public int OrganizationId { get; init; }
public bool IsActive { get; set; }
public DateTimeOffset? ExpiresAt { get; set; }
public DateTimeOffset CreatedAt { get; init; }
}

View File

View File

@@ -0,0 +1,15 @@
namespace MicCheck.Api.Audit;
public class AuditLog
{
public int Id { get; init; }
public required string ResourceType { get; init; }
public required string ResourceId { get; init; }
public required string Action { get; init; }
public string? Changes { get; init; }
public int OrganizationId { get; init; }
public int? ProjectId { get; init; }
public int? EnvironmentId { get; init; }
public int? ActorUserId { get; init; }
public DateTimeOffset CreatedAt { get; init; }
}

View File

@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc;
namespace MicCheck.Api.Auth;
public static class AuthEndpoints
{
public static void MapAuthEndpoints(this WebApplication app)
{
app.MapPost("/auth/token", (
[FromBody] TokenRequest request,
ITokenService tokenService) =>
{
if (string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrWhiteSpace(request.Password))
return Results.BadRequest("Username and password are required.");
var response = tokenService.GenerateToken(request.Username);
return Results.Ok(response);
})
.WithName("GetToken")
.WithTags("Auth")
.AllowAnonymous();
}
}

View File

@@ -0,0 +1,6 @@
namespace MicCheck.Api.Auth;
public interface ITokenService
{
TokenResponse GenerateToken(string username);
}

View File

@@ -0,0 +1,3 @@
namespace MicCheck.Api.Auth;
public record TokenRequest(string Username, string Password);

View File

@@ -0,0 +1,3 @@
namespace MicCheck.Api.Auth;
public record TokenResponse(string Token, DateTime ExpiresAt);

View File

@@ -0,0 +1,43 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace MicCheck.Api.Auth;
public class TokenService(IConfiguration configuration) : ITokenService
{
public TokenResponse GenerateToken(string username)
{
var secretKey = configuration["Jwt:SecretKey"]
?? throw new InvalidOperationException("Jwt:SecretKey is not configured.");
var issuer = configuration["Jwt:Issuer"]
?? throw new InvalidOperationException("Jwt:Issuer is not configured.");
var audience = configuration["Jwt:Audience"]
?? throw new InvalidOperationException("Jwt:Audience is not configured.");
var expiryMinutes = int.Parse(configuration["Jwt:ExpiryMinutes"] ?? "60");
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var expiresAt = DateTime.UtcNow.AddMinutes(expiryMinutes);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Name, username),
new Claim(JwtRegisteredClaimNames.Iat,
DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
ClaimValueTypes.Integer64),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: expiresAt,
signingCredentials: credentials);
return new TokenResponse(new JwtSecurityTokenHandler().WriteToken(token), expiresAt);
}
}

View File

@@ -0,0 +1,19 @@
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
WORKDIR /app
EXPOSE 8080
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY ["src/api/MicCheck.Api/MicCheck.Api.csproj", "src/api/MicCheck.Api/"]
COPY ["src/infrastructure/MicCheck.Infrastructure/MicCheck.Infrastructure.csproj", "src/infrastructure/MicCheck.Infrastructure/"]
RUN dotnet restore "src/api/MicCheck.Api/MicCheck.Api.csproj"
COPY . .
RUN dotnet build "src/api/MicCheck.Api/MicCheck.Api.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "src/api/MicCheck.Api/MicCheck.Api.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MicCheck.Api.dll"]

View File

@@ -0,0 +1,13 @@
using MicCheck.Api.Features;
namespace MicCheck.Api.Environments;
public class Environment
{
public int Id { get; init; }
public required string Name { get; set; }
public required string ApiKey { get; set; }
public int ProjectId { get; init; }
public DateTimeOffset CreatedAt { get; init; }
public ICollection<FeatureState> FeatureStates { get; init; } = [];
}

View File

View File

@@ -0,0 +1,17 @@
namespace MicCheck.Api.Features;
public class Feature
{
public int Id { get; init; }
public required string Name { get; set; }
public FeatureType Type { get; set; }
public string? InitialValue { get; set; }
public string? Description { get; set; }
public bool DefaultEnabled { get; set; }
public int ProjectId { get; init; }
public DateTimeOffset CreatedAt { get; init; }
public ICollection<FeatureState> FeatureStates { get; init; } = [];
public ICollection<Tag> Tags { get; init; } = [];
}
public enum FeatureType { Standard, MultiVariate }

View File

@@ -0,0 +1,11 @@
namespace MicCheck.Api.Features;
public class FeatureSegment
{
public int Id { get; init; }
public int FeatureId { get; init; }
public int SegmentId { get; init; }
public int EnvironmentId { get; init; }
public int Priority { get; set; }
public FeatureState? FeatureState { get; set; }
}

View File

@@ -0,0 +1,15 @@
namespace MicCheck.Api.Features;
public class FeatureState
{
public int Id { get; init; }
public int FeatureId { get; init; }
public int EnvironmentId { get; init; }
public int? IdentityId { get; set; }
public bool Enabled { get; set; }
public string? Value { get; set; }
public int? FeatureSegmentId { get; set; }
public DateTimeOffset CreatedAt { get; init; }
public DateTimeOffset UpdatedAt { get; set; }
public int Version { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace MicCheck.Api.Features;
public class FeatureStateResult
{
public required Feature Feature { get; init; }
public bool Enabled { get; init; }
public string? Value { get; init; }
}

View File

@@ -0,0 +1,9 @@
namespace MicCheck.Api.Features;
public class Tag
{
public int Id { get; init; }
public required string Label { get; set; }
public required string Color { get; set; }
public int ProjectId { get; init; }
}

View File

View File

@@ -0,0 +1,13 @@
using MicCheck.Api.Features;
namespace MicCheck.Api.Identities;
public class Identity
{
public int Id { get; init; }
public required string Identifier { get; set; }
public int EnvironmentId { get; init; }
public DateTimeOffset CreatedAt { get; init; }
public ICollection<IdentityTrait> Traits { get; init; } = [];
public ICollection<FeatureState> FeatureStateOverrides { get; init; } = [];
}

View File

@@ -0,0 +1,12 @@
namespace MicCheck.Api.Identities;
public class IdentityTrait
{
public int Id { get; init; }
public int IdentityId { get; init; }
public required string Key { get; set; }
public required string Value { get; set; }
public TraitValueType ValueType { get; set; }
}
public enum TraitValueType { String, Integer, Float, Boolean }

View File

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.5" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" />
<PackageReference Include="Scalar.AspNetCore" Version="2.6.0" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.16.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../infrastructure/MicCheck.Infrastructure/MicCheck.Infrastructure.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,14 @@
using MicCheck.Api.ApiKeys;
using MicCheck.Api.Projects;
namespace MicCheck.Api.Organizations;
public class Organization
{
public int Id { get; init; }
public required string Name { get; set; }
public DateTimeOffset CreatedAt { get; init; }
public ICollection<Project> Projects { get; init; } = [];
public ICollection<OrganizationUser> Members { get; init; } = [];
public ICollection<ApiKey> ApiKeys { get; init; } = [];
}

View File

@@ -0,0 +1,10 @@
namespace MicCheck.Api.Organizations;
public class OrganizationUser
{
public int OrganizationId { get; init; }
public int UserId { get; init; }
public OrganizationRole Role { get; set; }
}
public enum OrganizationRole { User, Admin }

View File

@@ -0,0 +1,86 @@
using System.Text;
using System.Threading.RateLimiting;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.IdentityModel.Tokens;
using MicCheck.Api.Auth;
using Scalar.AspNetCore;
using Serilog;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((context, services, config) =>
config.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.WriteTo.Console());
builder.Services.AddOpenApi();
builder.Services.AddControllers();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"]!))
};
});
builder.Services.AddAuthorization();
builder.Services.AddRateLimiter(options =>
options.AddFixedWindowLimiter("AdminApi", limiter =>
{
limiter.PermitLimit = 500;
limiter.Window = TimeSpan.FromMinutes(1);
limiter.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
limiter.QueueLimit = 0;
}));
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
builder.Services.AddScoped<ITokenService, TokenService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
app.UseSerilogRequestLogging();
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapAuthEndpoints();
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
public partial class Program { }

View File

View File

@@ -0,0 +1,17 @@
using MicCheck.Api.Features;
using MicCheck.Api.Segments;
using AppEnvironment = MicCheck.Api.Environments.Environment;
namespace MicCheck.Api.Projects;
public class Project
{
public int Id { get; init; }
public required string Name { get; set; }
public int OrganizationId { get; init; }
public DateTimeOffset CreatedAt { get; init; }
public bool HideDisabledFlags { get; set; }
public ICollection<AppEnvironment> Environments { get; init; } = [];
public ICollection<Feature> Features { get; init; } = [];
public ICollection<Segment> Segments { get; init; } = [];
}

View File

View File

@@ -0,0 +1,10 @@
namespace MicCheck.Api.Segments;
public class Segment
{
public int Id { get; init; }
public required string Name { get; set; }
public int ProjectId { get; init; }
public DateTimeOffset CreatedAt { get; init; }
public ICollection<SegmentRule> Rules { get; init; } = [];
}

View File

@@ -0,0 +1,31 @@
namespace MicCheck.Api.Segments;
public class SegmentCondition
{
public int Id { get; init; }
public int RuleId { get; init; }
public required string Property { get; set; }
public SegmentConditionOperator Operator { get; set; }
public required string Value { get; set; }
}
public enum SegmentConditionOperator
{
Equal,
NotEqual,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
Contains,
NotContains,
Regex,
IsSet,
IsNotSet,
In,
NotIn,
PercentageSplit,
ModuloValueDivisorRemainder,
IsTrue,
IsFalse
}

View File

@@ -0,0 +1,13 @@
namespace MicCheck.Api.Segments;
public class SegmentRule
{
public int Id { get; init; }
public int SegmentId { get; init; }
public int? ParentRuleId { get; set; }
public SegmentRuleType Type { get; set; }
public ICollection<SegmentCondition> Conditions { get; init; } = [];
public ICollection<SegmentRule> ChildRules { get; init; } = [];
}
public enum SegmentRuleType { All, Any, None }

View File

View File

@@ -0,0 +1,17 @@
using MicCheck.Api.Organizations;
namespace MicCheck.Api.Users;
public class User
{
public int Id { get; init; }
public required string Email { get; set; }
public required string PasswordHash { get; set; }
public required string FirstName { get; set; }
public required string LastName { get; set; }
public bool IsActive { get; set; }
public bool IsTwoFactorEnabled { get; set; }
public DateTimeOffset CreatedAt { get; init; }
public DateTimeOffset? LastLoginAt { get; set; }
public ICollection<OrganizationUser> Organizations { get; init; } = [];
}

View File

View File

@@ -0,0 +1,15 @@
namespace MicCheck.Api.Webhooks;
public class Webhook
{
public int Id { get; init; }
public required string Url { get; set; }
public string? Secret { get; set; }
public WebhookScope Scope { get; set; }
public int? EnvironmentId { get; set; }
public int? OrganizationId { get; set; }
public bool Enabled { get; set; }
public DateTimeOffset CreatedAt { get; init; }
}
public enum WebhookScope { Environment, Organization }

View File

@@ -0,0 +1,15 @@
namespace MicCheck.Api.Webhooks;
public class WebhookDeliveryLog
{
public int Id { get; init; }
public int WebhookId { get; init; }
public required string EventType { get; init; }
public required string PayloadJson { get; init; }
public int? ResponseStatusCode { get; set; }
public string? ResponseBody { get; set; }
public bool Success { get; set; }
public string? ErrorMessage { get; set; }
public DateTimeOffset AttemptedAt { get; init; }
public TimeSpan Duration { get; set; }
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Information"
}
}
}

View File

@@ -0,0 +1,21 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
}
},
"AllowedHosts": "*",
"Jwt": {
"SecretKey": "change-this-secret-key-in-production-must-be-32-chars",
"Issuer": "MicCheck",
"Audience": "MicCheck",
"ExpiryMinutes": 60
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=miccheck;Username=miccheck;Password=password"
}
}