Esempio n. 1
0
 protected virtual async Task CheckSelfRegistrationAsync()
 {
     if (!await SettingProvider.IsTrueAsync(AccountSettingNames.IsSelfRegistrationEnabled))
     {
         throw new UserFriendlyException(L["SelfRegistrationDisabledMessage"]);
     }
 }
Esempio n. 2
0
        public virtual async Task <ProfileDto> UpdateAsync(UpdateProfileDto input)
        {
            var user = await UserManager.GetByIdAsync(CurrentUser.GetId());

            if (await SettingProvider.IsTrueAsync(IdentitySettingNames.User.IsUserNameUpdateEnabled))
            {
                (await UserManager.SetUserNameAsync(user, input.UserName)).CheckErrors();
            }

            if (await SettingProvider.IsTrueAsync(IdentitySettingNames.User.IsEmailUpdateEnabled))
            {
                (await UserManager.SetEmailAsync(user, input.Email)).CheckErrors();
            }

            (await UserManager.SetPhoneNumberAsync(user, input.PhoneNumber)).CheckErrors();

            user.Name    = input.Name;
            user.Surname = input.Surname;

            input.MapExtraPropertiesTo(user);

            (await UserManager.UpdateAsync(user)).CheckErrors();

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <IdentityUser, ProfileDto>(user));
        }
Esempio n. 3
0
        public virtual async Task <IActionResult> OnGetAsync()
        {
            if (CurrentUser.IsAuthenticated)
            {
                ToastHelper.ToastSuccess(this, $"{L["Welcome back!"]}, {CurrentUser.Name}");
                if (ReturnUrl.IsNullOrEmpty())
                {
                    return(Redirect("/"));
                }
                else
                {
                    return(RedirectSafely(ReturnUrl, ReturnUrlHash));
                }
            }

            ActionHelper.AddTitle(this, "Login");

            LoginInput = new LoginInputModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            if (IsExternalLoginOnly)
            {
                //return await ExternalLogin(vm.ExternalLoginScheme, returnUrl);
                throw new NotImplementedException();
            }

            return(Page());
        }
Esempio n. 4
0
 protected virtual async Task CheckLocalLoginAsync()
 {
     if (!await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin))
     {
         throw new UserFriendlyException(L["LocalLoginDisabledMessage"]);
     }
 }
