Compare commits
8 Commits
f4f04e4a42
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78135a9f6d | ||
|
|
231e29f877 | ||
|
|
17a0be20b3 | ||
|
|
2f4823ed09 | ||
|
|
1759e8a2d4 | ||
|
|
865797d3f8 | ||
|
|
cefa47a176 | ||
|
|
c4d7fd6ed5 |
@@ -23,6 +23,9 @@ jobs:
|
||||
with:
|
||||
dotnet-version: "9.0.x"
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test
|
||||
|
||||
- name: Publish server project
|
||||
run: dotnet publish ./FoodsharingSiegen.Server/FoodsharingSiegen.Server.csproj -c Release -o ./Publish/Server
|
||||
|
||||
|
||||
@@ -23,6 +23,9 @@ jobs:
|
||||
with:
|
||||
dotnet-version: "9.0.x"
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test
|
||||
|
||||
- name: Publish server project
|
||||
run: dotnet publish ./FoodsharingSiegen.Server/FoodsharingSiegen.Server.csproj -c Release -o ./Publish/Server
|
||||
|
||||
|
||||
@@ -47,7 +47,10 @@ namespace FoodsharingSiegen.Server.Data
|
||||
/// <param name="options">The options (ab)</param>
|
||||
public FsContext(DbContextOptions<FsContext> options) : base(options)
|
||||
{
|
||||
Database.Migrate();
|
||||
if (Database.IsRelational())
|
||||
{
|
||||
Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -44,7 +44,11 @@ namespace FoodsharingSiegen.Server.Data.Service
|
||||
Data1 = data1,
|
||||
Data2 = data2
|
||||
};
|
||||
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(DateTime.Now.ToString() + " " + CurrentUser?.Name + " " + AuditHelper.CreateText(audit));
|
||||
Console.WriteLine();
|
||||
|
||||
Context.Audits?.Add(audit);
|
||||
var saveR = await Context.SaveChangesAsync();
|
||||
|
||||
|
||||
@@ -105,6 +105,13 @@ namespace FoodsharingSiegen.Server.Data.Service
|
||||
var user = await Context.Users!.Include(x => x.Interactions).FirstOrDefaultAsync(x => x.Id == userId);
|
||||
if (user == null) return new(new Exception("User not found"));
|
||||
|
||||
if (user.Type == UserType.Admin)
|
||||
{
|
||||
var adminCount = await Context.Users!.CountAsync(x => x.Type == UserType.Admin && x.Id != userId);
|
||||
if (adminCount == 0)
|
||||
return new(new Exception("Der letzte Administrator kann nicht gelöscht werden."));
|
||||
}
|
||||
|
||||
// Interaktionen vom aktuellen Nutzer übernehmen
|
||||
if(CurrentUser?.Id != null)
|
||||
foreach (var userInteraction in user.Interactions)
|
||||
@@ -184,6 +191,13 @@ namespace FoodsharingSiegen.Server.Data.Service
|
||||
var entityUser = await Context.Users!.FirstOrDefaultAsync(x => x.Id == user.Id);
|
||||
if (entityUser == null) return new(new Exception("User not found"));
|
||||
|
||||
if (entityUser.Type == UserType.Admin && user.Type != UserType.Admin)
|
||||
{
|
||||
var adminCount = await Context.Users!.CountAsync(x => x.Type == UserType.Admin && x.Id != user.Id);
|
||||
if (adminCount == 0)
|
||||
return new(new Exception("Der Typ des letzten Administrators kann nicht geändert werden."));
|
||||
}
|
||||
|
||||
if (entityUser.Mail != user.Mail ||
|
||||
entityUser.Type != user.Type ||
|
||||
entityUser.Groups != user.Groups)
|
||||
|
||||
@@ -55,13 +55,13 @@
|
||||
</div>
|
||||
</CardBody>
|
||||
<CardFooter Class="d-flex justify-content-between">
|
||||
<div>
|
||||
|
||||
</div>
|
||||
<Button Color="Color.Primary" Size="Size.Small" Clicked="() => EditUser(user)"><Icon Name="IconName.Edit" /></Button>
|
||||
<Button Color="Color.Info" Size="Size.Small" Clicked="() => SetPassword(user)"><i class="fa-solid fa-key"></i></Button>
|
||||
<Button Color="Color.Secondary" Size="Size.Small" Clicked="() => SendPasswordSetupMail(user)"><Icon Name="IconName.Mail" /></Button>
|
||||
<Button Color="Color.Danger" Size="Size.Small" Clicked="() => RemoveUserAsync(user)"><Icon Name="IconName.Delete" /></Button>
|
||||
@if (!(user.Type == UserType.Admin && SortedUsers.Count(x => x.Type == UserType.Admin) <= 1))
|
||||
{
|
||||
<Button Color="Color.Danger" Size="Size.Small" Clicked="() => RemoveUserAsync(user)"><Icon Name="IconName.Delete" /></Button>
|
||||
}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
}
|
||||
@@ -105,12 +105,16 @@
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>Typ</FieldLabel>
|
||||
<Select TValue="UserType" SelectedValue="EditModel.Type" SelectedValueChanged="@(v => EditModel.Type = v)">
|
||||
<Select TValue="UserType" SelectedValue="EditModel.Type" SelectedValueChanged="@(v => EditModel.Type = v)" Disabled="@IsLastAdmin">
|
||||
@foreach (var enumValue in Enum.GetValues<UserType>())
|
||||
{
|
||||
<SelectItem TValue="UserType" Value="enumValue">@enumValue</SelectItem>
|
||||
}
|
||||
</Select>
|
||||
@if (IsLastAdmin)
|
||||
{
|
||||
<small class="text-danger mt-1 d-block">Das ist der letzte Administrator-Account. Der Typ kann nicht geändert werden.</small>
|
||||
}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>Gruppen</FieldLabel>
|
||||
|
||||
@@ -57,6 +57,11 @@ namespace FoodsharingSiegen.Server.Pages
|
||||
/// </summary>
|
||||
private bool IsEditing { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the current editing user is the last admin
|
||||
/// </summary>
|
||||
private bool IsLastAdmin => IsEditing && EditModel?.Type == UserType.Admin && UserList?.Count(x => x.Type == UserType.Admin) <= 1;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the user groups (ab)
|
||||
/// </summary>
|
||||
@@ -184,12 +189,6 @@ namespace FoodsharingSiegen.Server.Pages
|
||||
/// <returns>A task that represents the asynchronous remove operation.</returns>
|
||||
private async Task RemoveUserAsync(User user)
|
||||
{
|
||||
if (user.IsAdmin())
|
||||
{
|
||||
await Notification.Error("Admins können nicht gelöscht werden!");
|
||||
return;
|
||||
}
|
||||
|
||||
await ConfirmDialog.ShowAsync(ModalService, "Bestätigen", $"User {user.Mail} löschen?", async () =>
|
||||
{
|
||||
var removeR = await UserService.RemoveAsync(user.Id);
|
||||
|
||||
@@ -14,18 +14,18 @@
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
|
||||
<meta name="apple-mobile-web-app-title" content="Foodsharing Einarbeitungen" />
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
|
||||
<link href="css/site.css" rel="stylesheet"/>
|
||||
<link href="FoodsharingSiegen.Server.styles.css" rel="stylesheet"/>
|
||||
<link rel="stylesheet" href="~/css/bootstrap/bootstrap.min.css" asp-append-version="true" />
|
||||
<link href="~/css/site.css" rel="stylesheet" asp-append-version="true" />
|
||||
<link href="~/FoodsharingSiegen.Server.styles.css" rel="stylesheet" asp-append-version="true" />
|
||||
|
||||
<!-- Material CSS -->
|
||||
<link href="css/material.min.css" rel="stylesheet">
|
||||
<link href="~/css/material.min.css" rel="stylesheet" asp-append-version="true" />
|
||||
|
||||
<!-- Add Material font (Roboto) and Material icon as needed -->
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i|Roboto+Mono:300,400,700|Roboto+Slab:300,400,700" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
||||
|
||||
<link href="css/all.min.css" rel="stylesheet" />
|
||||
<link href="~/css/all.min.css" rel="stylesheet" asp-append-version="true" />
|
||||
<link href="_content/Blazorise/blazorise.css?v=1.7.5.0" rel="stylesheet" />
|
||||
<link href="_content/Blazorise.Material/blazorise.material.css?v=1.7.5.0" rel="stylesheet" />
|
||||
<link href="_content/Blazorise.Icons.Material/blazorise.icons.material.css?v=1.7.5.0" rel="stylesheet" />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using FoodsharingSiegen.Contracts.Model;
|
||||
using MailKit.Net.Smtp;
|
||||
@@ -15,15 +16,17 @@ namespace FoodsharingSiegen.Server.Service
|
||||
{
|
||||
private readonly MailSettings _mailSettings;
|
||||
private readonly TermSettings _termSettings;
|
||||
private readonly Func<ISmtpClient> _smtpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MailService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="appSettings">The configured application settings injected by DI, containing the <see cref="MailSettings"/>.</param>
|
||||
public MailService(IOptions<AppSettings> appSettings)
|
||||
public MailService(IOptions<AppSettings> appSettings, Func<ISmtpClient>? smtpClientFactory = null)
|
||||
{
|
||||
_mailSettings = appSettings.Value.Mail;
|
||||
_termSettings = appSettings.Value.Terms;
|
||||
_smtpClientFactory = smtpClientFactory ?? (() => new SmtpClient());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -40,7 +43,7 @@ namespace FoodsharingSiegen.Server.Service
|
||||
};
|
||||
email.Body = textPart;
|
||||
|
||||
using var smtp = new SmtpClient();
|
||||
using var smtp = _smtpClientFactory();
|
||||
var secureOptions = _mailSettings.UseSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto;
|
||||
|
||||
await smtp.ConnectAsync(_mailSettings.Host, _mailSettings.Port, secureOptions);
|
||||
|
||||
27
FoodsharingSiegen.Tests/FoodsharingSiegen.Tests.csproj
Normal file
27
FoodsharingSiegen.Tests/FoodsharingSiegen.Tests.csproj
Normal file
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="9.0.2" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\FoodsharingSiegen.Server\FoodsharingSiegen.Server.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
87
FoodsharingSiegen.Tests/LocalStorageServiceTests.cs
Normal file
87
FoodsharingSiegen.Tests/LocalStorageServiceTests.cs
Normal file
@@ -0,0 +1,87 @@
|
||||
using System.Text.Json;
|
||||
using FoodsharingSiegen.Server.Service;
|
||||
using Microsoft.JSInterop;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace FoodsharingSiegen.Tests
|
||||
{
|
||||
public class LocalStorageServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task GetItem_ReturnsDeserializedObject_WhenItemExists()
|
||||
{
|
||||
// Arrange
|
||||
var mockJsRuntime = new Mock<IJSRuntime>();
|
||||
var service = new LocalStorageService(mockJsRuntime.Object);
|
||||
var expectedObject = new { Name = "Test" };
|
||||
var jsonString = JsonSerializer.Serialize(expectedObject);
|
||||
|
||||
mockJsRuntime.Setup(x => x.InvokeAsync<string>("localStorage.getItem", It.IsAny<object[]>()))
|
||||
.ReturnsAsync(jsonString);
|
||||
|
||||
// Act
|
||||
var result = await service.GetItem<dynamic>("testKey");
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
mockJsRuntime.Verify(x => x.InvokeAsync<string>("localStorage.getItem", It.Is<object[]>(args => args.Length == 1 && args[0].ToString() == "testKey")), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetItem_ReturnsDefault_WhenItemDoesNotExist()
|
||||
{
|
||||
// Arrange
|
||||
var mockJsRuntime = new Mock<IJSRuntime>();
|
||||
var service = new LocalStorageService(mockJsRuntime.Object);
|
||||
|
||||
mockJsRuntime.Setup(x => x.InvokeAsync<string>("localStorage.getItem", It.IsAny<object[]>()))
|
||||
.ReturnsAsync((string?)null);
|
||||
|
||||
// Act
|
||||
var result = await service.GetItem<string>("testKey");
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetItem_CallsSetItemInLocalStorage()
|
||||
{
|
||||
// Arrange
|
||||
var mockJsRuntime = new Mock<IJSRuntime>();
|
||||
var service = new LocalStorageService(mockJsRuntime.Object);
|
||||
var objectToSave = new { Name = "Test" };
|
||||
var expectedJson = JsonSerializer.Serialize(objectToSave);
|
||||
|
||||
// Act
|
||||
await service.SetItem("testKey", objectToSave);
|
||||
|
||||
// Assert
|
||||
// Note: InvokeVoidAsync is an extension method that calls InvokeAsync<IJSVoidResult> under the hood in Blazor.
|
||||
mockJsRuntime.Verify(
|
||||
x => x.InvokeAsync<It.IsAnyType>(
|
||||
"localStorage.setItem",
|
||||
It.Is<object[]>(args => args.Length == 2 && args[0].ToString() == "testKey" && args[1].ToString() == expectedJson)),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveItem_CallsRemoveItemInLocalStorage()
|
||||
{
|
||||
// Arrange
|
||||
var mockJsRuntime = new Mock<IJSRuntime>();
|
||||
var service = new LocalStorageService(mockJsRuntime.Object);
|
||||
|
||||
// Act
|
||||
await service.RemoveItem("testKey");
|
||||
|
||||
// Assert
|
||||
mockJsRuntime.Verify(
|
||||
x => x.InvokeAsync<It.IsAnyType>(
|
||||
"localStorage.removeItem",
|
||||
It.Is<object[]>(args => args.Length == 1 && args[0].ToString() == "testKey")),
|
||||
Times.Once);
|
||||
}
|
||||
}
|
||||
}
|
||||
110
FoodsharingSiegen.Tests/MailServiceTests.cs
Normal file
110
FoodsharingSiegen.Tests/MailServiceTests.cs
Normal file
@@ -0,0 +1,110 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FoodsharingSiegen.Contracts.Model;
|
||||
using FoodsharingSiegen.Server.Service;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MimeKit;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace FoodsharingSiegen.Tests
|
||||
{
|
||||
public class MailServiceTests
|
||||
{
|
||||
private readonly Mock<IOptions<AppSettings>> _mockOptions;
|
||||
private readonly AppSettings _appSettings;
|
||||
private readonly Mock<ISmtpClient> _mockSmtpClient;
|
||||
|
||||
public MailServiceTests()
|
||||
{
|
||||
_appSettings = new AppSettings
|
||||
{
|
||||
Mail = new MailSettings
|
||||
{
|
||||
Host = "smtp.test.com",
|
||||
Port = 587,
|
||||
UseSsl = false,
|
||||
Username = "user@test.com",
|
||||
Password = "password123",
|
||||
FromAddress = "no-reply@test.com"
|
||||
},
|
||||
Terms = new TermSettings
|
||||
{
|
||||
Title = "Foodsharing Test"
|
||||
}
|
||||
};
|
||||
|
||||
_mockOptions = new Mock<IOptions<AppSettings>>();
|
||||
_mockOptions.Setup(o => o.Value).Returns(_appSettings);
|
||||
|
||||
_mockSmtpClient = new Mock<ISmtpClient>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendEmailAsync_ConnectsAuthenticatesAndSendsEmail()
|
||||
{
|
||||
// Arrange
|
||||
var service = new MailService(_mockOptions.Object, () => _mockSmtpClient.Object);
|
||||
var toEmail = "recipient@test.com";
|
||||
var subject = "Test Subject";
|
||||
var body = "<p>Test Body</p>";
|
||||
|
||||
// Act
|
||||
await service.SendEmailAsync(toEmail, subject, body);
|
||||
|
||||
// Assert
|
||||
_mockSmtpClient.Verify(
|
||||
x => x.ConnectAsync(
|
||||
"smtp.test.com",
|
||||
587,
|
||||
SecureSocketOptions.Auto,
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
|
||||
_mockSmtpClient.Verify(
|
||||
x => x.AuthenticateAsync(
|
||||
"user@test.com",
|
||||
"password123",
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
|
||||
// Verify a MimeMessage is passed to SendAsync with correct attributes
|
||||
_mockSmtpClient.Verify(
|
||||
x => x.SendAsync(
|
||||
It.Is<MimeMessage>(m => m.Subject == subject),
|
||||
It.IsAny<CancellationToken>(),
|
||||
It.IsAny<MailKit.ITransferProgress>()),
|
||||
Times.Once);
|
||||
|
||||
_mockSmtpClient.Verify(
|
||||
x => x.DisconnectAsync(
|
||||
true,
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
|
||||
_mockSmtpClient.Verify(
|
||||
x => x.Dispose(),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendEmailAsync_SkipsAuthentication_WhenUsernameIsBlank()
|
||||
{
|
||||
// Arrange
|
||||
_appSettings.Mail.Username = "";
|
||||
_appSettings.Mail.Password = "";
|
||||
var service = new MailService(_mockOptions.Object, () => _mockSmtpClient.Object);
|
||||
|
||||
// Act
|
||||
await service.SendEmailAsync("recipient@test.com", "Subject", "Body");
|
||||
|
||||
// Assert
|
||||
_mockSmtpClient.Verify(
|
||||
x => x.AuthenticateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
}
|
||||
}
|
||||
236
FoodsharingSiegen.Tests/UserServiceTests.cs
Normal file
236
FoodsharingSiegen.Tests/UserServiceTests.cs
Normal file
@@ -0,0 +1,236 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using FoodsharingSiegen.Contracts.Entity;
|
||||
using FoodsharingSiegen.Contracts.Enums;
|
||||
using FoodsharingSiegen.Contracts.Model;
|
||||
using FoodsharingSiegen.Server.Auth;
|
||||
using FoodsharingSiegen.Server.Data;
|
||||
using FoodsharingSiegen.Server.Data.Service;
|
||||
using FoodsharingSiegen.Server.Service;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.JSInterop;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace FoodsharingSiegen.Tests
|
||||
{
|
||||
public class UserServiceTests
|
||||
{
|
||||
private FsContext CreateInMemoryContext(string dbName)
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<FsContext>()
|
||||
.UseInMemoryDatabase(databaseName: dbName)
|
||||
.Options;
|
||||
return new FsContext(options);
|
||||
}
|
||||
|
||||
private AuthService CreateAuthService(FsContext context, User? currentUser = null)
|
||||
{
|
||||
var mockJsRuntime = new Mock<IJSRuntime>();
|
||||
var localStorageService = new LocalStorageService(mockJsRuntime.Object);
|
||||
var authStateProvider = new Mock<AuthenticationStateProvider>();
|
||||
var mailService = new Mock<IMailService>();
|
||||
var appSettings = new Mock<IOptions<AppSettings>>();
|
||||
appSettings.Setup(x => x.Value).Returns(new AppSettings());
|
||||
|
||||
var authService = new AuthService(context, localStorageService, authStateProvider.Object, mailService.Object, appSettings.Object);
|
||||
|
||||
if (currentUser != null)
|
||||
{
|
||||
var field = typeof(AuthService).GetField("_user", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
field?.SetValue(authService, currentUser);
|
||||
}
|
||||
|
||||
return authService;
|
||||
}
|
||||
|
||||
private AuditService CreateAuditService(FsContext context, AuthService authService)
|
||||
{
|
||||
return new AuditService(context, authService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddUserAsync_Fails_WhenEmailAlreadyExists()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
context.Users!.Add(new User { Mail = "existing@example.com", Name = "Existing", Password = "123" });
|
||||
context.SaveChanges();
|
||||
|
||||
var result = await userService.AddUserAsync(new User { Mail = "EXISTING@example.com", Name = "New" });
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("Diese E-Mail Adresse wird bereits verwendet", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddUserAsync_Succeeds_AndSetsPasswordEmpty_IfNull()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var newUser = new User { Mail = "new@example.com", Name = "New", };
|
||||
|
||||
var result = await userService.AddUserAsync(newUser);
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal(string.Empty, result.Data?.Password);
|
||||
Assert.NotNull(result.Data?.Created);
|
||||
Assert.Single(context.Users!);
|
||||
Assert.Single(context.Audits!);
|
||||
Assert.Equal(AuditType.CreateUser, context.Audits!.First().Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveAsync_TransferInteractions_AndRemovesUser()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
|
||||
var currentUser = new User { Id = Guid.NewGuid(), Mail = "current@example.com" };
|
||||
var authService = CreateAuthService(context, currentUser);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var userToRemove = new User { Id = Guid.NewGuid(), Mail = "remove@example.com", Type = UserType.User };
|
||||
context.Users!.Add(currentUser);
|
||||
context.Users!.Add(userToRemove);
|
||||
|
||||
context.Interactions!.Add(new Interaction { Id = Guid.NewGuid(), UserID = userToRemove.Id });
|
||||
context.Audits!.Add(new Audit { Id = Guid.NewGuid(), UserID = userToRemove.Id, Type = AuditType.None });
|
||||
context.SaveChanges();
|
||||
|
||||
var result = await userService.RemoveAsync(userToRemove.Id);
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Empty(context.Users!.Where(u => u.Id == userToRemove.Id));
|
||||
var interaction = context.Interactions!.First();
|
||||
Assert.Equal(currentUser.Id, interaction.UserID);
|
||||
Assert.Single(context.Audits!.Where(a => a.Type == AuditType.RemoveUser)); // created audit for remove
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveAsync_Fails_WhenLastAdmin()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var admin = new User { Id = Guid.NewGuid(), Mail = "admin@example.com", Type = UserType.Admin };
|
||||
context.Users!.Add(admin);
|
||||
context.SaveChanges();
|
||||
|
||||
var result = await userService.RemoveAsync(admin.Id);
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("Der letzte Administrator kann nicht gelöscht werden.", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetPassword_Fails_IfUserNotFound()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var result = await userService.SetPassword(new User { Id = Guid.NewGuid(), Password = "P" });
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("User not found", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetPassword_Succeeds()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var user = new User { Id = Guid.NewGuid(), Mail = "test@example.com", Password = "Old" };
|
||||
context.Users!.Add(user);
|
||||
context.SaveChanges();
|
||||
|
||||
var result = await userService.SetPassword(new User { Id = user.Id, Password = "New" });
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal("New", context.Users!.First().Password);
|
||||
Assert.Equal(AuditType.SetUserPassword, context.Audits!.First().Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_Fails_IfNoChanges()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var user = new User { Id = Guid.NewGuid(), Mail = "a@a.com", Type = UserType.User };
|
||||
context.Users!.Add(user);
|
||||
context.SaveChanges();
|
||||
|
||||
var result = await userService.Update(new User { Id = user.Id, Mail = "a@a.com", Type = UserType.User });
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("Nichts zum Speichern gefunden", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_ForcesLogoutOnChange()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var user = new User { Id = Guid.NewGuid(), Mail = "a@a.com", Type = UserType.User };
|
||||
context.Users!.Add(user);
|
||||
context.SaveChanges();
|
||||
|
||||
var result = await userService.Update(new User { Id = user.Id, Mail = "b@b.com", Type = UserType.User });
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.True(context.Users!.First().ForceLogout);
|
||||
Assert.Single(context.Audits!.Where(a => a.Type == AuditType.UpdateUser));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_Fails_WhenDemotingLastAdmin()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
using var context = CreateInMemoryContext(dbName);
|
||||
var authService = CreateAuthService(context);
|
||||
var auditService = CreateAuditService(context, authService);
|
||||
var userService = new UserService(context, authService, auditService);
|
||||
|
||||
var admin = new User { Id = Guid.NewGuid(), Mail = "a@a.com", Type = UserType.Admin };
|
||||
context.Users!.Add(admin);
|
||||
context.SaveChanges();
|
||||
|
||||
var result = await userService.Update(new User { Id = admin.Id, Mail = "a@a.com", Type = UserType.User });
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal("Der Typ des letzten Administrators kann nicht geändert werden.", result.ErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,23 +6,68 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FoodsharingSiegen.Contracts
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FoodsharingSiegen.Shared", "FoodsharingSiegen.Shared\FoodsharingSiegen.Shared.csproj", "{625167D9-A375-40AF-82DE-87484519F6D9}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FoodsharingSiegen.Tests", "FoodsharingSiegen.Tests\FoodsharingSiegen.Tests.csproj", "{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Release|x64.Build.0 = Release|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{63D6CC91-095D-44C3-8752-660DDF9C710C}.Release|x86.Build.0 = Release|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|x64.Build.0 = Release|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|x86.Build.0 = Release|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Release|x64.Build.0 = Release|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{A3BBF859-E3BB-420A-895F-B1BCF4B38B74}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
Reference in New Issue
Block a user