1 Commits

Author SHA1 Message Date
gamer147
6b8cf9961b [FA-10] Adds user service and authentication service 2025-11-21 23:08:29 -05:00
41 changed files with 910 additions and 29 deletions

View File

@@ -0,0 +1,36 @@
using FictionArchive.Service.AuthenticationService.Models.Requests;
using FictionArchive.Service.AuthenticationService.Models.IntegrationEvents;
using FictionArchive.Service.Shared.Services.EventBus;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FictionArchive.Service.AuthenticationService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticationWebhookController : ControllerBase
{
private readonly IEventBus _eventBus;
public AuthenticationWebhookController(IEventBus eventBus)
{
_eventBus = eventBus;
}
[HttpPost(nameof(UserRegistered))]
public async Task<ActionResult> UserRegistered([FromBody] UserRegisteredWebhookPayload payload)
{
var authUserAddedEvent = new AuthUserAddedEvent
{
OAuthProviderId = payload.OAuthProviderId,
InviterOAuthProviderId = payload.InviterOAuthProviderId,
EventUserEmail = payload.EventUserEmail,
EventUserUsername = payload.EventUserUsername
};
await _eventBus.Publish(authUserAddedEvent);
return Ok();
}
}
}

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.AuthenticationService/FictionArchive.Service.AuthenticationService.csproj", "FictionArchive.Service.AuthenticationService/"]
RUN dotnet restore "FictionArchive.Service.AuthenticationService/FictionArchive.Service.AuthenticationService.csproj"
COPY . .
WORKDIR "/src/FictionArchive.Service.AuthenticationService"
RUN dotnet build "./FictionArchive.Service.AuthenticationService.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./FictionArchive.Service.AuthenticationService.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.AuthenticationService.dll"]

