private async Task <AccountModels.LoginViewModel> BuildLoginViewModelAsync(AccountModels.LoginViewModel model)
        {
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            var vm = BuildLoginViewModel(model.ReturnUrl, context);

            vm.Email      = model.Email;
            vm.RememberMe = model.RememberMe;
            return(vm);
        }
        public async Task <IActionResult> Login(AccountModels.LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _usersApplicationService.FindByUsernameAsync(model.Email);

                if (await _usersApplicationService.ValidateCredentialsAsync(user, model.Password))
                {
                    var tokenLifetime = 120; //_configuration.GetValue("TokenLifetimeMinutes", 120);

                    var props = new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(tokenLifetime),
                        AllowRefresh = true,
                        RedirectUri  = model.ReturnUrl,
                    };

                    if (model.RememberMe)
                    {
                        var permanentTokenLifetime = 365; //_configuration.GetValue("PermanentTokenLifetimeDays", 365);

                        props.ExpiresUtc   = DateTimeOffset.UtcNow.AddDays(permanentTokenLifetime);
                        props.IsPersistent = true;
                    }
                    ;

                    await _usersApplicationService.SignInAsync(user, props);

                    // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(RedirectToAction(nameof(LoggedIn)));
                }

                ModelState.AddModelError("", "Invalid username or password.");
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            ViewData["ReturnUrl"] = model.ReturnUrl;

            return(View(vm));
        }