[FA-10] Adds user service and authentication service

This commit is contained in:
gamer147
2025-11-21 23:08:29 -05:00
parent 303a9e6a63
commit 6b8cf9961b
41 changed files with 910 additions and 29 deletions

View File

@@ -0,0 +1,23 @@
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["FictionArchive.Service.UserService/FictionArchive.Service.UserService.csproj", "FictionArchive.Service.UserService/"]
RUN dotnet restore "FictionArchive.Service.UserService/FictionArchive.Service.UserService.csproj"
COPY . .
WORKDIR "/src/FictionArchive.Service.UserService"
RUN dotnet build "./FictionArchive.Service.UserService.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./FictionArchive.Service.UserService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "FictionArchive.Service.UserService.dll"]

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,13 @@
using FictionArchive.Service.UserService.Models.Database;
using FictionArchive.Service.UserService.Services;
namespace FictionArchive.Service.UserService.GraphQL;
public class Mutation
{
public async Task<User> RegisterUser(string username, string email, string oAuthProviderId,
string? inviterOAuthProviderId, UserManagementService userManagementService)
{
return await userManagementService.RegisterUser(username, email, oAuthProviderId, inviterOAuthProviderId);
}
}

View File

@@ -0,0 +1,12 @@
using FictionArchive.Service.UserService.Models.Database;
using FictionArchive.Service.UserService.Services;
namespace FictionArchive.Service.UserService.GraphQL;
public class Query
{
public async Task<IQueryable<User>> GetUsers(UserManagementService userManagementService)
{
return userManagementService.GetUsers();
}
}

View File

@@ -0,0 +1,77 @@
// <auto-generated />
using System;
using FictionArchive.Service.UserService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NodaTime;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
[DbContext(typeof(UserServiceDbContext))]
[Migration("20251122034145_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Instant>("CreatedTime")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("InviterId")
.HasColumnType("uuid");
b.Property<Instant>("LastUpdatedTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("OAuthProviderId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("InviterId");
b.ToTable("Users");
});
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.HasOne("FictionArchive.Service.UserService.Models.Database.User", "Inviter")
.WithMany()
.HasForeignKey("InviterId");
b.Navigation("Inviter");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using NodaTime;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Username = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
OAuthProviderId = table.Column<string>(type: "text", nullable: false),
Disabled = table.Column<bool>(type: "boolean", nullable: false),
InviterId = table.Column<Guid>(type: "uuid", nullable: true),
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
table.ForeignKey(
name: "FK_Users_Users_InviterId",
column: x => x.InviterId,
principalTable: "Users",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
name: "IX_Users_InviterId",
table: "Users",
column: "InviterId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -0,0 +1,80 @@
// <auto-generated />
using System;
using FictionArchive.Service.UserService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NodaTime;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
[DbContext(typeof(UserServiceDbContext))]
[Migration("20251122040724_UniqueOAuthProviderId")]
partial class UniqueOAuthProviderId
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Instant>("CreatedTime")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("InviterId")
.HasColumnType("uuid");
b.Property<Instant>("LastUpdatedTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("OAuthProviderId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("InviterId");
b.HasIndex("OAuthProviderId")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.HasOne("FictionArchive.Service.UserService.Models.Database.User", "Inviter")
.WithMany()
.HasForeignKey("InviterId");
b.Navigation("Inviter");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
/// <inheritdoc />
public partial class UniqueOAuthProviderId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_Users_OAuthProviderId",
table: "Users",
column: "OAuthProviderId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_OAuthProviderId",
table: "Users");
}
}
}

View File

