commit 45f1655edcd16d4b95457d9e14fb50c056d547bd
Author: Tomáš Orlovský <orlovtom@fit.cvut.cz>
Date:   Thu May 20 15:50:21 2021 +0200

    Changed the code so it is easier to test and rewrited some tests

diff --git a/src/Core/Application/Leuze.Core.Application/Authentication/AuthenticatedUserProvider.cs b/src/Core/Application/Leuze.Core.Application/Authentication/AuthenticatedUserProvider.cs
new file mode 100644
index 0000000..0790252
--- /dev/null
+++ b/src/Core/Application/Leuze.Core.Application/Authentication/AuthenticatedUserProvider.cs
@@ -0,0 +1,42 @@
+﻿using Microsoft.AspNetCore.Components.Authorization;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Security.Claims;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Leuze.Core.Application.Authentication
+{
+    public class AuthenticatedUserProvider
+    {
+        private readonly AuthenticationStateProvider _authenticationStateProvider;
+
+        public AuthenticatedUserProvider(AuthenticationStateProvider authenticationStateProvider)
+            => (_authenticationStateProvider) = (authenticationStateProvider);
+
+        public Guid? UserId
+        {
+            get
+            {
+                var state = _authenticationStateProvider.GetAuthenticationStateAsync().Result;
+                var isOk = Guid.TryParse(state.User!.FindFirst(ClaimTypes.NameIdentifier)!.Value, out var id);
+                return isOk ? id : null;
+            }
+            private set { }
+        }
+
+        public Guid RequiredUserId
+        {
+            get
+            {
+                var state = _authenticationStateProvider.GetAuthenticationStateAsync().Result;
+                var isOk = Guid.TryParse(state.User!.FindFirst(ClaimTypes.NameIdentifier)!.Value, out var id);
+                if (!isOk) throw new UnauthorizedAccessException();
+                return id;
+            }
+            private set { }
+        }
+
+    }
+}
diff --git a/src/Core/Application/Leuze.Core.Application/CQRS/Users/Queries/GetUsersList.cs b/src/Core/Application/Leuze.Core.Application/CQRS/Users/Queries/GetUsersList.cs
index 6e7a922..a55c1ef 100644
--- a/src/Core/Application/Leuze.Core.Application/CQRS/Users/Queries/GetUsersList.cs
+++ b/src/Core/Application/Leuze.Core.Application/CQRS/Users/Queries/GetUsersList.cs
@@ -7,6 +7,7 @@ using System.Linq;
 using System.Security.Claims;
 using System.Threading;
 using System.Threading.Tasks;