View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
</ItemGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Controllers\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@FictionArchive.Service.AuthenticationService_HostAddress = http://localhost:5091
GET {{FictionArchive.Service.AuthenticationService_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,16 @@
using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.AuthenticationService.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,17 @@
namespace FictionArchive.Service.AuthenticationService.Models.Requests;
public class UserRegisteredWebhookPayload
{
// The body of the notification message
public string Body { get; set; }
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,49 @@
using FictionArchive.Service.Shared;
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
namespace FictionArchive.Service.AuthenticationService;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#region Event Bus
builder.Services.AddRabbitMQ(opt =>
{
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
});
#endregion
builder.Services.AddHealthChecks();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapHealthChecks("/healthz");
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}

View File

@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:23522",
"sslPort": 44397
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5091",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7223;http://localhost:5091",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

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

View File

@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"RabbitMQ": {
"ConnectionString": "amqp://localhost",
"ClientIdentifier": "AuthenticationService"
},
"AllowedHosts": "*"
}

View File

@@ -2,7 +2,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class ChapterPullRequestedEvent : IntegrationEvent
public class ChapterPullRequestedEvent : IIntegrationEvent
{
public uint NovelId { get; set; }
public uint ChapterNumber { get; set; }

View File

@@ -2,7 +2,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class NovelUpdateRequestedEvent : IntegrationEvent
public class NovelUpdateRequestedEvent : IIntegrationEvent
{
public string NovelUrl { get; set; }
}

View File

@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class TranslationRequestCompletedEvent : IntegrationEvent
public class TranslationRequestCompletedEvent : IIntegrationEvent
{
/// <summary>
/// Maps this event back to a triggering request.

View File

@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class TranslationRequestCreatedEvent : IntegrationEvent
public class TranslationRequestCreatedEvent : IIntegrationEvent
{
public Guid TranslationRequestId { get; set; }
public Language From { get; set; }

View File

@@ -16,7 +16,7 @@ public class EventBusBuilder<TEventBus> where TEventBus : class, IEventBus
_services.AddSingleton<SubscriptionManager>(_subscriptionManager);
}
public EventBusBuilder<TEventBus> Subscribe<TEvent, TEventHandler>() where TEvent : IntegrationEvent where TEventHandler : class, IIntegrationEventHandler<TEvent>
public EventBusBuilder<TEventBus> Subscribe<TEvent, TEventHandler>() where TEvent : IIntegrationEvent where TEventHandler : class, IIntegrationEventHandler<TEvent>
{
_services.AddKeyedTransient<IIntegrationEventHandler, TEventHandler>(typeof(TEvent).Name);
_subscriptionManager.RegisterSubscription<TEvent>();

View File

@@ -2,6 +2,6 @@ namespace FictionArchive.Service.Shared.Services.EventBus;
public interface IEventBus
{
Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IntegrationEvent;
Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent;
Task Publish(object integrationEvent, string eventType);
}

View File

@@ -0,0 +1,7 @@
using NodaTime;
namespace FictionArchive.Service.Shared.Services.EventBus;
public interface IIntegrationEvent
{
}

View File

@@ -1,12 +1,12 @@
namespace FictionArchive.Service.Shared.Services.EventBus;
public interface IIntegrationEventHandler<in TEvent> : IIntegrationEventHandler where TEvent : IntegrationEvent
public interface IIntegrationEventHandler<in TEvent> : IIntegrationEventHandler where TEvent : IIntegrationEvent
{
Task Handle(TEvent @event);
Task IIntegrationEventHandler.Handle(IntegrationEvent @event) => Handle((TEvent)@event);
Task IIntegrationEventHandler.Handle(IIntegrationEvent @event) => Handle((TEvent)@event);
}
public interface IIntegrationEventHandler
{
Task Handle(IntegrationEvent @event);
Task Handle(IIntegrationEvent @event);
}

View File

@@ -22,6 +22,8 @@ public class RabbitMQEventBus : IEventBus, IHostedService
private readonly JsonSerializerSettings _jsonSerializerSettings;
private const string ExchangeName = "fiction-archive-event-bus";
private const string CreatedAtHeader = "X-Created-At";
private const string EventIdHeader = "X-Event-Id";
public RabbitMQEventBus(IServiceScopeFactory serviceScopeFactory, RabbitMQConnectionProvider connectionProvider, IOptions<RabbitMQOptions> options, SubscriptionManager subscriptionManager, ILogger<RabbitMQEventBus> logger)
{
@@ -33,14 +35,10 @@ public class RabbitMQEventBus : IEventBus, IHostedService
_jsonSerializerSettings = new JsonSerializerSettings().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
}
public async Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IntegrationEvent
public async Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent
{
var routingKey = typeof(TEvent).Name;
// Set integration event values
integrationEvent.CreatedAt = Instant.FromDateTimeUtc(DateTime.UtcNow);
integrationEvent.EventId = Guid.NewGuid();
await Publish(integrationEvent, routingKey);
}
@@ -48,7 +46,16 @@ public class RabbitMQEventBus : IEventBus, IHostedService
{
var channel = await _connectionProvider.GetDefaultChannelAsync();
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(integrationEvent));
await channel.BasicPublishAsync(ExchangeName, eventType, true, body);
// headers
var props = new BasicProperties();
props.Headers = new Dictionary<string, object?>()
{
{ CreatedAtHeader, Instant.FromDateTimeUtc(DateTime.UtcNow).ToString() },
{ EventIdHeader, Guid.NewGuid().ToString() }
};
await channel.BasicPublishAsync(ExchangeName, eventType, true, props, body);
_logger.LogInformation("Published event {EventName}", eventType);
}
@@ -70,6 +77,8 @@ public class RabbitMQEventBus : IEventBus, IHostedService
return OnReceivedEvent(sender, @event, channel);
};
await channel.BasicConsumeAsync(_options.ClientIdentifier, false, consumer, cancellationToken: cancellationToken);
foreach (var subscription in _subscriptionManager.Subscriptions)
{
await channel.QueueBindAsync(_options.ClientIdentifier, ExchangeName, subscription.Key,
@@ -77,8 +86,6 @@ public class RabbitMQEventBus : IEventBus, IHostedService
_logger.LogInformation("Subscribed to {SubscriptionKey}", subscription.Key);
}
await channel.BasicConsumeAsync(_options.ClientIdentifier, false, consumer, cancellationToken: cancellationToken);
_logger.LogInformation("RabbitMQ EventBus started.");
}
catch (Exception e)
@@ -106,7 +113,7 @@ public class RabbitMQEventBus : IEventBus, IHostedService
}
var eventBody = Encoding.UTF8.GetString(@event.Body.Span);
var eventObject = JsonConvert.DeserializeObject(eventBody, _subscriptionManager.Subscriptions[eventName], _jsonSerializerSettings) as IntegrationEvent;
var eventObject = JsonConvert.DeserializeObject(eventBody, _subscriptionManager.Subscriptions[eventName], _jsonSerializerSettings) as IIntegrationEvent;
using var scope = _serviceScopeFactory.CreateScope();

View File

@@ -1,9 +0,0 @@
using NodaTime;
namespace FictionArchive.Service.Shared.Services.EventBus;
public abstract class IntegrationEvent
{
public Guid EventId { get; set; }
public Instant CreatedAt { get; set; }
}

View File

@@ -4,7 +4,7 @@ using FictionArchive.Service.TranslationService.Models.Enums;
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
public class TranslationRequestCompletedEvent : IntegrationEvent
public class TranslationRequestCompletedEvent : IIntegrationEvent
{
/// <summary>
/// Maps this event back to a triggering request.

View File

@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
public class TranslationRequestCreatedEvent : IntegrationEvent
public class TranslationRequestCreatedEvent : IIntegrationEvent
{
public Guid TranslationRequestId { get; set; }
public Language From { get; set; }

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": "*"
}

View File

@@ -12,6 +12,15 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.Shar
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.SchedulerService", "FictionArchive.Service.SchedulerService\FictionArchive.Service.SchedulerService.csproj", "{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.UserService", "FictionArchive.Service.UserService\FictionArchive.Service.UserService.csproj", "{EE4D4795-2F79-4614-886D-AF8DA77120AC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.AuthenticationService", "FictionArchive.Service.AuthenticationService\FictionArchive.Service.AuthenticationService.csproj", "{70C4AE82-B01E-421D-B590-C0F47E63CD0C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{35C67E32-A17F-4EAB-B141-88AFCE11FF9C}"
ProjectSection(SolutionItems) = preProject
compose.yaml = compose.yaml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -42,5 +51,13 @@ Global
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.Build.0 = Release|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.Build.0 = Release|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal