using Bit.Core.Auth.Enums; using Bit.Core.Auth.Models; using Bit.Core.Entities; using Bit.Core.Services; using Bit.Core.Utilities; using Bit.Test.Common.AutoFixture; using Bit.Test.Common.AutoFixture.Attributes; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; using Xunit; namespace Bit.Core.Test.Auth.Identity; [SutProviderCustomize] public abstract class BaseTokenProviderTests where T : IUserTwoFactorTokenProvider { public abstract TwoFactorProviderType TwoFactorProviderType { get; } protected static IEnumerable SetupCanGenerateData(params (Dictionary MetaData, bool ExpectedResponse)[] data) { return data.Select(d => new object[] { d.MetaData, d.ExpectedResponse, }); } protected virtual IUserService AdditionalSetup(SutProvider sutProvider, User user) { var userService = Substitute.For(); sutProvider.GetDependency() .GetService(typeof(IUserService)) .Returns(userService); SetupUserService(userService, user); return userService; } protected virtual void SetupUserService(IUserService userService, User user) { userService .TwoFactorProviderIsEnabledAsync(TwoFactorProviderType, user) .Returns(true); userService .CanAccessPremium(user) .Returns(true); } protected static UserManager SubstituteUserManager() { return new UserManager(Substitute.For>(), Substitute.For>(), Substitute.For>(), Enumerable.Empty>(), Enumerable.Empty>(), Substitute.For(), Substitute.For(), Substitute.For(), Substitute.For>>()); } protected void MockDatabase(User user, Dictionary metaData) { var providers = new Dictionary { [TwoFactorProviderType] = new TwoFactorProvider { Enabled = true, MetaData = metaData, }, }; user.TwoFactorProviders = JsonHelpers.LegacySerialize(providers); } public virtual async Task RunCanGenerateTwoFactorTokenAsync(Dictionary metaData, bool expectedResponse, User user, SutProvider sutProvider) { var userManager = SubstituteUserManager(); MockDatabase(user, metaData); AdditionalSetup(sutProvider, user); var response = await sutProvider.Sut.CanGenerateTwoFactorTokenAsync(userManager, user); Assert.Equal(expectedResponse, response); } }