Skip to content

Commit eec1d7e

Browse files
Refuse an external registration whose e-mail already has an account (#1071)
1 parent 6246f40 commit eec1d7e

45 files changed

Lines changed: 326 additions & 274 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,31 @@ protected virtual async Task<ExternalAuthResult> AuthenticateNewUser(Customer cu
102102
return ExternalAuthResult.Associated(currentLoggedInUser);
103103
}
104104

105-
//or try to register new user
106-
if (_customerSettings.UserRegistrationType != UserRegistrationType.Disabled)
107-
return await RegisterNewUser(parameters, customer, storeId, language);
105+
//the same rule as the registration form; the provider's e-mail never takes over an existing account. Checked
106+
//before the registration type: the owner signs in and connects the account, registration or not
107+
if (await IsEmailOrUsernameTaken(parameters.Email, storeId))
108+
return ExternalAuthResult.EmailAlreadyExists();
108109

109110
//registration is disabled
110-
return ExternalAuthResult.RegistrationDisabled();
111+
if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
112+
return ExternalAuthResult.RegistrationDisabled();
113+
114+
//the new account signs in and receives its mail with the provider's e-mail
115+
if (string.IsNullOrWhiteSpace(parameters.Email))
116+
return ExternalAuthResult.EmailRequired();
117+
118+
return await RegisterNewUser(parameters, customer, storeId, language);
119+
}
120+
121+
/// <summary>
122+
/// Whether another customer has the provider's e-mail as their e-mail or, with usernames enabled, as their
123+
/// username; registration stores the provider's e-mail in both fields
124+
/// </summary>
125+
private async Task<bool> IsEmailOrUsernameTaken(string email, string storeId)
126+
{
127+
return await _customerService.GetCustomerByEmail(email, storeId) != null ||
128+
(_customerSettings.UsernamesEnabled &&
129+
await _customerService.GetCustomerByUsername(email, storeId) != null);
111130
}
112131

113132
/// <summary>

‎src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,9 @@ await RequiresPassword(linkedCustomer, storeId))
115115
!string.Equals(principal.FindFirst(_config.Claims.EmailVerified)?.Value, "true", StringComparison.OrdinalIgnoreCase))
116116
return OidcCustomerResult.InvalidToken("The e-mail address in the token is not verified");
117117

118-
//without per-store identity the e-mail is unique across stores - a store-scoped lookup would miss customers
119-
//of other stores and register a duplicate
120-
var customer = await _customerService.GetCustomerByEmail(email,
121-
_customerConfig.RegisterCustomersPerStore ? storeId : "");
118+
//the lookup applies the per-store identity rule: without it the store does not narrow the search, so a
119+
//customer of another store is found instead of registered twice
120+
var customer = await _customerService.GetCustomerByEmail(email, storeId);
122121
if (customer == null)
123122
return await Register(sub, email, storeId);
124123

@@ -182,8 +181,7 @@ public virtual async Task<OidcLoginResult> ResolveForLogin(string sub, string em
182181
return OidcLoginResult.Refused(OidcLoginRefusal.EmailNotVerified);
183182
}
184183

