From 0f0ff9dcececcb3bdf115e36ff31fdd9d8686699 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Fri, 4 Mar 2022 23:19:21 +0100 Subject: [PATCH] Fix login for invited users. --- .../Controllers/Account/AccountController.cs | 50 +++++++++++++++---- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs b/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs index 9e9a0ca6d..d54a7a600 100644 --- a/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs +++ b/backend/src/Squidex/Areas/IdentityServer/Controllers/Account/AccountController.cs @@ -228,8 +228,9 @@ namespace Squidex.Areas.IdentityServer.Controllers.Account } var isLoggedIn = result.Succeeded; + var isLocked = false; - IUser? user; + IUser? user = null; if (isLoggedIn) { @@ -244,24 +245,41 @@ namespace Squidex.Areas.IdentityServer.Controllers.Account throw new DomainException(T.Get("users.noEmailAddress")); } - var values = new UserValues + user = await userService.FindByEmailAsync(email!, HttpContext.RequestAborted); + + // If we have a login, we reject this user, otherwise you can login to an account you do not own. + if (user != null && await HasLoginAsync(user)) { - CustomClaims = login.Principal.Claims.GetSquidexClaims().ToList() - }; + user = null; + } - user = await userService.CreateAsync(email, values, identityOptions.LockAutomatically, HttpContext.RequestAborted); + if (user == null) + { + var values = new UserValues + { + CustomClaims = login.Principal.Claims.GetSquidexClaims().ToList() + }; - await userService.AddLoginAsync(user.Id, login, HttpContext.RequestAborted); + var locked = identityOptions.LockAutomatically; - (isLoggedIn, var locked) = await LoginAsync(login); + // Try to create a user. If the user exists an exception message is shown to the user. + user = await userService.CreateAsync(email!, values, locked, HttpContext.RequestAborted); + } - if (locked) + if (user != null) { - return View(nameof(LockedOut)); + await userService.AddLoginAsync(user.Id, login, HttpContext.RequestAborted); + + // Login might fail if the user is locked out. + (isLoggedIn, isLocked) = await LoginAsync(login); } } - if (!isLoggedIn) + if (isLocked) + { + return View(nameof(LockedOut)); + } + else if (!isLoggedIn) { return RedirectToAction(nameof(Login)); } @@ -275,6 +293,18 @@ namespace Squidex.Areas.IdentityServer.Controllers.Account } } + private async Task HasLoginAsync(IUser user) + { + if (await userService.HasPasswordAsync(user, HttpContext.RequestAborted)) + { + return true; + } + + var logins = await userService.GetLoginsAsync(user, HttpContext.RequestAborted); + + return logins.Count > 0; + } + private async Task<(bool Success, bool Locked)> LoginAsync(UserLoginInfo externalLogin) { var result = await SignInManager.ExternalLoginSignInAsync(externalLogin.LoginProvider, externalLogin.ProviderKey, true);