+using Leuze.Core.Application.Authentication;
 
 namespace Leuze.Core.Application.CQRS.Users.Queries
 {
@@ -31,14 +32,14 @@ namespace Leuze.Core.Application.CQRS.Users.Queries
         public class Handler : IBaseRequestHandler<Query, Response>
         {
             private readonly IDomainUserRepository _domainUserRepository;
-            private readonly AuthenticationStateProvider _authenticationStateProvider;
+            private readonly AuthenticatedUserProvider _authenticationStateProvider;
 
             /// <summary>
             /// 
             /// </summary>
             /// <param name="domainUserRepository"></param>
             /// <param name="authenticationStateProvider"></param>
-            public Handler(IDomainUserRepository domainUserRepository, AuthenticationStateProvider authenticationStateProvider)
+            public Handler(IDomainUserRepository domainUserRepository, AuthenticatedUserProvider authenticationStateProvider)
                 => (_domainUserRepository, _authenticationStateProvider) = (domainUserRepository, authenticationStateProvider);
 
             /// <summary>
@@ -50,8 +51,8 @@ namespace Leuze.Core.Application.CQRS.Users.Queries
             public async Task<RequestResponse<Response>> Handle(Query request, CancellationToken cancellationToken)
             {
                 var list = await _domainUserRepository.GetListAsync();
-                var state = await _authenticationStateProvider.GetAuthenticationStateAsync();
-                var id = Guid.Parse(state.User!.FindFirst(ClaimTypes.NameIdentifier)!.Value);
+                //var state = await _authenticationStateProvider.GetAuthenticationStateAsync();
+                var id = _authenticationStateProvider.RequiredUserId;
                 if (request.ExcludeMyself) list = list.Where(o => o.Id != id).ToList();
                 return RequestResponse<Response>.CreateSuccessResponse(new(list));
             }
diff --git a/src/Core/Application/Leuze.Core.Application/Configuration/Extensions/CustomAuthenticationExtensions.cs b/src/Core/Application/Leuze.Core.Application/Configuration/Extensions/CustomAuthenticationExtensions.cs
index 4158841..7d1eabf 100644
--- a/src/Core/Application/Leuze.Core.Application/Configuration/Extensions/CustomAuthenticationExtensions.cs
+++ b/src/Core/Application/Leuze.Core.Application/Configuration/Extensions/CustomAuthenticationExtensions.cs
@@ -11,6 +11,7 @@ using System;
 using System.Linq;
 using System.Security.Claims;
 using System.Threading.Tasks;
+using Leuze.Core.Application.Authentication;
 
 namespace Leuze.Core.Application.Configuration.Extensions
 {
@@ -26,6 +27,7 @@ namespace Leuze.Core.Application.Configuration.Extensions
         /// <param name="configuration"></param>
         public static void AddAzureAdAuthentication(this IServiceCollection services, IConfiguration configuration)
         {
+            services.AddTransient(typeof(AuthenticatedUserProvider));
             services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                 .AddMicrosoftIdentityWebApp(options =>
                 {
diff --git a/src/Core/Infrastructure/Leuze.Core.Infrastructure.Persistence/Seeds/ApplicationSeed.cs b/src/Core/Infrastructure/Leuze.Core.Infrastructure.Persistence/Seeds/ApplicationSeed.cs
index 25fb9cd..9b08326 100644
--- a/src/Core/Infrastructure/Leuze.Core.Infrastructure.Persistence/Seeds/ApplicationSeed.cs
+++ b/src/Core/Infrastructure/Leuze.Core.Infrastructure.Persistence/Seeds/ApplicationSeed.cs
@@ -6,6 +6,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
+using Microsoft.EntityFrameworkCore;
 
 namespace Leuze.Core.Infrastructure.Persistence.Seeds
 {
@@ -21,7 +22,7 @@ namespace Leuze.Core.Infrastructure.Persistence.Seeds
         /// <param name="context"></param>
         /// <param name="userManager"></param>
         /// <param name="roleManager"></param>
-        public static void Run(LeuzeDbContext context, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
+        public static void Run(DbContext context, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
         {
             var permissions = context.Set<ApplicationPermission>().ToList();
             var role1 = CreateRole("Admin", false, roleManager, permissions);
@@ -32,7 +33,7 @@ namespace Leuze.Core.Infrastructure.Persistence.Seeds
             CreateUser("Testovací MA", "ma@test.cz", role3, context, userManager);
         }
 
-        private static void CreateUser(string name, string email, ApplicationRole role, LeuzeDbContext context, UserManager<ApplicationUser> userManager)
+        private static void CreateUser(string name, string email, ApplicationRole role, DbContext context, UserManager<ApplicationUser> userManager)
         {
             ApplicationUser user = new(email, email, false);
             userManager.CreateAsync(user).Wait();
diff --git a/tests/Core/Leuze.Tests.Core/Leuze.Tests.Core.csproj b/tests/Core/Leuze.Tests.Core/Leuze.Tests.Core.csproj
index ee31ca7..b0a89a3 100644
--- a/tests/Core/Leuze.Tests.Core/Leuze.Tests.Core.csproj
+++ b/tests/Core/Leuze.Tests.Core/Leuze.Tests.Core.csproj
@@ -9,6 +9,7 @@
   <ItemGroup>
     <PackageReference Include="FluentAssertions" Version="5.10.3" />
     <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
+    <PackageReference Include="Moq" Version="4.16.1" />
     <PackageReference Include="xunit" Version="2.4.1" />
     <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
       <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
diff --git a/tests/Core/Leuze.Tests.Core/LoginTests.cs b/tests/Core/Leuze.Tests.Core/LoginTests.cs
index 2111824..cc0b16c 100644
--- a/tests/Core/Leuze.Tests.Core/LoginTests.cs
+++ b/tests/Core/Leuze.Tests.Core/LoginTests.cs
@@ -5,7 +5,10 @@ using Leuze.Core.Application.CQRS.Auth.Commands;
 using Leuze.Core.Application.Identity;
 using Leuze.Tests.Configuration;
 using MediatR;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Identity;
 using Microsoft.Extensions.DependencyInjection;
+using Moq;
 using Xunit;
 
 namespace Leuze.Tests.Core
@@ -28,22 +31,44 @@ namespace Leuze.Tests.Core
             //DatabaseFixture.UserManager.AddPasswordAsync(user1, "kappa123").Wait();
         }
 
-        [Fact]
-        public async Task SimpleLoginTest()
-        {
-            await _semaphore.WaitAsync();
+        //[Fact]
+        //public async Task SimpleLoginTest()
+        //{
+        //    await _semaphore.WaitAsync();
 
-            IMediator mediator = DatabaseFixture.Services.GetRequiredService<IMediator>();
+        //    IMediator mediator = DatabaseFixture.Services.GetRequiredService<IMediator>();
 
-            var response = await mediator.Send(new VerifyLocalUser.Command(USER1.mail, USER1.pass));
-            // response.IsSuccess.Should().BeTrue();
+        //    var response = await mediator.Send(new VerifyLocalUser.Command(USER1.mail, USER1.pass));
+        //    // response.IsSuccess.Should().BeTrue();
 
             
-            //HttpContext context = DatabaseFixture.Services.GetRequiredService<IHttpContextAccessor>().HttpContext;
+        //    //HttpContext context = DatabaseFixture.Services.GetRequiredService<IHttpContextAccessor>().HttpContext;
             
-            //Assert.True(context.User.Identity.IsAuthenticated);
-            //context.User.Identity.IsAuthenticated.Should().Be(true);
+        //    //Assert.True(context.User.Identity.IsAuthenticated);
+        //    //context.User.Identity.IsAuthenticated.Should().Be(true);
             
+        //    _semaphore.Release();
+        //}
+
+        [Fact]
+        public async Task SimpleLoginTest()
+        {
+            var signInManagerMock = new Mock<SignInManager<ApplicationUser>>(
+                DatabaseFixture.UserManager,
+                Mock.Of<IHttpContextAccessor>(),
+                Mock.Of<IUserClaimsPrincipalFactory<ApplicationUser>>(),
+                null, null, null, null);
+            var user = await DatabaseFixture.UserManager.FindByEmailAsync("user@test.com");
+            signInManagerMock.Setup(e => e.SignInAsync(It.IsAny<ApplicationUser>(), It.IsAny<bool>(), null)).Returns(Task.CompletedTask);
+            signInManagerMock.Setup(e => e.CheckPasswordSignInAsync(user, "Kappa123.", It.IsAny<bool>())).Returns(Task.FromResult(SignInResult.Success));
+            signInManagerMock.Setup(e => e.CheckPasswordSignInAsync(user, It.IsNotIn("Kappa123."), It.IsAny<bool>())).Returns(Task.FromResult(SignInResult.Failed));
+            signInManagerMock.Setup(e => e.CheckPasswordSignInAsync(It.IsNotIn(user), It.IsAny<string>(), It.IsAny<bool>())).Returns(Task.FromResult(SignInResult.Failed));
+
+            await _semaphore.WaitAsync();
+            var handler = new VerifyLocalUser.Handler(signInManagerMock.Object, DatabaseFixture.UserManager);
+            var result = await handler.Handle(new VerifyLocalUser.Command("user@test.com", "Kappa123."), default);
+            result.IsSuccess.Should().BeTrue();
+
             _semaphore.Release();
         }
 
diff --git a/tests/Core/Leuze.Tests.Core/RoleTests.cs b/tests/Core/Leuze.Tests.Core/RoleTests.cs
index b457ecf..a405563 100644
--- a/tests/Core/Leuze.Tests.Core/RoleTests.cs
+++ b/tests/Core/Leuze.Tests.Core/RoleTests.cs
@@ -1,10 +1,17 @@
 ﻿using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Security.Claims;
 using System.Text;
+using FluentAssertions;
 using System.Threading.Tasks;
+using Leuze.Core.Application.Authentication;
+using Leuze.Core.Application.CQRS.Users.Queries;
+using Leuze.Core.Infrastructure.Persistence.Seeds;
 using Leuze.Tests.Configuration;
+using Microsoft.AspNetCore.Components.Authorization;
 using Microsoft.Extensions.DependencyInjection;
+using Moq;
 using Xunit;
 
 namespace Leuze.Tests.Core
@@ -17,12 +24,23 @@ namespace Leuze.Tests.Core
             var services = new ServiceCollection();
 
             Initialize(services);
+
+            ApplicationSeed.Run(DatabaseFixture.Storage, DatabaseFixture.UserManager, DatabaseFixture.RoleManager);
         }
 
         [Fact]
         public async Task AdminRoleTest()
         {
-            //TODO: implementation
+            await _semaphore.WaitAsync();
+            var user = await DatabaseFixture.UserManager.FindByEmailAsync("admin@test.cz");
+            (user != null).Should().BeTrue();
+
+            var AuthenticationStateProviderMock = new Mock<AuthenticatedUserProvider>();
+            AuthenticationStateProviderMock.Setup(e => e.RequiredUserId).Returns(user.Id);
+
+            var handler = new GetUsersList.Handler(DatabaseFixture.UserManager)
+
+            _semaphore.Release();
         }
 
         [Fact]