185-
var customer = await _customerService.GetCustomerByEmail(email,
186-
_customerConfig.RegisterCustomersPerStore ? storeId : "");
184+
var customer = await _customerService.GetCustomerByEmail(email, storeId);
187185
if (customer == null)
188186
{
189187
//provider-only with automatic accounts: the provider decides who gets in, no form and no registration type
@@ -323,8 +321,7 @@ private enum Provisioning
323321
{
324322
//the e-mail becomes the user name - another account may hold it as its user name without that e-mail
325323
var normalizedEmail = email.ToLowerInvariant();
326-
if (await _customerService.GetCustomerByUsername(normalizedEmail,
327-
_customerConfig.RegisterCustomersPerStore ? storeId : "") != null)
324+
if (await _customerService.GetCustomerByUsername(normalizedEmail, storeId) != null)
328325
{
329326
_logger.LogWarning("Subject {Subject}: the user name is already taken in store {StoreId}", sub, storeId);
330327
return (Provisioning.UserNameTaken, null, null);

‎src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ Task<int> GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI
108108

109109
/// <summary>
110110
/// Get customer by email.
111-
/// When <paramref name="storeId" /> is supplied (per-store customer identity) the lookup is scoped to
112-
/// that store; when it is empty the customer is resolved globally (default behaviour).
111+
/// With per-store customer identity a supplied <paramref name="storeId" /> scopes the lookup to that store
112+
/// (and the store-independent accounts); otherwise, or when it is empty, the customer is resolved globally.
113113
/// </summary>
114114
/// <param name="email">Email</param>
115115
/// <param name="storeId">Store identifier (optional)</param>
@@ -125,8 +125,8 @@ Task<int> GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI
125125

126126
/// <summary>
127127
/// Get customer by username.
128-
/// When <paramref name="storeId" /> is supplied (per-store customer identity) the lookup is scoped to
129-
/// that store; when it is empty the customer is resolved globally (default behaviour).
128+
/// With per-store customer identity a supplied <paramref name="storeId" /> scopes the lookup to that store
129+
/// (and the store-independent accounts); otherwise, or when it is empty, the customer is resolved globally.
130130
/// </summary>
131131
/// <param name="username">Username</param>
132132
/// <param name="storeId">Store identifier (optional)</param>

‎src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,15 @@ public enum ExternalAuthStatus
2222
/// <summary>The external account is unknown and registration of new customers is disabled</summary>
2323
RegistrationDisabled,
2424

25+
/// <summary>
26+
/// The external account is unknown and its e-mail belongs to an existing customer, who signs in and connects
27+
/// the account instead
28+
/// </summary>
29+
EmailAlreadyExists,
30+
31+
/// <summary>The external account is unknown and shares no e-mail, which a new customer needs</summary>
32+
EmailRequired,
33+
2534
/// <summary>The authentication failed; <see cref="ExternalAuthResult.Errors" /> says why</summary>
2635
Error
2736
}
@@ -60,5 +69,11 @@ public static ExternalAuthResult AlreadyAssigned() =>
6069
public static ExternalAuthResult RegistrationDisabled() =>
6170
new(ExternalAuthStatus.RegistrationDisabled, null, []);
6271

72+
public static ExternalAuthResult EmailAlreadyExists() =>
73+
new(ExternalAuthStatus.EmailAlreadyExists, null, []);
74+
75+
public static ExternalAuthResult EmailRequired() =>
76+
new(ExternalAuthStatus.EmailRequired, null, []);
77+
6378
public static ExternalAuthResult Error(string error) => new(ExternalAuthStatus.Error, null, [error]);
6479
}

‎src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,17 @@ public virtual async Task RegisterCustomer(RegistrationRequest request)
136136
if (request.Customer == null)
137137
throw new ArgumentException("Can't load current customer");
138138

139+
//every registration path answers a taken e-mail or username itself; this stops any path that forgot to
140+
var byEmail = await _customerService.GetCustomerByEmail(request.Email, request.StoreId);
141+
if (byEmail != null && byEmail.Id != request.Customer.Id)
142+
throw new GrandException("The e-mail is already used by another customer");
143+
if (_customerSettings.UsernamesEnabled)
144+
{
145+
var byUsername = await _customerService.GetCustomerByUsername(request.Username, request.StoreId);
146+
if (byUsername != null && byUsername.Id != request.Customer.Id)
147+
throw new GrandException("The username is already used by another customer");
148+
}
149+
139150
//event notification
140151
await _mediator.CustomerRegistrationEvent(request);
141152

‎src/Business/Grand.Business.Customers/Services/CustomerService.cs‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -238,15 +238,13 @@ public virtual async Task<Customer> GetCustomerByEmail(string email, string stor
238238
return null;
239239

240240
var loweredEmail = email.ToLowerInvariant();
241-
if (!string.IsNullOrEmpty(storeId))
241+
//without per-store identity the e-mail is unique across stores, so the store does not narrow the lookup
242+
if (_customerConfig.RegisterCustomersPerStore && !string.IsNullOrEmpty(storeId))
242243
{
243244
var inStore = await _customerRepository.GetOneAsync(x => x.Email == loweredEmail && x.StoreId == storeId);
244245
if (inStore != null)
245246
return inStore;
246247

247-
if (!_customerConfig.RegisterCustomersPerStore)
248-
return null;
249-
250248
return await _customerRepository.GetOneAsync(x =>
251249
x.Email == loweredEmail && (x.StoreId == null || x.StoreId == ""));
252250
}
@@ -291,17 +289,14 @@ public virtual async Task<Customer> GetCustomerByUsername(string username, strin
291289
return null;
292290

293291
var loweredUsername = username.ToLowerInvariant();
294-
if (!string.IsNullOrEmpty(storeId))
292+
//without per-store identity the username is unique across stores (see GetCustomerByEmail)
293+
if (_customerConfig.RegisterCustomersPerStore && !string.IsNullOrEmpty(storeId))
295294
{
296295
var inStore = await _customerRepository.GetOneAsync(x => x.Username == loweredUsername && x.StoreId == storeId);
297296
if (inStore != null)
298297
return inStore;
299298

300-
//no customer for this store: without per-store identity there is no fallback; with it, a
301-
//store-scoped lookup must still reach the store-independent system/back-office account
302-
if (!_customerConfig.RegisterCustomersPerStore)
303-
return null;
304-
299+
//no customer for this store: the lookup must still reach the store-independent system/back-office account
305300
return await _customerRepository.GetOneAsync(x =>
306301
x.Username == loweredUsername && (x.StoreId == null || x.StoreId == ""));
307302
}

‎src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@ public TokenWebController(
3737
IRefreshTokenService refreshTokenService,
3838
IExternalSignInPolicy externalSignInPolicy,
3939
IAntiforgery antiforgery,
40-
FrontendAPIConfig apiConfig,
41-
CustomerConfig customerConfig)
40+
FrontendAPIConfig apiConfig)
4241
{
4342
_customerService = customerService;
4443
_mediator = mediator;
@@ -47,17 +46,8 @@ public TokenWebController(
4746
_externalSignInPolicy = externalSignInPolicy;
4847
_antiforgery = antiforgery;
4948
_apiConfig = apiConfig;
50-
_customerConfig = customerConfig;
5149
}
5250

53-
private readonly CustomerConfig _customerConfig;
54-
55-
/// <summary>
56-
/// The current store id when per-store customer identity is enabled, otherwise empty (global lookup).
57-
/// </summary>
58-
private string CustomerStoreId =>
59-
_customerConfig.RegisterCustomersPerStore ? _contextAccessor.StoreContext.CurrentStore.Id : "";
60-
6151
[AllowAnonymous]
6252
[IgnoreAntiforgeryToken]
6353
[HttpPost]
@@ -93,7 +83,7 @@ public async Task<IActionResult> Login([FromBody] LoginWebModel model)
9383

9484
try
9585
{
96-
var customer = await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId);
86+
var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id);
9787
var claims = new Dictionary<string, string> {
9888
{ "CustomerId", customer.Id },
9989
{ "Email", model.Email },

‎src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,10 @@ public LoginWebValidator(
1616
FrontendAPIConfig apiConfig,
1717
ICustomerService customerService,
1818
ICustomerManagerService customerManagerService,
19-
IContextAccessor contextAccessor,
20-
CustomerConfig customerConfig)
19+
IContextAccessor contextAccessor)
2120
: base(validators)
2221
{
23-
var storeId = customerConfig.RegisterCustomersPerStore
24-
? contextAccessor.StoreContext.CurrentStore.Id
25-
: "";
22+
var storeId = contextAccessor.StoreContext.CurrentStore.Id;
2623

2724
if (!apiConfig.Enabled)
2825
{

‎src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs‎

Lines changed: 67 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ public void Init()
4242
_externalAuthenticationService = CreateService(UserRegistrationType.Standard);
4343
}
4444

45-
private ExternalAuthenticationService CreateService(UserRegistrationType userRegistrationType)
45+
private ExternalAuthenticationService CreateService(UserRegistrationType userRegistrationType,
46+
bool usernamesEnabled = false)
4647
{
4748
var externalAuthenticationSetting = new ExternalAuthenticationSettings {
4849
ActiveAuthenticationMethodSystemNames = [
@@ -53,7 +54,8 @@ private ExternalAuthenticationService CreateService(UserRegistrationType userReg
5354
return new ExternalAuthenticationService(_customerManagerServiceMock.Object, _customerServiceMock.Object,
5455
_groupServiceMock.Object, _mediatorMock.Object, _externalAuthenticationRecordRepository,
5556
_externalAuthenticationProviders,
56-
new CustomerSettings { UserRegistrationType = userRegistrationType }, externalAuthenticationSetting);
57+
new CustomerSettings { UserRegistrationType = userRegistrationType, UsernamesEnabled = usernamesEnabled },
58+
externalAuthenticationSetting);
5759
}
5860

5961

@@ -167,6 +169,69 @@ public async Task Authenticate_UnknownIdentity_RegistersPassedCustomerInPassedSt
167169
Assert.AreSame(guest, result.Customer);
168170
}
169171

172+
[TestMethod]
173+
public async Task Authenticate_UnknownIdentityWithEmailOfExistingCustomer_RegistersNobody()
174+
{
175+
_customerServiceMock.Setup(c => c.GetCustomerByEmail("taken@test.com", "store1"))
176+
.ReturnsAsync(new Customer { Id = "existing", Email = "taken@test.com" });
177+
var guest = new Customer { Id = "guest" };
178+
var parameters = new ExternalAuthParam {
179+
ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new", Email = "taken@test.com"
180+
};
181+
182+
var result =
183+
await _externalAuthenticationService.Authenticate(parameters, guest, new Store { Id = "store1" }, new Language());
184+
185+
Assert.AreEqual(ExternalAuthStatus.EmailAlreadyExists, result.Status);
186+
Assert.IsNull(result.Customer);
187+
_customerManagerServiceMock.Verify(m => m.RegisterCustomer(It.IsAny<RegistrationRequest>()), Times.Never);
188+
Assert.IsFalse(_externalAuthenticationRecordRepository.Table.Any());
189+
}
190+
191+
[TestMethod]
192+
public async Task Authenticate_UnknownIdentityWithEmailUsedAsUsername_RegistersNobody()
193+
{
194+
_customerServiceMock.Setup(c => c.GetCustomerByUsername("taken@test.com", "store1"))
195+
.ReturnsAsync(new Customer { Id = "existing", Username = "taken@test.com", Email = "other@test.com" });
196+
var parameters = new ExternalAuthParam {
197+
ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new", Email = "taken@test.com"
198+
};
199+
200+
var result = await CreateService(UserRegistrationType.Standard, usernamesEnabled: true)
201+
.Authenticate(parameters, new Customer { Id = "guest" }, new Store { Id = "store1" }, new Language());
202+
203+
Assert.AreEqual(ExternalAuthStatus.EmailAlreadyExists, result.Status);
204+
_customerManagerServiceMock.Verify(m => m.RegisterCustomer(It.IsAny<RegistrationRequest>()), Times.Never);
205+
}
206+
207+
[TestMethod]
208+
public async Task Authenticate_UnknownIdentityWithoutEmail_RegistersNobody()
209+
{
210+
var parameters = new ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new" };
211+
212+
var result = await _externalAuthenticationService.Authenticate(parameters, new Customer { Id = "guest" },
213+
new Store { Id = "store1" }, new Language());
214+
215+
Assert.AreEqual(ExternalAuthStatus.EmailRequired, result.Status);
216+
_customerManagerServiceMock.Verify(m => m.RegisterCustomer(It.IsAny<RegistrationRequest>()), Times.Never);
217+
Assert.IsFalse(_externalAuthenticationRecordRepository.Table.Any());
218+
}
219+
220+
[TestMethod]
221+
public async Task Authenticate_UnknownIdentityWithEmailOfExistingCustomerAndRegistrationDisabled_IsEmailAlreadyExists()
222+
{
223+
_customerServiceMock.Setup(c => c.GetCustomerByEmail("taken@test.com", "store1"))
224+
.ReturnsAsync(new Customer { Id = "existing", Email = "taken@test.com" });
225+
var parameters = new ExternalAuthParam {
226+
ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "new", Email = "taken@test.com"
227+
};
228+
229+
var result = await CreateService(UserRegistrationType.Disabled)
230+
.Authenticate(parameters, new Customer { Id = "guest" }, new Store { Id = "store1" }, new Language());
231+
232+
Assert.AreEqual(ExternalAuthStatus.EmailAlreadyExists, result.Status);
233+
}
234+
170235
[TestMethod]
171236
public async Task Authenticate_UnknownIdentityWithAdminApproval_IsAwaitingApproval()
172237
{

‎src/Tests/Grand.Business.Authentication.Tests/Services/OidcCustomerResolverLoginTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ public async Task NoEmail_Refused_InvalidIdentity() =>
132132
public async Task ExistingCustomer_Verified_LinkedAndSignIn()
133133
{
134134
var customer = new Customer { Id = "c1", Active = true, Email = "john@example.com" };
135-
_customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", "")).ReturnsAsync(customer);
135+
_customerService.Setup(x => x.GetCustomerByEmail("John@Example.com", Store)).ReturnsAsync(customer);
136136
var result = await Resolver().ResolveForLogin("sub-1", "John@Example.com", true, Store, Language);
137137
Assert.AreEqual(OidcLoginOutcome.SignIn, result.Outcome);
138138
var link = await _links.GetOneAsync(x => x.ExternalIdentifier == "sub-1");

0 commit comments

Comments
 (0)