Files
Umbraco-CMS/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Security/MemberSignInManagerTests.cs

124 lines
5.4 KiB
C#
Raw Normal View History

using System;
2021-04-12 18:02:43 +10:00
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
using Umbraco.Cms.Core.Configuration.Models;
Merge branch 'netcore/dev' into netcore/members-userstore # Conflicts: # src/Umbraco.Core/Models/Membership/IMembershipUser.cs # src/Umbraco.Core/Models/Membership/IUser.cs # src/Umbraco.Core/Services/IMembershipRoleService.cs # src/Umbraco.Infrastructure/Compose/AuditEventsComponent.cs # src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.MappingProfiles.cs # src/Umbraco.Infrastructure/DependencyInjection/UmbracoBuilder.Services.cs # src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs # src/Umbraco.Infrastructure/Security/BackOfficeIdentityUser.cs # src/Umbraco.Infrastructure/Security/BackOfficeUserStore.cs # src/Umbraco.Infrastructure/Security/IBackOfficeUserPasswordChecker.cs # src/Umbraco.Infrastructure/Security/IUmbracoUserManager.cs # src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs # src/Umbraco.Infrastructure/Security/SignOutAuditEventArgs.cs # src/Umbraco.Infrastructure/Security/UmbracoUserManager.cs # src/Umbraco.Infrastructure/Services/Implement/MemberService.cs # src/Umbraco.Tests.Integration/TestServerTest/TestAuthHandler.cs # src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/UmbracoBackOfficeServiceCollectionExtensionsTests.cs # src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/BackOffice/BackOfficeLookupNormalizerTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Security/NoOpLookupNormalizerTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Controllers/UsersControllerTests.cs # src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs # src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs # src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs # src/Umbraco.Web.BackOffice/Controllers/MemberController.cs # src/Umbraco.Web.BackOffice/Controllers/UsersController.cs # src/Umbraco.Web.BackOffice/DependencyInjection/ServiceCollectionExtensions.cs # src/Umbraco.Web.BackOffice/Filters/CheckIfUserTicketDataIsStaleAttribute.cs # src/Umbraco.Web.BackOffice/Mapping/MemberMapDefinition.cs # src/Umbraco.Web.BackOffice/Security/BackOfficePasswordHasher.cs # src/Umbraco.Web.BackOffice/Security/BackOfficeSecurityStampValidator.cs # src/Umbraco.Web.BackOffice/Security/BackOfficeSessionIdValidator.cs # src/Umbraco.Web.BackOffice/Security/BackOfficeSignInManager.cs # src/Umbraco.Web.BackOffice/Security/BackOfficeUserManagerAuditer.cs # src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeIdentityOptions.cs # src/Umbraco.Web.BackOffice/Security/ExternalSignInAutoLinkOptions.cs # src/Umbraco.Web.BackOffice/Security/IBackOfficeSignInManager.cs # src/Umbraco.Web.BackOffice/Security/PasswordChanger.cs # src/Umbraco.Web.Common/DependencyInjection/ServiceCollectionExtensions.cs # src/Umbraco.Web.Common/Middleware/BootFailedMiddleware.cs # src/Umbraco.Web.Common/Security/BackOfficeUserManager.cs # src/Umbraco.Web/Security/MembershipHelper.cs # src/Umbraco.Web/Security/MembershipProviderBase.cs # src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs # src/Umbraco.Web/Security/Providers/MembersRoleProvider.cs # src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs
2021-02-22 20:55:12 +00:00
using Umbraco.Cms.Core.Net;
2021-02-23 09:05:06 +01:00
using Umbraco.Cms.Core.Security;
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
using Umbraco.Cms.Core.Services;
2021-02-23 09:05:06 +01:00
using Umbraco.Cms.Web.Common.Security;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.Common.Security
{
[TestFixture]
public class MemberSignInManagerTests
{
private Mock<ILogger<SignInManager<MemberIdentityUser>>> _mockLogger;
2021-04-12 18:02:43 +10:00
private readonly Mock<MemberManager> _memberManager = MockMemberManager();
public UserClaimsPrincipalFactory<MemberIdentityUser> CreateClaimsFactory(MemberManager userMgr)
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
=> new UserClaimsPrincipalFactory<MemberIdentityUser>(userMgr, Options.Create(new IdentityOptions()));
public MemberSignInManager CreateSut()
{
// This all needs to be setup because internally aspnet resolves a bunch
// of services from the HttpContext.RequestServices.
var serviceProviderFactory = new DefaultServiceProviderFactory();
var serviceCollection = new ServiceCollection();
serviceCollection
.AddLogging()
.AddAuthentication()
.AddCookie(IdentityConstants.ApplicationScheme);
IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(serviceCollection);
var httpContextFactory = new DefaultHttpContextFactory(serviceProvider);
IFeatureCollection features = new DefaultHttpContext().Features;
features.Set<IHttpConnectionFeature>(new HttpConnectionFeature
{
LocalIpAddress = IPAddress.Parse("127.0.0.1")
});
HttpContext httpContext = httpContextFactory.Create(features);
_mockLogger = new Mock<ILogger<SignInManager<MemberIdentityUser>>>();
return new MemberSignInManager(
2021-03-17 18:04:54 +00:00
_memberManager.Object,
Mock.Of<IHttpContextAccessor>(x => x.HttpContext == httpContext),
CreateClaimsFactory(_memberManager.Object),
Mock.Of<IOptions<IdentityOptions>>(),
_mockLogger.Object,
Mock.Of<IAuthenticationSchemeProvider>(),
Mock.Of<IUserConfirmation<MemberIdentityUser>>());
}
2021-04-12 18:02:43 +10:00
private static Mock<MemberManager> MockMemberManager()
=> new Mock<MemberManager>(
Mock.Of<IIpResolver>(),
Mock.Of<IUserStore<MemberIdentityUser>>(),
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
Options.Create(new IdentityOptions()),
2021-04-12 18:02:43 +10:00
Mock.Of<IPasswordHasher<MemberIdentityUser>>(),
Enumerable.Empty<IUserValidator<MemberIdentityUser>>(),
Enumerable.Empty<IPasswordValidator<MemberIdentityUser>>(),
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
new MembersErrorDescriber(),
2021-04-12 18:02:43 +10:00
Mock.Of<IServiceProvider>(),
Mock.Of<ILogger<UserManager<MemberIdentityUser>>>(),
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
Options.Create(new MemberPasswordConfigurationSettings()),
Mock.Of<IPublicAccessService>(),
Mock.Of<IHttpContextAccessor>());
[Test]
public async Task WhenPasswordSignInAsyncIsCalled_AndEverythingIsSetup_ThenASignInResultSucceededShouldBeReturnedAsync()
{
//arrange
var userId = "bo8w3d32q9b98";
MemberSignInManager sut = CreateSut();
var fakeUser = new MemberIdentityUser(777)
2020-12-01 19:47:56 +00:00
{
UserName = "TestUser",
2020-12-01 19:47:56 +00:00
};
2021-03-17 18:04:54 +00:00
var password = "testPassword";
var lockoutOnFailure = false;
var isPersistent = true;
_memberManager.Setup(x => x.GetUserIdAsync(It.IsAny<MemberIdentityUser>())).ReturnsAsync(userId);
_memberManager.Setup(x => x.GetUserNameAsync(It.IsAny<MemberIdentityUser>())).ReturnsAsync(fakeUser.UserName);
2021-03-14 22:19:27 +00:00
_memberManager.Setup(x => x.FindByNameAsync(It.IsAny<string>())).ReturnsAsync(fakeUser);
2021-03-17 18:28:56 +00:00
_memberManager.Setup(x => x.CheckPasswordAsync(fakeUser, password)).ReturnsAsync(true);
_memberManager.Setup(x => x.IsEmailConfirmedAsync(fakeUser)).ReturnsAsync(true);
_memberManager.Setup(x => x.IsLockedOutAsync(fakeUser)).ReturnsAsync(false);
//act
2021-03-17 18:04:54 +00:00
SignInResult actual = await sut.PasswordSignInAsync(fakeUser, password, isPersistent, lockoutOnFailure);
//assert
Assert.IsTrue(actual.Succeeded);
}
[Test]
public async Task WhenPasswordSignInAsyncIsCalled_AndTheResultFails_ThenASignInFailedResultShouldBeReturnedAsync()
{
//arrange
MemberSignInManager sut = CreateSut();
var fakeUser = new MemberIdentityUser(777)
{
UserName = "TestUser",
};
2021-03-17 18:04:54 +00:00
var password = "testPassword";
var lockoutOnFailure = false;
var isPersistent = true;
//act
2021-03-17 18:04:54 +00:00
SignInResult actual = await sut.PasswordSignInAsync(fakeUser, password, isPersistent, lockoutOnFailure);
//assert
Assert.IsFalse(actual.Succeeded);
}
}
}