@@ -0,0 +1,77 @@
// <auto-generated />
using System;
using FictionArchive.Service.UserService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NodaTime;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
[DbContext(typeof(UserServiceDbContext))]
partial class UserServiceDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Instant>("CreatedTime")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("InviterId")
.HasColumnType("uuid");
b.Property<Instant>("LastUpdatedTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("OAuthProviderId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("InviterId");
b.HasIndex("OAuthProviderId")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.HasOne("FictionArchive.Service.UserService.Models.Database.User", "Inviter")
.WithMany()
.HasForeignKey("InviterId");
b.Navigation("Inviter");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,20 @@
using FictionArchive.Service.Shared.Models;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.Service.UserService.Models.Database;
[Index(nameof(OAuthProviderId), IsUnique = true)]
public class User : BaseEntity<Guid>
{
public string Username { get; set; }
public string Email { get; set; }
public string OAuthProviderId { get; set; }
public bool Disabled { get; set; }
/// <summary>
/// The user that generated an invite used by this user.
/// </summary>
public User? Inviter { get; set; }
}

View File

@@ -0,0 +1,16 @@
using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.UserService.Models.IntegrationEvents;
public class AuthUserAddedEvent : IIntegrationEvent
{
public string OAuthProviderId { get; set; }
public string InviterOAuthProviderId { get; set; }
// The email of the user that created the event
public string EventUserEmail { get; set; }
// The username of the user that created the event
public string EventUserUsername { get; set; }
}

View File

@@ -0,0 +1,52 @@
using FictionArchive.Service.Shared.Extensions;
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
using FictionArchive.Service.UserService.GraphQL;
using FictionArchive.Service.UserService.Models.IntegrationEvents;
using FictionArchive.Service.UserService.Services;
using FictionArchive.Service.UserService.Services.EventHandlers;
namespace FictionArchive.Service.UserService;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
#region Event Bus
builder.Services.AddRabbitMQ(opt =>
{
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
})
.Subscribe<AuthUserAddedEvent, AuthUserAddedEventHandler>();
#endregion
#region GraphQL
builder.Services.AddDefaultGraphQl<Query, Mutation>();
#endregion
builder.Services.RegisterDbContext<UserServiceDbContext>(builder.Configuration.GetConnectionString("DefaultConnection"));
builder.Services.AddTransient<UserManagementService>();
builder.Services.AddHealthChecks();
var app = builder.Build();
// Update database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<UserServiceDbContext>();
dbContext.UpdateDatabase();
}
app.MapGraphQL();
app.MapHealthChecks("/healthz");
app.Run();
}
}

View File

@@ -0,0 +1,39 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:20480",
"sslPort": 44309
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5145",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "graphql",
"applicationUrl": "https://localhost:7157;http://localhost:5145",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,23 @@
using FictionArchive.Service.Shared.Services.EventBus;
using FictionArchive.Service.UserService.Models.IntegrationEvents;
using FictionArchive.Service.UserService.Models.Database;
using Microsoft.EntityFrameworkCore; // Add this line to include the UserModel
namespace FictionArchive.Service.UserService.Services.EventHandlers;
public class AuthUserAddedEventHandler : IIntegrationEventHandler<AuthUserAddedEvent>
{
private readonly UserManagementService _userManagementService;
private readonly ILogger<AuthUserAddedEventHandler> _logger;
public AuthUserAddedEventHandler(UserServiceDbContext dbContext, ILogger<AuthUserAddedEventHandler> logger, UserManagementService userManagementService)
{
_logger = logger;
_userManagementService = userManagementService;
}
public async Task Handle(AuthUserAddedEvent @event)
{
await _userManagementService.RegisterUser(@event.EventUserUsername, @event.EventUserEmail, @event.OAuthProviderId, @event.InviterOAuthProviderId);
}
}

View File

@@ -0,0 +1,45 @@
using FictionArchive.Service.UserService.Models.Database;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.Service.UserService.Services;
public class UserManagementService
{
private readonly ILogger<UserManagementService> _logger;
private readonly UserServiceDbContext _dbContext;
public UserManagementService(UserServiceDbContext dbContext, ILogger<UserManagementService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<User> RegisterUser(string username, string email, string oAuthProviderId,
string? inviterOAuthProviderId)
{
var newUser = new User();
User? inviter =
await _dbContext.Users.FirstOrDefaultAsync(user => user.OAuthProviderId == inviterOAuthProviderId);
if (inviter == null && inviterOAuthProviderId != null)
{
_logger.LogCritical(
"A user with OAuthProviderId {OAuthProviderId} was marked as having inviter with OAuthProviderId {inviterOAuthProviderId}, but no user was found with that value.",
inviterOAuthProviderId, inviterOAuthProviderId);
newUser.Disabled = true;
}
newUser.Username = username;
newUser.Email = email;
newUser.OAuthProviderId = oAuthProviderId;
_dbContext.Users.Add(newUser); // Add the new user to the DbContext
await _dbContext.SaveChangesAsync(); // Save changes to the database
return newUser;
}
public IQueryable<User> GetUsers()
{
return _dbContext.Users.AsQueryable();
}
}

View File

@@ -0,0 +1,14 @@
using FictionArchive.Service.Shared.Services.Database;
using FictionArchive.Service.UserService.Models.Database;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.Service.UserService.Services;
public class UserServiceDbContext : FictionArchiveDbContext
{
public DbSet<User> Users { get; set; }
public UserServiceDbContext(DbContextOptions options, ILogger<UserServiceDbContext> logger) : base(options, logger)
{
}
}

View File

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

View File

@@ -0,0 +1,16 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=FictionArchive_UserService;Username=postgres;password=postgres"
},
"RabbitMQ": {
"ConnectionString": "amqp://localhost",
"ClientIdentifier": "UserService"
},
"AllowedHosts": "*"
}