Repository navigation
Expand file tree
/
Copy pathLoginControllerTwoFactorTests.cs
More file actions
164 lines (138 loc) · 7.07 KB
/
Copy pathLoginControllerTwoFactorTests.cs
File metadata and controls
164 lines (138 loc) · 7.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Utilities.Authentication;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.Mediator;
using Grand.Web.Admin.Controllers;
using Grand.Web.AdminShared.Models.Common;
using Grand.Web.Common.Localization;
using Grand.Web.Common.Security.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Moq;
namespace Grand.Web.Admin.Tests.Controllers;
[TestClass]
public class LoginControllerTwoFactorTests
{
private sealed class TestSession : ISession
{
private readonly Dictionary<string, byte[]> _data = new();
public bool IsAvailable => true;
public string Id => "s";
public IEnumerable<string> Keys => _data.Keys;
public void Clear() => _data.Clear();
public Task CommitAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task LoadAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public void Remove(string key) => _data.Remove(key);
public void Set(string key, byte[] value) => _data[key] = value;
public bool TryGetValue(string key, out byte[] value) => _data.TryGetValue(key, out value!);
}
private readonly Customer _customer = new() { Id = "c1", Email = "admin@shop.com" };
private Mock<ICustomerManagerService> _manager = null!;
private Mock<IGrandAuthenticationService> _authentication = null!;
private TestSession _session = null!;
private LoginController _controller = null!;
[TestInitialize]
public void Setup()
{
_customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.TwoFactorEnabled, Value = "True", StoreId = "" });
_manager = new Mock<ICustomerManagerService>();
_manager.Setup(x => x.LoginCustomer("admin@shop.com", "pwd", It.IsAny<string>(), It.IsAny<SignInSurface>()))
.ReturnsAsync(CustomerLoginResults.RequiresTwoFactor);
var customers = new Mock<ICustomerService>();
customers.Setup(x => x.GetCustomerByEmail("admin@shop.com", It.IsAny<string>())).ReturnsAsync(_customer);
_authentication = new Mock<IGrandAuthenticationService>();
var settings = new CustomerSettings {
TwoFactorAuthenticationEnabled = true,
TwoFactorAuthenticationType = TwoFactorAuthenticationType.AppVerification
};
var translations = new Mock<IRequestTranslationService>();
var workContextMock = new Mock<IWorkContext>();
workContextMock.Setup(w => w.CurrentCustomer).Returns(_customer);
var contextAccessorMock = new Mock<IContextAccessor>();
contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);
var storeContextMock = new Mock<IStoreContext>();
storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = "s1" });
contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object);
translations.Setup(x => x.GetResource(It.IsAny<string>())).Returns<string>(key => key);
_controller = new LoginController(settings, new CaptchaSettings(), translations.Object,
_manager.Object, customers.Object, _authentication.Object, new Mock<ICustomerMessageProviderService>().Object,
contextAccessorMock.Object, new Mock<IMediator>().Object);
_session = new TestSession();
_controller.ControllerContext = new ControllerContext {
HttpContext = new DefaultHttpContext { Session = _session },
RouteData = new RouteData { Values = { ["area"] = "Admin" } }
};
}
private Task<IActionResult> PasswordStep() =>
_controller.Index(new LoginModel { Email = "admin@shop.com", Password = "pwd" },
new Mock<IExternalAuthenticationService>().Object, new OidcLoginConfig());
[TestMethod]
public async Task Password_RequiresTwoFactor_GoesToThePanelsOwnSecondStep()
{
var result = (RedirectToActionResult)await PasswordStep();
Assert.AreEqual("TwoFactorAuthorization", result.ActionName);
Assert.AreEqual("Login", result.ControllerName);
Assert.AreEqual("Admin", result.RouteValues!["area"]);
Assert.IsFalse(_session.Keys.Contains("RequiresTwoFactor"), "the storefront's key signs in on the storefront");
}
[TestMethod]
public async Task SecondStep_Get_ShowsTheForm()
{
await PasswordStep();
var result = await _controller.TwoFactorAuthorization(new Mock<ITwoFactorAuthenticationService>().Object);
Assert.IsInstanceOfType<ViewResult>(result);
}
private static Mock<ITwoFactorSignInService> CodeAnswers(TwoFactorSignInResult result)
{
var twoFactor = new Mock<ITwoFactorSignInService>();
twoFactor.Setup(x => x.CheckCode(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<TwoFactorAuthenticationType>()))
.ReturnsAsync(result);
return twoFactor;
}
[TestMethod]
public async Task SecondStep_ValidCode_SignsInToThePanel()
{
await PasswordStep();
var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456",
CodeAnswers(TwoFactorSignInResult.Passed).Object);
Assert.AreEqual("AdminIndex", result.RouteName);
_authentication.Verify(x => x.SignIn(_customer, false), Times.Once);
Assert.IsFalse(_session.Keys.Any());
}
[TestMethod]
public async Task SecondStep_WrongCode_NotSignedIn()
{
await PasswordStep();
var result = await _controller.TwoFactorAuthorization("000000",
CodeAnswers(TwoFactorSignInResult.WrongCode).Object);
Assert.IsInstanceOfType<ViewResult>(result);
_authentication.Verify(x => x.SignIn(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);
}
[TestMethod]
public async Task SecondStep_WithoutPasswordStep_BackToThePanelLogin()
{
var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456",
CodeAnswers(TwoFactorSignInResult.Passed).Object);
Assert.AreEqual("AdminLogin", result.RouteName);
_authentication.Verify(x => x.SignIn(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);
}
[TestMethod]
public async Task SecondStep_LockedOut_SignInMustStartAgain()
{
await PasswordStep();
Assert.IsInstanceOfType<ViewResult>(await _controller.TwoFactorAuthorization("000000",
CodeAnswers(TwoFactorSignInResult.LockedOut).Object));
//the waiting sign-in is gone: even a code that passes goes back to the password step
var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456",
CodeAnswers(TwoFactorSignInResult.Passed).Object);
Assert.AreEqual("AdminLogin", result.RouteName);
_authentication.Verify(x => x.SignIn(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);
}
}