fc99c91bd8
Introduce authentication API: add AuthController with login, logout and me endpoints using SignInManager/UserManager; add LoginRequest and CurrentUserResponse DTOs. Login enforces active users, updates UpdatedAt on success, and returns localized messages. Also change default seed admin password from "Hoard" to "HoardPassword".
53 lines
1.8 KiB
C#
53 lines
1.8 KiB
C#
using API.Models;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace API.Services
|
|
{
|
|
public class IdentitySeedService(
|
|
UserManager<AppUser> userManager,
|
|
IConfiguration configuration,
|
|
ILogger<IdentitySeedService> logger)
|
|
{
|
|
public async Task SeedAsync()
|
|
{
|
|
var hasAdmin = await userManager.Users.AnyAsync(x => x.IsAdmin);
|
|
|
|
if (hasAdmin)
|
|
{
|
|
logger.LogDebug("Admin-Seed übersprungen: Es existiert bereits ein Admin-Account.");
|
|
return;
|
|
}
|
|
|
|
var adminUserName = configuration["SeedAdmin:UserName"] ?? "admin";
|
|
var adminPassword = configuration["SeedAdmin:Password"] ?? "HoardPassword";
|
|
var adminEmail = configuration["SeedAdmin:Email"];
|
|
|
|
var admin = new AppUser
|
|
{
|
|
UserName = adminUserName,
|
|
Email = string.IsNullOrWhiteSpace(adminEmail) ? null : adminEmail,
|
|
IsAdmin = true,
|
|
IsActive = true,
|
|
MustChangePassword = true,
|
|
CreatedAt = DateTimeOffset.UtcNow,
|
|
UpdatedAt = DateTimeOffset.UtcNow
|
|
};
|
|
|
|
var result = await userManager.CreateAsync(admin, adminPassword);
|
|
|
|
if (!result.Succeeded)
|
|
{
|
|
var errors = string.Join(", ", result.Errors.Select(x => x.Description));
|
|
logger.LogError("Admin-Seed fehlgeschlagen: {Errors}", errors);
|
|
throw new InvalidOperationException($"Admin-Seed fehlgeschlagen: {errors}");
|
|
}
|
|
|
|
logger.LogInformation(
|
|
"Admin-Account wurde geseedet (UserName: {UserName}, Email: {Email}).",
|
|
admin.UserName,
|
|
admin.Email ?? "(keine)");
|
|
}
|
|
}
|
|
}
|