Esempio n. 5
0
        public virtual async Task <IActionResult> OnGetAsync()
        {
            LoginInput = new LoginInputModel();

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null || x.Name.Equals(_accountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
                            .Select(x => new ExternalProviderModel
            {
                DisplayName          = x.DisplayName,
                AuthenticationScheme = x.Name
            })
                            .ToList();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            ExternalProviders = providers.ToArray();

            if (IsExternalLoginOnly)
            {
                //return await ExternalLogin(vm.ExternalLoginScheme, returnUrl);
                throw new NotImplementedException();
            }

            return(Page());
        }
Esempio n. 6
0
    public virtual async Task <IActionResult> OnPostAsync(string action)
    {
        await CheckLocalLoginAsync();

        ValidateModel();

        ExternalProviders = await GetExternalProviders();

        EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

        await ReplaceEmailToUsernameOfInputIfNeeds();

        await IdentityOptions.SetAsync();

        var result = await SignInManager.PasswordSignInAsync(
            LoginInput.UserNameOrEmailAddress,
            LoginInput.Password,
            LoginInput.RememberMe,
            true
            );

        await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
        {
            Identity = IdentitySecurityLogIdentityConsts.Identity,
            Action   = result.ToIdentitySecurityLogAction(),
            UserName = LoginInput.UserNameOrEmailAddress
        });

        if (result.RequiresTwoFactor)
        {
            return(await TwoFactorLoginResultAsync());
        }

        if (result.IsLockedOut)
        {
            Alerts.Warning(L["UserLockedOutMessage"]);
            return(Page());
        }

        if (result.IsNotAllowed)
        {
            Alerts.Warning(L["LoginIsNotAllowed"]);
            return(Page());
        }

        if (!result.Succeeded)
        {
            Alerts.Danger(L["InvalidUserNameOrPassword"]);
            return(Page());
        }

        //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
        var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
                   await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);

        Debug.Assert(user != null, nameof(user) + " != null");

        return(RedirectSafely(ReturnUrl, ReturnUrlHash));
    }
        public async override Task <IActionResult> OnGetAsync()
        {
            LoginInput = new LoginInputModel();

            var context = await Interaction.GetAuthorizationContextAsync(ReturnUrl);

            if (context != null)
            {
                ShowCancelButton = true;

                LoginInput.UserNameOrEmailAddress = context.LoginHint;

                //TODO: Reference AspNetCore MultiTenancy module and use options to get the tenant key!
                var tenant = context.Parameters[TenantResolverConsts.DefaultTenantKey];
                if (!string.IsNullOrEmpty(tenant))
                {
                    CurrentTenant.Change(Guid.Parse(tenant));
                    Response.Cookies.Append(TenantResolverConsts.DefaultTenantKey, tenant);
                }
            }

            if (context?.IdP != null)
            {
                LoginInput.UserNameOrEmailAddress = context.LoginHint;
                ExternalProviders = new[] { new ExternalProviderModel {
                                                AuthenticationScheme = context.IdP
                                            } };
                return(Page());
            }

            var providers = await GetExternalProviders();

            ExternalProviders = providers.ToList();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            if (context?.Client?.ClientId != null)
            {
                var client = await ClientStore.FindEnabledClientByIdAsync(context?.Client?.ClientId);

                if (client != null)
                {
                    EnableLocalLogin = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            if (IsExternalLoginOnly)
            {
                return(await base.OnPostExternalLogin(providers.First().AuthenticationScheme));
            }

            return(Page());
        }
Esempio n. 8
0
        public virtual async Task <IActionResult> OnGetAsync()
        {
            Input = new LoginInputModel();
            await ExternalProviderHelper.GetVisibleExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            return(Page());
        }
Esempio n. 9
0
        public virtual async Task <IActionResult> OnPostAsync(string action)
        {
            await CheckLocalLoginAsync();

            ValidateModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            await ReplaceEmailToUsernameOfInputIfNeeds();

            var result = await SignInManager.PasswordSignInAsync(
                LoginInput.UserNameOrEmailAddress,
                LoginInput.Password,
                LoginInput.RememberMe,
                true
                );

            if (result.RequiresTwoFactor)
            {
                return(RedirectToPage("./SendSecurityCode", new
                {
                    returnUrl = ReturnUrl,
                    returnUrlHash = ReturnUrlHash,
                    rememberMe = LoginInput.RememberMe
                }));
            }

            if (result.IsLockedOut)
            {
                Alerts.Warning(L["UserLockedOutMessage"]);
                return(Page());
            }

            if (result.IsNotAllowed)
            {
                Alerts.Warning(L["LoginIsNotAllowed"]);
                return(Page());
            }

            if (!result.Succeeded)
            {
                Alerts.Danger(L["InvalidUserNameOrPassword"]);
                return(Page());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
                       await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress) ??
                       UserManager.Users.FirstOrDefault(m => m.PhoneNumber == LoginInput.UserNameOrEmailAddress);

            Debug.Assert(user != null, nameof(user) + " != null");

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
        public virtual async Task ChangeTwoFactorEnabledAsync(ChangeTwoFactorEnabledDto input)
        {
            if (!await SettingProvider.IsTrueAsync(IdentitySettingNames.TwoFactor.UsersCanChange))
            {
                throw new BusinessException(Volo.Abp.Identity.IdentityErrorCodes.CanNotChangeTwoFactor);
            }

            var user = await UserManager.GetByIdAsync(CurrentUser.GetId());

            (await UserManager.SetTwoFactorEnabledWithAccountConfirmedAsync(user, input.Enabled)).CheckErrors();

            await CurrentUnitOfWork.SaveChangesAsync();
        }
Esempio n. 11
0
        public virtual async Task SendAsync(SmsMessage smsMessage)
        {
            var domain = await SettingProvider.GetOrNullAsync(AliyunSmsSettingNames.Sms.Domain);

            var action = await SettingProvider.GetOrNullAsync(AliyunSmsSettingNames.Sms.ActionName);

            var version = await SettingProvider.GetOrNullAsync(AliyunSmsSettingNames.Sms.Version);

            Check.NotNullOrWhiteSpace(domain, AliyunSmsSettingNames.Sms.Domain);
            Check.NotNullOrWhiteSpace(action, AliyunSmsSettingNames.Sms.ActionName);
            Check.NotNullOrWhiteSpace(version, AliyunSmsSettingNames.Sms.Version);

            CommonRequest request = new CommonRequest
            {
                Method  = MethodType.POST,
                Domain  = domain,
                Action  = action,
                Version = version
            };

            await TryAddTemplateCodeAsync(request, smsMessage);
            await TryAddSignNameAsync(request, smsMessage);
            await TryAddSendPhoneAsync(request, smsMessage);

            TryAddTemplateParam(request, smsMessage);

            try
            {
                var client = await AcsClientFactory.CreateAsync();

                CommonResponse response        = client.GetCommonResponse(request);
                var            responseContent = Encoding.Default.GetString(response.HttpResponse.Content);
                var            aliyunResponse  = JsonSerializer.Deserialize <AliyunSmsResponse>(responseContent);
                if (!aliyunResponse.IsSuccess())
                {
                    if (await SettingProvider.IsTrueAsync(AliyunSmsSettingNames.Sms.VisableErrorToClient))
                    {
                        throw new UserFriendlyException(aliyunResponse.Code, aliyunResponse.Message);
                    }
                    throw new AliyunSmsException(aliyunResponse.Code, $"Text message sending failed, code:{aliyunResponse.Code}, message:{aliyunResponse.Message}!");
                }
            }
            catch (ServerException se)
            {
                throw new AliyunSmsException(se.ErrorCode, $"Sending text messages to aliyun server is abnormal,type: {se.ErrorType}, error: {se.ErrorMessage}");
            }
            catch (ClientException ce)
            {
                throw new AliyunSmsException(ce.ErrorCode, $"A client exception occurred in sending SMS messages,type: {ce.ErrorType}, error: {ce.ErrorMessage}");
            }
        }
Esempio n. 12
0
    public virtual async Task <IActionResult> OnGetAsync()
    {
        LoginInput = new LoginInputModel();

        ExternalProviders = await GetExternalProviders();

        EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

        if (IsExternalLoginOnly)
        {
            return(await OnPostExternalLogin(ExternalProviders.First().AuthenticationScheme));
        }

        return(Page());
    }
Esempio n. 13
0
        public virtual async Task <IActionResult> OnGetAsync()
        {
            LoginInput = new LoginInputModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            if (IsExternalLoginOnly)
            {
                //return await ExternalLogin(vm.ExternalLoginScheme, returnUrl);
                throw new NotImplementedException();
            }

            return(Page());
        }
        public virtual async Task <TClient> CreateAsync()
        {
            var regionId = await SettingProvider.GetOrNullAsync(AliyunSettingNames.Authorization.RegionId);

            var accessKey = await SettingProvider.GetOrNullAsync(AliyunSettingNames.Authorization.AccessKeyId);

            var accessKeySecret = await SettingProvider.GetOrNullAsync(AliyunSettingNames.Authorization.AccessKeySecret);

            Check.NotNullOrWhiteSpace(regionId, AliyunSettingNames.Authorization.RegionId);
            Check.NotNullOrWhiteSpace(accessKey, AliyunSettingNames.Authorization.AccessKeyId);
            Check.NotNullOrWhiteSpace(accessKeySecret, AliyunSettingNames.Authorization.AccessKeySecret);

            if (await SettingProvider.IsTrueAsync(AliyunSettingNames.Authorization.UseSecurityTokenService))
            {
                var cacheItem = await GetCacheItemAsync(accessKey, accessKeySecret, regionId);

                return(GetSecurityTokenClient(regionId, cacheItem.AccessKeyId, cacheItem.AccessKeySecret, cacheItem.SecurityToken));
            }

            return(GetClient(regionId, accessKey, accessKeySecret));
        }
Esempio n. 15
0
        public virtual async Task <ProfileDto> UpdateAsync(UpdateProfileDto input)
        {
            await IdentityOptions.SetAsync();

            var user = await UserManager.GetByIdAsync(CurrentUser.GetId());

            if (!string.Equals(user.UserName, input.UserName, StringComparison.InvariantCultureIgnoreCase))
            {
                if (await SettingProvider.IsTrueAsync(IdentitySettingNames.User.IsUserNameUpdateEnabled))
                {
                    (await UserManager.SetUserNameAsync(user, input.UserName)).CheckErrors();
                }
            }

            if (!string.Equals(user.Email, input.Email, StringComparison.InvariantCultureIgnoreCase))
            {
                if (await SettingProvider.IsTrueAsync(IdentitySettingNames.User.IsEmailUpdateEnabled))
                {
                    (await UserManager.SetEmailAsync(user, input.Email)).CheckErrors();
                }
            }

            if (!string.Equals(user.PhoneNumber, input.PhoneNumber, StringComparison.InvariantCultureIgnoreCase))
            {
                (await UserManager.SetPhoneNumberAsync(user, input.PhoneNumber)).CheckErrors();
            }

            user.Name    = input.Name;
            user.Surname = input.Surname;

            user.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);

            input.MapExtraPropertiesTo(user);

            (await UserManager.UpdateAsync(user)).CheckErrors();

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <IdentityUser, ProfileDto>(user));
        }
Esempio n. 16
0
        public virtual async Task <IActionResult> OnPostAsync(string action)
        {
            ActionHelper.AddTitle(this, "Login");

            // Clean old noitify data
            ViewData["LoginError"] = null;

            await CheckLocalLoginAsync();

            ValidateModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            await ReplaceEmailToUsernameOfInputIfNeeds();

            await IdentityOptions.SetAsync();

            var result = await SignInManager.PasswordSignInAsync(
                LoginInput.UserNameOrEmailAddress,
                LoginInput.Password,
                LoginInput.RememberMe,
                true
                );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = result.ToIdentitySecurityLogAction(),
                UserName = LoginInput.UserNameOrEmailAddress
            });

            if (result.RequiresTwoFactor)
            {
                return(await TwoFactorLoginResultAsync());
            }

            if (result.IsLockedOut)
            {
                ViewData["LoginError"] = L["Please try again after a few minutes"];
                ToastHelper.ToastError(this, L["Please try again after a few minutes"]);
                return(Page());
            }

            if (result.IsNotAllowed)
            {
                ViewData["LoginError"] = L["You are not permitted login right now"];
                ToastHelper.ToastError(this, L["You are not permitted login right now"]);
                return(Page());
            }

            if (!result.Succeeded)
            {
                ViewData["LoginError"] = L["Invalid Username/Email or Password"];
                ToastHelper.ToastError(this, L["Invalid Username/Email or Password"]);
                return(Page());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
                       await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);

            Debug.Assert(user != null, nameof(user) + " != null");

            ToastHelper.ToastSuccess(this, L["Login successful"]);

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
Esempio n. 17
0
        public virtual async Task <IActionResult> OnPostAsync()
        {
            if (!await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin))
            {
                MyAlerts.Danger(L["LocalLoginDisabledMessage"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            try
            {
                ValidateModel();
            }
            catch (AbpValidationException e)
            {
                var message = GetMessageFromException(e);
                MyAlerts.Warning(message, L["OperationFailed"]);
                return(await OnGetAsync());
            }

            await ReplaceEmailToUsernameOfInputIfNeeds();

            var result = await SignInManager.PasswordSignInAsync(
                Input.UserNameOrEmailAddress,
                Input.Password,
                Input.RememberMe,
                true
                );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = result.ToIdentitySecurityLogAction(),
                UserName = Input.UserNameOrEmailAddress
            });

            if (result.RequiresTwoFactor)
            {
                return(await TwoFactorLoginResultAsync());
            }

            if (result.IsLockedOut)
            {
                MyAlerts.Danger(L["UserLockedOutMessage"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            if (result.IsNotAllowed)
            {
                MyAlerts.Danger(L["LoginIsNotAllowed"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            if (!result.Succeeded)
            {
                MyAlerts.Warning(L["InvalidUserNameOrPassword"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(Input.UserNameOrEmailAddress) ??
                       await UserManager.FindByEmailAsync(Input.UserNameOrEmailAddress);

            Debug.Assert(user != null, nameof(user) + " != null");

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
Esempio n. 18
0
        [UnitOfWork] //TODO: Will be removed when we implement action filter
        public override async Task <IActionResult> OnPostAsync(string action)
        {
            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin).ConfigureAwait(false);

            if (action == "Cancel")
            {
                var context = await Interaction.GetAuthorizationContextAsync(ReturnUrl).ConfigureAwait(false);

                if (context == null)
                {
                    return(Redirect("~/"));
                }

                await Interaction.GrantConsentAsync(context, ConsentResponse.Denied).ConfigureAwait(false);

                return(Redirect(ReturnUrl));
            }

            ValidateModel();

            await ReplaceEmailToUsernameOfInputIfNeeds().ConfigureAwait(false);

            var result = await SignInManager.PasswordSignInAsync(
                LoginInput.UserNameOrEmailAddress,
                LoginInput.Password,
                LoginInput.RememberMe,
                true
                ).ConfigureAwait(false);

            if (result.RequiresTwoFactor)
            {
                return(RedirectToPage("./SendSecurityCode", new
                {
                    returnUrl = ReturnUrl,
                    returnUrlHash = ReturnUrlHash,
                    rememberMe = LoginInput.RememberMe
                }));
            }

            if (result.IsLockedOut)
            {
                Alerts.Warning(L["UserLockedOutMessage"]);
                return(Page());
            }

            if (result.IsNotAllowed)
            {
                Alerts.Warning(L["LoginIsNotAllowed"]);
                return(Page());
            }

            if (!result.Succeeded)
            {
                Alerts.Danger(L["InvalidUserNameOrPassword"]);
                return(Page());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress).ConfigureAwait(false) ??
                       await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress).ConfigureAwait(false);

            Debug.Assert(user != null, nameof(user) + " != null");
            await IdentityServerEvents.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName)).ConfigureAwait(false); //TODO: Use user's name once implemented

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
        public async override Task <IActionResult> OnPostAsync(string action)
        {
            if (action == "Cancel")
            {
                var context = await Interaction.GetAuthorizationContextAsync(ReturnUrl);

                if (context == null)
                {
                    return(Redirect("~/"));
                }

                await Interaction.GrantConsentAsync(context, new ConsentResponse()
                {
                    Error = AuthorizationError.AccessDenied
                });

                return(Redirect(ReturnUrl));
            }

            await CheckLocalLoginAsync();

            ValidateModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            await ReplaceEmailToUsernameOfInputIfNeeds();

            var result = await SignInManager.PasswordSignInAsync(
                LoginInput.UserNameOrEmailAddress,
                LoginInput.Password,
                LoginInput.RememberMe,
                true
                );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = result.ToIdentitySecurityLogAction(),
                UserName = LoginInput.UserNameOrEmailAddress
            });

            if (result.RequiresTwoFactor)
            {
                return(await TwoFactorLoginResultAsync());
            }

            if (result.IsLockedOut)
            {
                Alerts.Warning(L["UserLockedOutMessage"]);
                return(Page());
            }

            if (result.IsNotAllowed)
            {
                Alerts.Warning(L["LoginIsNotAllowed"]);
                return(Page());
            }

            if (!result.Succeeded)
            {
                Alerts.Danger(L["InvalidUserNameOrPassword"]);
                return(Page());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
                       await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);

            Debug.Assert(user != null, nameof(user) + " != null");
            await IdentityServerEvents.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName)); //TODO: Use user's name once implemented

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
Esempio n. 20
0
        public override async Task <IActionResult> OnGetAsync()
        {
            LoginInput = new LoginInputModel();

            var context = await Interaction.GetAuthorizationContextAsync(ReturnUrl);

            if (context != null)
            {
                LoginInput.UserNameOrEmailAddress = context.LoginHint;

                //TODO: Reference AspNetCore MultiTenancy module and use options to get the tenant key!
                var tenant = context.Parameters[TenantResolverConsts.DefaultTenantKey];
                if (!string.IsNullOrEmpty(tenant))
                {
                    CurrentTenant.Change(Guid.Parse(tenant));
                    Response.Cookies.Append(TenantResolverConsts.DefaultTenantKey, tenant);
                }
            }

            if (context?.IdP != null)
            {
                LoginInput.UserNameOrEmailAddress = context.LoginHint;
                ExternalProviders = new[] { new ExternalProviderModel {
                                                AuthenticationScheme = context.IdP
                                            } };
                return(Page());
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null || x.Name.Equals(_accountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
                            .Select(x => new ExternalProviderModel
            {
                DisplayName          = x.DisplayName,
                AuthenticationScheme = x.Name
            })
                            .ToList();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            if (context?.ClientId != null)
            {
                var client = await ClientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    EnableLocalLogin = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            ExternalProviders = providers.ToArray();

            if (IsExternalLoginOnly)
            {
                return(await base.OnPostExternalLogin(providers.First().AuthenticationScheme));
            }

            return(Page());
        }