示例#1
0
    public async Task <IActionResult> Verify2FACode(Verify2FACodeModel model, string?returnUrl = null)
    {
        MemberIdentityUser?user = await _memberSignInManager.GetTwoFactorAuthenticationUserAsync();

        if (user == null !)
        {
            _logger.LogWarning("PostVerify2FACode :: No verified member found, returning 404");
            return(NotFound());
        }

        if (ModelState.IsValid)
        {
            SignInResult result = await _memberSignInManager.TwoFactorSignInAsync(
                model.Provider,
                model.Code,
                model.IsPersistent,
                model.RememberClient);

            if (result.Succeeded && returnUrl is not null)
            {
                return(RedirectToLocal(returnUrl));
            }

            if (result.IsLockedOut)
            {
                ModelState.AddModelError(nameof(Verify2FACodeModel.Code), "Member is locked out");
            }
            else if (result.IsNotAllowed)
            {
                ModelState.AddModelError(nameof(Verify2FACodeModel.Code), "Member is not allowed");
            }
            else
            {
                ModelState.AddModelError(nameof(Verify2FACodeModel.Code), "Invalid code");
            }
        }

        // We need to set this, to ensure we show the 2fa login page
        IEnumerable <string> providerNames =
            await _twoFactorLoginService.GetEnabledTwoFactorProviderNamesAsync(user.Key);

        ViewData.SetTwoFactorProviderNames(providerNames);
        return(CurrentUmbracoPage());
    }
示例#2
0
        //[ApiExplorerSettings(IgnoreApi = true)]
        public async Task <IActionResult> CreateCompany([FromBody] ModelUserCompany model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.email, Name = model.Name, Email = model.email, Last_Name = model.Last_name
                };
                Microsoft.AspNetCore.Identity.SignInResult resultUser = await _signInManager.PasswordSignInAsync(model.email, model.Password, isPersistent : false, lockoutOnFailure : false);

                if (resultUser.Succeeded)
                {
                    if (context.UsersCompany.Count(x => x.IdUser == (context.Users.FirstOrDefault(y => y.Email == model.email).Id)) > 0)
                    {
                        return(BadRequest("El Usuario ya posee una Empresa asignada"));
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(context.Users.FirstOrDefault(x => x.Email == model.email), "Company");

                        if (context.Company.Count(x => x.Rut == model.Rut) > 0)
                        {
                            var UserCompany = new UsersCompany();
                            UserCompany.idCompany = model.Rut;
                            UserCompany.IdUser    = user.Id;
                            context.UsersCompany.Add(UserCompany);
                            context.SaveChanges();
                            //await _emailSender.SendEmailAsync(model.email, "Bienvenidos a la aplicación Aprovechapp!-.", CreateBodyWelcome(model)).ConfigureAwait(false);
                            return(Ok());
                        }
                        else
                        {
                            var company = new Company();
                            company.email = model.email;
                            company.Name  = model.Name;
                            company.Rut   = model.Rut;
                            company.Name  = model.NameBussines;
                            context.Company.Add(company);
                            context.SaveChanges();
                            var UserCompany = new UsersCompany();
                            UserCompany.idCompany = company.Rut;
                            UserCompany.IdUser    = user.Id;
                            context.UsersCompany.Add(UserCompany);
                            context.SaveChanges();
                            //await _emailSender.SendEmailAsync(model.email, "Bienvenidos a la aplicación Aprovechapp!-.", CreateBodyWelcome(model)).ConfigureAwait(false);
                            return(Ok());
                        }
                    }
                }
                else
                {
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(context.Users.FirstOrDefault(x => x.Email == model.email), "Company");

                        if (context.Company.Count(x => x.Rut == model.Rut) > 0)
                        {
                            var UserCompany = new UsersCompany();
                            UserCompany.idCompany = model.Rut;
                            UserCompany.IdUser    = user.Id;
                            context.UsersCompany.Add(UserCompany);
                            context.SaveChanges();
                            //await _emailSender.SendEmailAsync(model.email, "Bienvenidos a la aplicación Aprovechapp!-.", CreateBodyWelcome(model)).ConfigureAwait(false);
                            return(Ok());
                        }
                        else
                        {
                            var company = new Company();
                            company.email = model.email;
                            company.Name  = model.Name;
                            company.Rut   = model.Rut;
                            company.Name  = model.NameBussines;
                            context.Company.Add(company);
                            context.SaveChanges();
                            var UserCompany = new UsersCompany();
                            UserCompany.idCompany = company.Rut;
                            UserCompany.IdUser    = user.Id;
                            context.UsersCompany.Add(UserCompany);
                            context.SaveChanges();
                            //await _emailSender.SendEmailAsync(model.email, "Bienvenidos a la aplicación Aprovechapp!-.", CreateBodyWelcome(model)).ConfigureAwait(false);
                            return(Ok());
                        }
                    }
                    else
                    {
                        return(BadRequest(result.Errors));
                    }
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
示例#3
0
        public async Task <IActionResult> LogIn(LogInViewModel logInViewModel)
        {
            if (ModelState.IsValid)
            {
                UserApp user = await UserManager.FindByEmailAsync(logInViewModel.Email);

                if (user != null)
                {
                    if (await UserManager.IsLockedOutAsync(user))
                    {
                        ModelState.AddModelError(string.Empty, "Hesabınız bir süreliğine kilitlenmiştir.\nLütfen daha sonra tekrar deneyiniz.");
                        return(View(logInViewModel));
                    }
                    if (!UserManager.IsEmailConfirmedAsync(user).Result)
                    {
                        ModelState.AddModelError(string.Empty, "E-postanızı doğrulanmamıştır. Lütfen e-postanızı doğrulayınız.");
                        return(View(logInViewModel));
                    }

                    bool userCheck = await UserManager.CheckPasswordAsync(user, logInViewModel.Password);

                    if (userCheck)
                    {
                        await UserManager.ResetAccessFailedCountAsync(user);

                        await SignInManager.SignOutAsync();

                        Microsoft.AspNetCore.Identity.SignInResult result = await SignInManager.PasswordSignInAsync(user, logInViewModel.Password, logInViewModel.RememberMe, false);

                        if (result.RequiresTwoFactor)
                        {
                            if (user.TwoFactorAuthType == (sbyte)TwoFactorAuthTypes.Email || user.TwoFactorAuthType == (sbyte)TwoFactorAuthTypes.SMS)
                            {
                                HttpContext.Session.Remove("CurrentTime");
                            }
                            if (TempData["ReturnUrl"] != null)
                            {
                                return(RedirectToAction("LoginTwoFactor", "Home", new { returnUrl = TempData["ReturnUrl"].ToString() }));
                            }
                            return(RedirectToAction("LoginTwoFactor"));
                        }
                        else if (result.Succeeded)
                        {
                            if (TempData["ReturnUrl"] != null)
                            {
                                return(Redirect(TempData["ReturnUrl"].ToString()));
                            }
                            return(RedirectToAction("Index", "Member"));
                        }
                    }
                    else
                    {
                        await UserManager.AccessFailedAsync(user);

                        if (await UserManager.GetAccessFailedCountAsync(user) >= 3)
                        {
                            await UserManager.SetLockoutEndDateAsync(user, new DateTimeOffset(DateTime.Now.AddMinutes(45)));

                            ModelState.AddModelError(string.Empty, "Hesabınız başarısız giriş denemelerinden dolayı 45dk kilitlenmiştir.\nLütfen daha sonra tekrar deneyiniz.");
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Email adresiniz veya şifreniz yanlış.");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Bu email adresine kayıtlı kullanıcı bulunamamıştır.");
                }
            }
            return(View(logInViewModel));
        }
示例#4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                string userName = Input.Email;
                if (IsValidEmail(Input.Email))
                {
                    User potentialUser = await _userManager.FindByEmailAsync(Input.Email.Normalize());

                    if (potentialUser != null)
                    {
                        userName = potentialUser.UserName;
                    }
                }
                User user = await _userManager.FindByNameAsync(userName.Normalize());

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "Username or email not found");
                    return(Page());
                }
                else if (!await _userManager.IsEmailConfirmedAsync(user))
                {
                    ModelState.AddModelError(string.Empty, "Email Not Verified");
                    return(Page());
                }
                SignInResult result = await _signInManager.PasswordSignInAsync(
                    user,
                    Input.Password,
                    Input.RememberMe,
                    lockoutOnFailure : true
                    );

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }
                else if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                else if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else if (result.IsNotAllowed)
                {
                    _logger.LogWarning("User account Not Allowed");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            ModelState.AddModelError(string.Empty, "Something Wrong");
            return(Page());
        }
示例#5
0
        public async Task <IActionResult> Login(RoleModification model, Login login, User statuslog)
        {
            if (login.Email != null)
            {
                AppUser appUser = await userManager.FindByEmailAsync(login.Email);

                if (appUser != null)
                {
                    await signInManager.SignOutAsync();

                    Microsoft.AspNetCore.Identity.SignInResult result1 = await signInManager.PasswordSignInAsync(appUser, login.Password, false, true);

                    if (result1.Succeeded)
                    {
                        List <string> role = new List <string>();
                        role.Add(model.RoleName);
                        foreach (string userId in model.DeleteIds ?? new string[] { })
                        {
                            AppUser user = await userManager.FindByIdAsync(userId);

                            if (user != null)
                            {
                                var result2 = await userManager.FindByNameAsync(model.RoleName);
                            }
                        }


                        var updateLoginStatus = await __userLoginStatus.UpdatStaus(appUser.Id, true);

                        TempData["UserId"] = appUser.Id;


                        var getrole = userManager.GetRolesAsync(appUser);
                        if (getrole.Result[0] == "Admin")
                        {
                            return(RedirectToAction("Index1", "Home"));
                        }
                        if (getrole.Result[0] == "User")
                        {
                            return(RedirectToAction("Index", "UserHome"));
                        }
                        if (getrole.Result[0] == "Manager")
                        {
                            return(Redirect(login.ReturnUrl ?? "/UserIndex"));
                        }
                        //if (User.IsInRole(appUser.Id,"Admin")) { return Redirect(login.ReturnUrl ?? "/"); }
                        //if (User.IsInRole("Admin")) { return Redirect(login.ReturnUrl ?? "/"); }
                        return(Redirect(login.ReturnUrl ?? "/"));
                    }

                    /*bool emailStatus = await userManager.IsEmailConfirmedAsync(appUser);
                     * if (emailStatus == false)
                     * {
                     *  ModelState.AddModelError(nameof(login.Email), "Email is unconfirmed, please confirm it first");
                     * }*/

                    if (result1.IsLockedOut)
                    {
                        _toastNotification.AddErrorToastMessage(ResponseMessageUtilities.ACCOUNT_LOCKED_OUT);
                    }
                    if (!result1.Succeeded)
                    {
                        _toastNotification.AddErrorToastMessage(ResponseMessageUtilities.INVALID_LOGIN);
                        return(View());
                    }
                    if (result1.RequiresTwoFactor)
                    {
                        return(RedirectToAction("LoginTwoStep", new { appUser.Email, login.ReturnUrl }));
                    }
                }
                _toastNotification.AddErrorToastMessage(ResponseMessageUtilities.INVALID_LOGIN);
                return(View());
                //ModelState.AddModelError(nameof(login.Email), "Login Failed: Invalid Email or password");
            }
            return(View(login));
        }
示例#6
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToAction(nameof(Login)));
            }
            ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            // Sign in the user with this external login provider if the user already has a login.
            Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
                return(RedirectToLocal(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToAction(nameof(Lockout)));
            }
            else // In case user does not exists, create user
            {
                string username = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier) ?? Guid.NewGuid().ToString().Remove('-');
                string name     = info.Principal.FindFirstValue(ClaimTypes.Name) ?? username;
                string email    = info.Principal.FindFirstValue(ClaimTypes.Email) ?? "";
                string dob      = info.Principal.FindFirstValue(ClaimTypes.DateOfBirth);
                string gender   = info.Principal.FindFirstValue(ClaimTypes.Gender);
                string avatar   = "";
                if (info.LoginProvider == "Facebook")
                {
                    avatar = $"https://graph.facebook.com/{info.ProviderKey}/picture?type=large";
                }
                if (info.LoginProvider == "Google")
                {
                    avatar = info.Principal.FindFirstValue("image");
                    // avatar = $"https://www.googleapis.com/plus/v1/people/{info.ProviderKey}?fields=image&key={googleApiKey}";
                }

                ApplicationUser user = new ApplicationUser {
                    UserName = username, Email = email, Name = name, Avatar = avatar, Gender = gender
                };
                IdentityResult result1 = await _userManager.CreateAsync(user);

                if (result1.Succeeded)
                {
                    result1 = await _userManager.AddLoginAsync(user, info);

                    if (result1.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }

                return(RedirectToLocal(returnUrl));
            }
        }
示例#7
0
        public async Task <IActionResult> Login([FromBody] CredentialModel model)
        {
            _logger.LogWarning("ini LogIn - process");
            _logger.LogInformation("ini LogIn - process");

            User user = await _userInMgr.FindByEmailAsync(model.Email);

            if (user != null)
            {
                _logger.LogInformation($"LogIn - process for user {user.Email}");

                if (user.Disabled)
                {
                    ModelState.AddModelError("", "Your account is disabled, please contact with the web master");
                    return(BadRequest(new ApiBadRequestResponse(ModelState)));
                }

                if (!user.EmailConfirmed)
                {
                    ModelState.AddModelError("", "Please confirm your email or contact with the web master");
                    return(BadRequest(new ApiBadRequestResponse(ModelState)));
                }

                var validCredentials = await _userInMgr.CheckPasswordAsync(user, model.Password);

                // When a user is lockedout, this check is done to ensure that even if the credentials are valid
                // the user can not login until the lockout duration has passed
                if (await _userInMgr.IsLockedOutAsync(user))
                {
                    ModelState.AddModelError("",
                                             $"Your account has been locked out for {_config["Account:DefaultAccountLockoutTimeSpan"]} minutes due to multiple failed login attempts.");
                }
                // if user is subject to lockouts and the credentials are invalid
                // record the failure and check if user is lockedout and display message, otherwise,
                // display the number of attempts remaining before lockout
                else if (await _userInMgr.GetLockoutEnabledAsync(user) && !validCredentials)
                {
                    // Record the failure which also may cause the user to be locked out
                    await _userInMgr.AccessFailedAsync(user);

                    string message;

                    if (await _userInMgr.IsLockedOutAsync(user))
                    {
                        message = string.Format(
                            "Your account has been locked out for {0} minutes due to multiple failed login attempts.",
                            _config["Account:DefaultAccountLockoutTimeSpan"]);
                    }
                    else
                    {
                        int accessFailedCount = await _userInMgr.GetAccessFailedCountAsync(user);

                        int attemptsLeft = Convert.ToInt32(_config["Account:MaxFailedAccessAttemptsBeforeLockout"]) - accessFailedCount;

                        message = string.Format(
                            "Invalid credentials. You have {0} more attempt(s) before your account gets locked out..",
                            attemptsLeft);
                    }

                    ModelState.AddModelError("", message);
                }
                else if (!validCredentials)
                {
                    ModelState.AddModelError("", "Invalid credentials. Please try again.");
                }
                else
                {
                    await _userInMgr.ResetAccessFailedCountAsync(user);

                    Microsoft.AspNetCore.Identity.SignInResult signInStatus = await _signInMgr.PasswordSignInAsync(
                        user.UserName, model.Password, model.RememberMe, false);

                    if (signInStatus.Succeeded)
                    {
                        _logger.LogInformation("LogIn - Success");
                        _logger.LogInformation($"user LogIn info email:{user.Email}, idUser:{user.Id}");
                        return(Ok(ModelFactory.Create(user)));
                    }

                    if (signInStatus.IsNotAllowed)
                    {
                        _logger.LogWarning("LogIn - Invalid password");
                        ModelState.AddModelError("", "Invalid credentials. Please try again");
                    }
                }
            }
            else
            {
                _logger.LogWarning("LogIn - invalid email.");
                ModelState.AddModelError("", "Invalid credentials. Please try again");
            }

            _logger.LogWarning("LogIn - BadRequest.");
            return(BadRequest(new ApiBadRequestResponse(ModelState)));
        }
示例#8
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl)
        {
            var errors = new List <string>();

            ExternalLoginInfo?loginInfo = await _memberSignInManager.GetExternalLoginInfoAsync();

            if (loginInfo is null)
            {
                errors.Add("Invalid response from the login provider");
            }
            else
            {
                SignInResult result = await _memberSignInManager.ExternalLoginSignInAsync(loginInfo, false, _securitySettings.Value.MemberBypassTwoFactorForExternalLogins);

                if (result == SignInResult.Success)
                {
                    // Update any authentication tokens if succeeded
                    await _memberSignInManager.UpdateExternalAuthenticationTokensAsync(loginInfo);

                    return(RedirectToLocal(returnUrl));
                }

                if (result == SignInResult.TwoFactorRequired)
                {
                    MemberIdentityUser attemptedUser =
                        await _memberManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey);

                    if (attemptedUser == null)
                    {
                        return(new ValidationErrorResult(
                                   $"No local user found for the login provider {loginInfo.LoginProvider} - {loginInfo.ProviderKey}"));
                    }


                    var providerNames = await _twoFactorLoginService.GetEnabledTwoFactorProviderNamesAsync(attemptedUser.Key);

                    ViewData.SetTwoFactorProviderNames(providerNames);

                    return(CurrentUmbracoPage());
                }

                if (result == SignInResult.LockedOut)
                {
                    errors.Add(
                        $"The local member {loginInfo.Principal.Identity?.Name} for the external provider {loginInfo.ProviderDisplayName} is locked out.");
                }
                else if (result == SignInResult.NotAllowed)
                {
                    // This occurs when SignInManager.CanSignInAsync fails which is when RequireConfirmedEmail , RequireConfirmedPhoneNumber or RequireConfirmedAccount fails
                    // however since we don't enforce those rules (yet) this shouldn't happen.
                    errors.Add(
                        $"The member {loginInfo.Principal.Identity?.Name} for the external provider {loginInfo.ProviderDisplayName} has not confirmed their details and cannot sign in.");
                }
                else if (result == SignInResult.Failed)
                {
                    // Failed only occurs when the user does not exist
                    errors.Add("The requested provider (" + loginInfo.LoginProvider +
                               ") has not been linked to an account, the provider must be linked before it can be used.");
                }
                else if (result == MemberSignInManager.ExternalLoginSignInResult.NotAllowed)
                {
                    // This occurs when the external provider has approved the login but custom logic in OnExternalLogin has denined it.
                    errors.Add(
                        $"The user {loginInfo.Principal.Identity?.Name} for the external provider {loginInfo.ProviderDisplayName} has not been accepted and cannot sign in.");
                }
                else if (result == MemberSignInManager.AutoLinkSignInResult.FailedNotLinked)
                {
                    errors.Add("The requested provider (" + loginInfo.LoginProvider +
                               ") has not been linked to an account, the provider must be linked from the back office.");
                }
                else if (result == MemberSignInManager.AutoLinkSignInResult.FailedNoEmail)
                {
                    errors.Add(
                        $"The requested provider ({loginInfo.LoginProvider}) has not provided the email claim {ClaimTypes.Email}, the account cannot be linked.");
                }
                else if (result is MemberSignInManager.AutoLinkSignInResult autoLinkSignInResult &&
                         autoLinkSignInResult.Errors.Count > 0)
                {
                    errors.AddRange(autoLinkSignInResult.Errors);
                }
        public async Task<IActionResult> ExternalLoginCallback(string returnUrl)
        {
            var errors = new List<string>();

            ExternalLoginInfo loginInfo = await _memberSignInManager.GetExternalLoginInfoAsync();
            if (loginInfo is null)
            {
                errors.Add("Invalid response from the login provider");
            }
            else
            {
                SignInResult result = await _memberSignInManager.ExternalLoginSignInAsync(loginInfo, false);

                if (result == SignInResult.Success)
                {
                    // Update any authentication tokens if succeeded
                    await _memberSignInManager.UpdateExternalAuthenticationTokensAsync(loginInfo);

                    return RedirectToLocal(returnUrl);
                }

                if (result == SignInResult.TwoFactorRequired)
                {
                    MemberIdentityUser attemptedUser =
                        await _memberManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey);
                    if (attemptedUser == null)
                    {
                        return new ValidationErrorResult(
                            $"No local user found for the login provider {loginInfo.LoginProvider} - {loginInfo.ProviderKey}");
                    }

                    // create a with information to display a custom two factor send code view
                    var verifyResponse =
                        new ObjectResult(new { userId = attemptedUser.Id })
                        {
                            StatusCode = StatusCodes.Status402PaymentRequired
                        };

                    return verifyResponse;
                }

                if (result == SignInResult.LockedOut)
                {
                    errors.Add(
                        $"The local member {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} is locked out.");
                }
                else if (result == SignInResult.NotAllowed)
                {
                    // This occurs when SignInManager.CanSignInAsync fails which is when RequireConfirmedEmail , RequireConfirmedPhoneNumber or RequireConfirmedAccount fails
                    // however since we don't enforce those rules (yet) this shouldn't happen.
                    errors.Add(
                        $"The member {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not confirmed their details and cannot sign in.");
                }
                else if (result == SignInResult.Failed)
                {
                    // Failed only occurs when the user does not exist
                    errors.Add("The requested provider (" + loginInfo.LoginProvider +
                               ") has not been linked to an account, the provider must be linked before it can be used.");
                }
                else if (result == MemberSignInManager.ExternalLoginSignInResult.NotAllowed)
                {
                    // This occurs when the external provider has approved the login but custom logic in OnExternalLogin has denined it.
                    errors.Add(
                        $"The user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not been accepted and cannot sign in.");
                }
                else if (result == MemberSignInManager.AutoLinkSignInResult.FailedNotLinked)
                {
                    errors.Add("The requested provider (" + loginInfo.LoginProvider +
                               ") has not been linked to an account, the provider must be linked from the back office.");
                }
                else if (result == MemberSignInManager.AutoLinkSignInResult.FailedNoEmail)
                {
                    errors.Add(
                        $"The requested provider ({loginInfo.LoginProvider}) has not provided the email claim {ClaimTypes.Email}, the account cannot be linked.");
                }
                else if (result is MemberSignInManager.AutoLinkSignInResult autoLinkSignInResult &&
                         autoLinkSignInResult.Errors.Count > 0)
                {
                    errors.AddRange(autoLinkSignInResult.Errors);
                }
示例#10
0
        private async Task <IActionResult> ExternalSignInAsync(ExternalLoginInfo loginInfo, Func <IActionResult> response)
        {
            if (loginInfo == null)
            {
                throw new ArgumentNullException(nameof(loginInfo));
            }
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            // Sign in the user with this external login provider (which auto links, etc...)
            SignInResult result = await _signInManager.ExternalLoginSignInAsync(loginInfo, isPersistent : false, bypassTwoFactor : _securitySettings.Value.UserBypassTwoFactorForExternalLogins);

            var errors = new List <string>();

            if (result == SignInResult.Success)
            {
                // Update any authentication tokens if succeeded
                await _signInManager.UpdateExternalAuthenticationTokensAsync(loginInfo);

                // Check if we are in an upgrade state, if so we need to redirect
                if (_runtimeState.Level == Core.RuntimeLevel.Upgrade)
                {
                    // redirect to the the installer
                    return(Redirect("/"));
                }
            }
            else if (result == SignInResult.TwoFactorRequired)
            {
                var attemptedUser = await _userManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey);

                if (attemptedUser == null)
                {
                    return(new ValidationErrorResult($"No local user found for the login provider {loginInfo.LoginProvider} - {loginInfo.ProviderKey}"));
                }

                var twofactorView = _backOfficeTwoFactorOptions.GetTwoFactorView(attemptedUser.UserName);
                if (twofactorView.IsNullOrWhiteSpace())
                {
                    return(new ValidationErrorResult($"The registered {typeof(IBackOfficeTwoFactorOptions)} of type {_backOfficeTwoFactorOptions.GetType()} did not return a view for two factor auth "));
                }

                // create a with information to display a custom two factor send code view
                var verifyResponse = new ObjectResult(new
                {
                    twoFactorView = twofactorView,
                    userId        = attemptedUser.Id
                })
                {
                    StatusCode = StatusCodes.Status402PaymentRequired
                };

                return(verifyResponse);
            }
            else if (result == SignInResult.LockedOut)
            {
                errors.Add($"The local user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} is locked out.");
            }
            else if (result == SignInResult.NotAllowed)
            {
                // This occurs when SignInManager.CanSignInAsync fails which is when RequireConfirmedEmail , RequireConfirmedPhoneNumber or RequireConfirmedAccount fails
                // however since we don't enforce those rules (yet) this shouldn't happen.
                errors.Add($"The user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not confirmed their details and cannot sign in.");
            }
            else if (result == SignInResult.Failed)
            {
                // Failed only occurs when the user does not exist
                errors.Add("The requested provider (" + loginInfo.LoginProvider + ") has not been linked to an account, the provider must be linked from the back office.");
            }
            else if (result == ExternalLoginSignInResult.NotAllowed)
            {
                // This occurs when the external provider has approved the login but custom logic in OnExternalLogin has denined it.
                errors.Add($"The user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not been accepted and cannot sign in.");
            }
            else if (result == AutoLinkSignInResult.FailedNotLinked)
            {
                errors.Add("The requested provider (" + loginInfo.LoginProvider + ") has not been linked to an account, the provider must be linked from the back office.");
            }
            else if (result == AutoLinkSignInResult.FailedNoEmail)
            {
                errors.Add($"The requested provider ({loginInfo.LoginProvider}) has not provided the email claim {ClaimTypes.Email}, the account cannot be linked.");
            }
            else if (result is AutoLinkSignInResult autoLinkSignInResult && autoLinkSignInResult.Errors.Count > 0)
            {
                errors.AddRange(autoLinkSignInResult.Errors);
            }
        private async Task <Framework.WebApi.AuthenticationResponse> GetAuthenticationResponse(
            Elmah.MvcCore.Models.ApplicationUser user
            , Microsoft.AspNetCore.Identity.SignInResult result)
        {
            var loginResponse = new Framework.WebApi.AuthenticationResponse
            {
                Succeeded = result.Succeeded
                ,
                IsLockedOut = result.IsLockedOut
                ,
                IsNotAllowed = result.IsNotAllowed
                ,
                RequiresTwoFactor = result.RequiresTwoFactor
                ,
                EntityID = user != null ? user.EntityID : null
            };

            // authentication successful, then generate jwt token
            string tokenInString = Elmah.MvcCore.Security.CustomizedClaimTypes.GetJwtSecurityTokenInString(user.Id.ToLower(), _appSettings.Secret);

            loginResponse.Token = tokenInString;

            // Load LogIn User related data
            if (loginResponse.Succeeded)
            {
                loginResponse.Roles = await _userManager.GetRolesAsync(user);

                #region TODO: Load more data to LoginResponse

                //// TODO: Load more data to LoginResponse
                //using (var scope = _serviceProvider.CreateScope())
                //{
                //    var criteria = new NTierOnTime.CommonBLLEntities.EntityChainedQueryCriteriaIdentifier();
                //    criteria.Identifier.EntityID.NullableValueToCompare = user.EntityID;

                //    var entityResponse = new NTierOnTime.AspNetMvcCoreViewModel.Entity.DashboardVM(); // TODO: how to IoC
                //    entityResponse.CriteriaOfMasterEntity = criteria;
                //    entityResponse.SetServiceProvider(this._serviceProvider);
                //    await entityResponse.LoadData(
                //        isToLoadFK_CourseCategory_Entity_ParentEntityID_List: false
                //        , isToLoadFK_Album_Entity_Owner_List: false
                //        , isToLoadFK_Comment_Entity_PostedByID_List: false
                //        , isToLoadFK_EntityAddress_Entity_EntityID_List: false
                //        , isToLoadFK_EntityAlbum_Entity_EntityID_List: false
                //        , isToLoadFK_EntityCalendarItem_Entity_EntityID_List: false
                //        , isToLoadFK_EntityCommentThread_Entity_EntityID_List: false
                //        , isToLoadFK_EntityContact_Entity_EntityID_List: false
                //        , isToLoadFK_EntityEmail_Entity_EntityID_List: false
                //        , isToLoadFK_EntityScheduleGroup_Entity_EntityID_List: false
                //        , isToLoadFK_EntityVirtualAddress_Entity_EntityID_List: false
                //        , isToLoadFK_Liking_Entity_EntityID_List: false
                //        , isToLoadFK_Liking_Entity_TheOtherSideEntityID_List: false
                //        , isToLoadFK_MemberProgram_Entity_ProgramEntityID_List: false
                //        , isToLoadFK_Membership_Entity_MasterEntityID_List: false
                //        , isToLoadFK_Membership_Entity_SlaveEntityID_List: true
                //        , isToLoadFK_ProgramScheduleCalendarItem_Entity_ProgramEntityID_List: false
                //        , isToLoadFK_BusinessEntity_Entity_EntityID_FormView: false
                //        , isToLoadFK_Class_Entity_EntityID_FormView: false
                //        , isToLoadFK_Course_Entity_EntityID_FormView: false
                //        , isToLoadFK_ActivitySummary_Entity_EntityID_FormView: false
                //        , isToLoadFK_Membership_Entity_MembershipID_FormView: true
                //        , isToLoadFK_Person_Entity_EntityID_FormView: true);

                //    // 1. Entity
                //    if (entityResponse.StatusOfMasterEntity == Framework.Services.BusinessLogicLayerResponseStatus.MessageOK || entityResponse.StatusOfMasterEntity == Framework.Services.BusinessLogicLayerResponseStatus.UIProcessReady)
                //    {
                //        loginResponse.Entity = entityResponse.MasterEntity;
                //    }

                //    // 2. Person
                //    if (entityResponse.StatusOfFK_Person_Entity_EntityID_FormView == Framework.Services.BusinessLogicLayerResponseStatus.MessageOK || entityResponse.StatusOfFK_Person_Entity_EntityID_FormView == Framework.Services.BusinessLogicLayerResponseStatus.UIProcessReady)
                //    {
                //        loginResponse.HasPerson = entityResponse.StatusOfFK_Person_Entity_EntityID_FormView == Framework.Services.BusinessLogicLayerResponseStatus.MessageOK || entityResponse.StatusOfFK_Person_Entity_EntityID_FormView == Framework.Services.BusinessLogicLayerResponseStatus.UIProcessReady;
                //        loginResponse.Person = entityResponse.FK_Person_Entity_EntityID_FormView;
                //    }

                //    // 3. Joined Memberships
                //    if (entityResponse.StatusOfFK_Membership_Entity_SlaveEntityID_List == Framework.Services.BusinessLogicLayerResponseStatus.MessageOK || entityResponse.StatusOfFK_Membership_Entity_SlaveEntityID_List == Framework.Services.BusinessLogicLayerResponseStatus.UIProcessReady)
                //    {
                //        loginResponse.HasJoinedMemberShip = entityResponse.StatusOfFK_Membership_Entity_SlaveEntityID_List == Framework.Services.BusinessLogicLayerResponseStatus.MessageOK || entityResponse.StatusOfFK_Membership_Entity_SlaveEntityID_List == Framework.Services.BusinessLogicLayerResponseStatus.UIProcessReady;
                //        loginResponse.JoinedMemberships = entityResponse.FK_Membership_Entity_SlaveEntityID_List;
                //    }

                //}

                #endregion TODO: Load more data to LoginResponse
            }
            return(loginResponse);
        }
 /// <summary>
 /// Менеджер аутентификации
 /// </summary>
 private static Mock <ISignInManagerBoutique> GetSignInManager(SignInResult signInResult) =>
 new Mock <ISignInManagerBoutique>().
 Void(singMock => singMock.Setup(signInManager => signInManager.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(),
                                                                                    It.IsAny <bool>(), It.IsAny <bool>())).
      ReturnsAsync(signInResult));
示例#13
0
        public async Task <IActionResult> Login(LoginModel details, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                ISession session = HttpContext.Session;
                AppUser  user    = await userManager.FindByEmailAsync(details.Email);

                if (user != null)
                {
                    if (context.Students
                        .Include(s => s.StudentUser)
                        .ToArray()
                        .Select(s => s.StudentUserId)
                        .Contains(user.Id))
                    {
                        long studentId = context.Students
                                         .Include(s => s.StudentUser)
                                         .ToArray()
                                         .First(s => s.StudentUserId.Contains(user.Id)).StudentId;
                        SecurityHelper.LoggedInStudents.Add(studentId);

                        await signInManager.SignOutAsync();

                        Microsoft.AspNetCore.Identity.SignInResult result =
                            await signInManager.PasswordSignInAsync(
                                user, details.Password, false, false);

                        if (result.Succeeded)
                        {
                            session.Set <long>("student", studentId);
                            return(Redirect(returnUrl ?? "/"));
                        }
                    }
                    else if (context.Clients
                             .Include(c => c.ClientUser)
                             .ToArray()
                             .Select(c => c.ClientUserId)
                             .Contains(user.Id))
                    {
                        long clientId = context.Clients
                                        .Include(c => c.ClientUser)
                                        .ToArray()
                                        .First(s => s.ClientUserId.Contains(user.Id)).ClientId;
                        SecurityHelper.LoggedInClients.Add(clientId);

                        await signInManager.SignOutAsync();

                        Microsoft.AspNetCore.Identity.SignInResult result =
                            await signInManager.PasswordSignInAsync(
                                user, details.Password, false, false);

                        if (result.Succeeded)
                        {
                            session.Set <long>("client", clientId);
                            return(Redirect(returnUrl ?? "/"));
                        }
                    }
                }
                ModelState.AddModelError(nameof(LoginModel.Email), "Несуществующий пользователь или пароль");
            }
            return(View(details));
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                Microsoft.AspNetCore.Identity.SignInResult inputUserName;
                Microsoft.AspNetCore.Identity.SignInResult inputEmail;
                Microsoft.AspNetCore.Identity.SignInResult result = Microsoft.AspNetCore.Identity.SignInResult.Failed;

                var userByEmail = await _userManager.FindByEmailAsync(Input.UserNameOrEmail);

                if (userByEmail != null)
                {
                    inputEmail = await _signInManager.PasswordSignInAsync(userByEmail, Input.Password, Input.RememberMe, lockoutOnFailure : false);

                    if (inputEmail.Succeeded)
                    {
                        result = inputEmail;
                    }
                }
                else
                {
                    inputUserName = await _signInManager.PasswordSignInAsync(Input.UserNameOrEmail, Input.Password, Input.RememberMe, lockoutOnFailure : false);

                    if (inputUserName.Succeeded)
                    {
                        result = inputUserName;
                    }
                }

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }

                var userWithUsername = await _userManager.FindByNameAsync(Input.UserNameOrEmail);

                var isPassOk = await _userManager.CheckPasswordAsync(userWithUsername, Input.Password);

                if (userWithUsername != null && userWithUsername.EmailConfirmed == false && isPassOk)
                {
                    return(RedirectToPage("RegisterConfirmation", new { email = userWithUsername.Email }));
                }

                var userWithEmail = await _userManager.FindByEmailAsync(Input.UserNameOrEmail);

                if (userWithEmail != null && userWithEmail.EmailConfirmed == false && result.Succeeded && isPassOk)
                {
                    return(RedirectToPage("RegisterConfirmation", new { email = userWithEmail.Email }));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
示例#15
0
        public override async Task <LoginReply> Login(LoginRequest request, ServerCallContext context)
        {
            AppUser?user = await _userManager.FindByNameAsync(request.UserId);

            HttpContext httpContext = context.GetHttpContext();

            IPAddress?ip = httpContext.Connection.RemoteIpAddress;

            if (ip == null)
            {
                return(new LoginReply
                {
                    State = LoginStateEnum.Failed
                });
            }

            StringValues userAgent;

            httpContext.Request.Headers.TryGetValue("User-Agent", out userAgent);

            if (userAgent.Count != 1)
            {
                return(new LoginReply
                {
                    State = LoginStateEnum.Failed
                });
            }

            bool isUserBlocked         = false;
            bool isUserOnTrustedDevice = false;

            if (user != null)
            {
                isUserBlocked = await _bruteforceManager.IsUserBlockedAsync(user);

                string?encryptedDeviceId;
                context.GetHttpContext().Request.Cookies.TryGetValue(DeviceCookieManager.DEVICE_COOKIE_STRING, out encryptedDeviceId);

                if (encryptedDeviceId != null)
                {
                    isUserOnTrustedDevice = await _deviceCookieManager.IsCookieTrustedForUser(
                        new EncryptedDeviceCookie(encryptedDeviceId),
                        user
                        );
                }
            }
            bool isIpBlocked = await _bruteforceManager.IsIpBlockedAsync(ip);

            if (
                !isUserOnTrustedDevice
                &&
                (isUserBlocked || isIpBlocked)
                )
            {
                return(new LoginReply
                {
                    State = LoginStateEnum.Blocked,
                });
            }

            if (user == null)
            {
                await _bruteforceManager.MarkInvalidLoginAttemptAsync(
                    ip,
                    userAgent[0],
                    request.UserId
                    );

                return(new LoginReply
                {
                    State = LoginStateEnum.Failed
                });
            }
            else
            {
                if (user.IsDisabled)
                {
                    return(new LoginReply
                    {
                        State = LoginStateEnum.Disabled
                    });
                }
            }

            Microsoft.AspNetCore.Identity.SignInResult result =
                await _signInManager.PasswordSignInAsync(user, request.Password, false, false);

            if (result.Succeeded)
            {
                return(new LoginReply
                {
                    State = LoginStateEnum.Success
                });
            }
            else if (result.RequiresTwoFactor)
            {
                return(new LoginReply
                {
                    State = LoginStateEnum.TwoFactorRequired
                });
            }

            await _bruteforceManager.MarkInvalidLoginAttemptAsync(
                ip,
                userAgent[0],
                request.UserId
                );

            return(new LoginReply
            {
                State = LoginStateEnum.Failed
            });
        }
        public async Task <ActionResult> LoginModal(string userEmail, string userPassword)
        {
            Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(userEmail, userPassword, isPersistent : true, lockoutOnFailure : false);

            return(RedirectToAction("Index", "Home"));
        }
示例#17
0
        public async Task <ActionResult> Register(RegisterViewModel model, int SelectedMajor, Classification SelectedPositionType)
        {
            Decimal decStudentGPA;
            Int32   intGraduationDate;

            try
            {
                decStudentGPA = Convert.ToDecimal(model.GPA);
            }
            catch  //this code will display when something is wrong
            {
                //Add a message for the viewbag
                ViewBag.Message1 = "GPA must be a valid decimal";

                //Re-populate dropdown
                ViewBag.AllMajors = GetAllMajors();

                //Send user back to home page
                return(View("Register"));
            }

            try
            {
                intGraduationDate = Convert.ToInt32(model.GraduationDate);
            }
            catch  //this code will display when something is wrong
            {
                //Add a message for the viewbag
                ViewBag.Message2 = "GraduationDate must be a valid number";

                //Re-populate dropdown
                ViewBag.AllMajors = GetAllMajors();

                //Send user back to home page
                return(View("Register"));
            }

            ModelState.Clear();
            Major major = _db.Majors.Find(SelectedMajor);

            model.Major = major;
            TryValidateModel(model);

            if (ModelState.IsValid)
            {
                AppUser user = new AppUser
                {
                    //TODO: Add the rest of the user fields here
                    UserName       = model.Email,
                    Email          = model.Email,
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    Major          = major,
                    GraduationDate = intGraduationDate,
                    PositionType   = SelectedPositionType.ToString(),
                    GPA            = decStudentGPA,
                    Active         = true
                };

                IdentityResult result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //TODO: Add user to desired role. This example adds the user to the customer role

                    await _userManager.AddToRoleAsync(user, "Student");

                    if (User.IsInRole("CSO"))
                    {
                        AppUser userLoggedIn = await _userManager.FindByNameAsync(User.Identity.Name);

                        await _signInManager.SignInAsync(userLoggedIn, isPersistent : false);
                    }

                    else
                    {
                        Microsoft.AspNetCore.Identity.SignInResult result2 = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, lockoutOnFailure : false);
                    }
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            //re-populate the Viewbag in case there is an error
            ViewBag.AllMajors = GetAllMajors();
            return(View(model));
        }
        public async Task <IActionResult> Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                AppUser user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    if (await _userManager.IsLockedOutAsync(user))
                    {
                        ModelState.AddModelError("", "Saat başına yapılabilen maksimum istek sayısını aştınız");
                        return(View(model));
                    }

                    if (_userManager.IsEmailConfirmedAsync(user).Result == false)
                    {
                        ModelState.AddModelError("", "Email adresiniz onaylanmamıştır Lütfen e-postanızı kontrol ediniz");
                        return(View(model));
                    }

                    await _signInManager.SignOutAsync();

                    Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, false);

                    if (result.Succeeded)
                    {
                        await _userManager.ResetAccessFailedCountAsync(user);

                        if (TempData["ReturnUrl"] != null)
                        {
                            return(Redirect(TempData["ReturnUrl"].ToString()));
                        }
                        return(RedirectToAction("GetArticles", "Article"));
                    }
                    else
                    {
                        await _userManager.AccessFailedAsync(user);

                        int fail = await _userManager.GetAccessFailedCountAsync(user);

                        ModelState.AddModelError("", $"{fail} kez başarısız giriş");

                        if (fail == 3)
                        {
                            await _userManager.SetLockoutEndDateAsync(user, new System.DateTimeOffset(DateTime.Now.AddMinutes(60)));

                            ModelState.AddModelError("", "Hesabınız 3 başarısız girişten dolayı 1 saat süreyle kitlenmiştir.Lütfen daha sonra tekrar deneyiniz");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Email adresiniz veya şifreniz yanlış");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Email adresiniz veya şifreniz yanlış");
                }
            }
            //ViewData["Message"] = _message;
            return(View(model));
        }
示例#19
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToAction(nameof(Login)));
            }
            ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            // Sign in the user with this external login provider if the user already has a login.
            Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                string          email        = info.Principal.FindFirstValue(ClaimTypes.Email);
                ApplicationUser existingUser = await _userManager.FindByEmailAsync(email);

                if (existingUser != null)
                {
                    string logMessage = String.Format("User {0} logged in with {1} provider.", existingUser.UserName, info.LoginProvider);

                    await NotificationSender.SendTeamNotificationAsync(logMessage);

                    _logger.LogInformation(logMessage);

                    SetProfileOnSession(new Guid(existingUser.Id), existingUser.UserName);

                    await SetStaffRoles(existingUser);

                    SetPreferences(existingUser);
                }

                return(RedirectToLocal(returnUrl));
            }

            if (result.IsLockedOut)
            {
                return(RedirectToAction(nameof(Lockout)));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ViewData["ReturnUrl"]     = returnUrl;
                ViewData["LoginProvider"] = info.LoginProvider;
                ViewData["ButtonText"]    = SharedLocalizer["Register"];
                string text = "You've successfully authenticated with your external account. Please choose a username to use and click the Register button to finish logging in.";

                string email = info.Principal.FindFirstValue(ClaimTypes.Email);

                MvcExternalLoginViewModel model = new MvcExternalLoginViewModel {
                    Email = email
                };

                ApplicationUser existingUser = await _userManager.FindByEmailAsync(email);

                if (existingUser != null)
                {
                    model.UserExists = true;
                    model.Username   = existingUser.UserName;

                    text = "Oh! It looks like you already have a user registered here with us. Check your info below and confirm to link your account to your external account.";

                    ViewData["ButtonText"] = SharedLocalizer["Link Acounts"];
                }
                else
                {
                    model.ProfileName = SelectName(info);
                }

                ViewData["RegisterText"] = SharedLocalizer[text];

                return(View("ExternalLogin", model));
            }
        }
示例#20
0
        public async Task <IActionResult> HandleLogin([Bind(Prefix = "loginModel")] LoginModel model)
        {
            if (ModelState.IsValid == false)
            {
                return(CurrentUmbracoPage());
            }

            MergeRouteValuesToModel(model);

            // Sign the user in with username/password, this also gives a chance for developers to
            // custom verify the credentials and auto-link user accounts with a custom IBackOfficePasswordChecker
            SignInResult result = await _signInManager.PasswordSignInAsync(
                model.Username, model.Password, isPersistent : model.RememberMe, lockoutOnFailure : true);

            if (result.Succeeded)
            {
                TempData["LoginSuccess"] = true;

                // If there is a specified path to redirect to then use it.
                if (model.RedirectUrl.IsNullOrWhiteSpace() == false)
                {
                    // Validate the redirect URL.
                    // If it's not a local URL we'll redirect to the root of the current site.
                    return(Redirect(Url.IsLocalUrl(model.RedirectUrl)
                        ? model.RedirectUrl
                        : CurrentPage !.AncestorOrSelf(1) !.Url(PublishedUrlProvider)));
                }

                // Redirect to current URL by default.
                // This is different from the current 'page' because when using Public Access the current page
                // will be the login page, but the URL will be on the requested page so that's where we need
                // to redirect too.
                return(RedirectToCurrentUmbracoUrl());
            }

            if (result.RequiresTwoFactor)
            {
                MemberIdentityUser attemptedUser = await _memberManager.FindByNameAsync(model.Username);

                if (attemptedUser == null)
                {
                    return(new ValidationErrorResult(
                               $"No local member found for username {model.Username}"));
                }

                var providerNames = await _twoFactorLoginService.GetEnabledTwoFactorProviderNamesAsync(attemptedUser.Key);

                ViewData.SetTwoFactorProviderNames(providerNames);
            }
            else if (result.IsLockedOut)
            {
                ModelState.AddModelError("loginModel", "Member is locked out");
            }
            else if (result.IsNotAllowed)
            {
                ModelState.AddModelError("loginModel", "Member is not allowed");
            }
            else
            {
                ModelState.AddModelError("loginModel", "Invalid username or password");
            }
            return(CurrentUmbracoPage());
        }
        public async Task <IActionResult> LoginUserAsync([FromBody] LoginModel LoginModelDTO)
        {
            JObject responseObject = new JObject();

            try
            {
                if (LoginModelDTO == null)
                {
                    responseObject.Add("message", JToken.FromObject("Login request body cannot be null!"));
                    return(UtilityExtensions.ReturnResponse(responseObject, HttpStatusCode.BadRequest));
                }

                if (!ModelState.IsValid)
                {
                    string modelErrorMessage = string.Join(" | ", ModelState.Values
                                                           .SelectMany(v => v.Errors)
                                                           .Select(e => e.ErrorMessage));

                    responseObject.Add("message", JToken.FromObject(modelErrorMessage));
                    return(UtilityExtensions.ReturnResponse(responseObject, HttpStatusCode.BadRequest));
                }

                SignInResult signInResult = await _signInManager.PasswordSignInAsync
                                                (userName : LoginModelDTO.UserName,
                                                password : LoginModelDTO.Password,
                                                isPersistent : true,
                                                lockoutOnFailure : false);

                if (signInResult.Succeeded)
                {
                    ApplicationUser      currentlyLoggedinUser = _userManager.Users.SingleOrDefault(x => x.UserName == LoginModelDTO.UserName);
                    IEnumerable <string> role = await _userManager.GetRolesAsync(currentlyLoggedinUser);

                    if (role.Count() > 0)
                    {
                        responseObject.Add("role", JToken.FromObject(role.ElementAt(0)));
                    }
                    else
                    {
                        responseObject.Add("message", JToken.FromObject("User is unauthorized to login!!!"));
                        return(UtilityExtensions.ReturnResponse(responseObject, HttpStatusCode.Unauthorized));
                    }
                    if (currentlyLoggedinUser == null)
                    {
                        responseObject.Add("message", JToken.FromObject("User with credentials not found"));
                        return(UtilityExtensions.ReturnResponse(responseObject, HttpStatusCode.NotFound));
                    }

                    string jwtSecurityToken = await GenerateJwtToken(currentlyLoggedinUser);

                    responseObject.Add("access_token", JToken.FromObject(jwtSecurityToken));
                    responseObject.Add("expires", JToken.FromObject(30));
                    responseObject.Add("email", JToken.FromObject(currentlyLoggedinUser.Email));

                    return(UtilityExtensions.ReturnResponse(responseObject, HttpStatusCode.OK));
                }
                else
                {
                    responseObject.Add("message", JToken.FromObject("User is unauthorized to login!!!"));
                    return(UtilityExtensions.ReturnResponse(responseObject, HttpStatusCode.Unauthorized));
                }
            }
            catch (Exception ex)
            {
                responseObject.Add("message", JToken.FromObject(ex.Message));
                return(UtilityExtensions.ReturnResponse(responseObject, HttpStatusCode.InternalServerError));
            }
        }
        //[HttpPost, Route("login"), AllowAnonymous]
        ////public async Task<IActionResult> Login([FromBody]JObject jo)
        //public async Task<IActionResult> Login()
        //{
        //    Console.WriteLine("call login~. No Parameter");
        //    //foreach (string key in Response.Headers.Keys)
        //    //{
        //    //    Console.WriteLine($"{key} : {Response.Headers[key]}");
        //    //}
        //    //Response.Cookies.Append("babo", "you~");
        //    //if (jo == null)
        //    //    return NoContent();
        //    //return await ClaimsLogin(jo);
        //    return Ok();
        //}

        //private async Task<IActionResult> ClaimsLogin([FromBody]JObject jo)
        //{
        //    bool isUservalid = false;
        //    LoginViewModel user = JsonConvert.DeserializeObject<LoginViewModel>(jo.ToString());

        //    if (ModelState.IsValid && isUservalid)
        //    {
        //        var claims = new List<Claim>();

        //        claims.Add(new Claim(ClaimTypes.Name, user.Email));


        //        var identity = new ClaimsIdentity(
        //            claims, JwtBearerDefaults.AuthenticationScheme);

        //        var principal = new ClaimsPrincipal(identity);

        //        var props = new AuthenticationProperties();
        //        props.IsPersistent = user.RememberMe;

        //        HttpContext.SignInAsync(
        //            IdentityConstants.ApplicationScheme,
        //            principal, props).Wait();
        //        string token = JasonWebTokenManager.GenerateToken(user.Email);
        //        return Ok(new { Token = token });
        //    }
        //    else
        //    {
        //        return BadRequest();
        //    }
        //}

        private async Task <IActionResult> OldLogin([FromBody] LoginModel user)
        {
            //[FromBody]
            //JObject jo = null;
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(user.Email) || string.IsNullOrEmpty(user.Password))
                {
                    Console.WriteLine("Invalid User");
                    return(BadRequest());
                }

                UserAccountEF account = await _userManager.FindByEmailAsync(user.Email);

                if (account == null)
                {
                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).UserNotFound();
                    IdentityResult _result = IdentityResult.Failed(error);
                    return(BadRequest(new { Result = _result }));
                }
                else if (account.SignInConfirm == false)
                {
                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).SignInNotConfirm(user.Email);
                    IdentityResult _result = IdentityResult.Failed(error);
                    return(BadRequest(new { Result = _result }));
                }
                else if (account.Expire <= DateTime.Now)
                {
                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).Expired();
                    IdentityResult _result = IdentityResult.Failed(error);
                    return(BadRequest(new { Result = _result }));
                }

                Microsoft.AspNetCore.Identity.SignInResult signResult = await _signInManager.PasswordSignInAsync(user.Email, user.Password, true, false);

                if (signResult.Succeeded)
                {
                    var accountUser = await _userManager.FindByEmailAsync(user.Email);

                    string token = await GenerateAccessTokenAsync(accountUser);

                    string result       = JasonWebTokenManager.ValidateToken(user.Email, token, ClaimTypes.NameIdentifier);
                    string refreshToken = null;



                    if (distributedCache.TryGetValue(user.Email, out refreshToken) == false)
                    {
                        refreshToken = JasonWebTokenManager.GenerateRefreshToken(user.Email);
                        var cacheEntryOptions = new MemoryCacheEntryOptions()
                                                .SetSlidingExpiration(TimeSpan.FromDays(100));
                        distributedCache.Set(user.Email, refreshToken, cacheEntryOptions);
                    }
                    //if (string.IsNullOrEmpty(returnUrl) == false)
                    //{
                    //    Console.WriteLine("returnurl:" + returnUrl);
                    //    return Redirect(returnUrl);
                    //}
                    Console.WriteLine("Log-in Success: " + user.Email);
                    return(Ok(new { Result = signResult, Token = token, RefreshToken = refreshToken, User = accountUser }));
                }
                else
                {
                    Console.WriteLine($"Login Failed");
                    //if (signResult.RequiresTwoFactor)
                    //{
                    //    return RedirectToAction("act", new { ReturnUrl = returnUrl, RememberMe = user.RememberMe });
                    //}
                    if (signResult.IsLockedOut)
                    {
                        IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).UserLockoutEnabled();
                        IdentityResult _result = IdentityResult.Failed(error);
                        return(BadRequest(new { Result = _result }));
                    }
                    else
                    {
                        IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).PasswordMismatch();
                        IdentityResult _result = IdentityResult.Failed(error);
                        return(BadRequest(new { Result = _result }));
                    }
                }
            }
            else
            {
                Console.WriteLine("Invalid LoginViewModel");
                return(Ok(StatusCodes.Status406NotAcceptable));
            }
        }
示例#23
0
        private async Task <SignInResult> GetTokenAndSaveOnCookie(LoginRequest loginRequest, SignInResult signInResult)
        {
            var token = await _authHttpService.GetTokenAsync(loginRequest);

            if (token is null)
            {
                return(SignInResult.Failed);
            }

            var options = new CookieOptions
            {
                HttpOnly = true,
                Secure   = true,
                SameSite = SameSiteMode.Strict,
                MaxAge   = TimeSpan.FromMinutes(10)
            };

            _httpContextAccessor.HttpContext.Response.Cookies.Delete("bibliotecaToken");
            _httpContextAccessor.HttpContext.Response.Cookies.Append("bibliotecaToken", token, options);

            return(signInResult);
        }
示例#24
0
 internal LoginServiceBuilder WithSignInResult(IdentitySignInResult signInResult)
 {
     _signInManager = CreateDefaultMockSignInManager(signInResult);
     return(this);
 }
示例#25
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? this.Url.Content("~/");

            if (this.ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                Microsoft.AspNetCore.Identity.SignInResult result = await this.signInManager
                                                                    .PasswordSignInAsync(this.Input.Username, this.Input.Password, this.Input.RememberMe, lockoutOnFailure : false);

                var user = await this.userManager.FindByNameAsync(this.Input.Username);

                if (result.Succeeded)
                {
                    this.logger.LogInformation("User logged in.");

                    if (user == null)
                    {
                        return(this.NotFound("Unable to load user for update last login."));
                    }

                    user.LastLoginTime = DateTimeOffset.UtcNow;
                    var lastLoginResult = await this.userManager.UpdateAsync(user);

                    if (!lastLoginResult.Succeeded)
                    {
                        throw new InvalidOperationException($"Unexpected error occurred setting the last login date" +
                                                            $" ({lastLoginResult.ToString()}) for user with ID '{user.Id}'.");
                    }

                    if (await this.userManager.IsEmailConfirmedAsync(user) == false)
                    {
                        this.ErrorMessage = this.sharedLocalizer.GetHtmlString(ErrorMessages.EmailNotConfirmed);
                        this.ModelState.AddModelError(string.Empty, ErrorMessages.EmailNotConfirmed);
                        return(this.Page());
                    }

                    return(this.Redirect(GlobalConstants.UserPanelUrl));
                }

                if (await this.userManager.IsEmailConfirmedAsync(user) == false)
                {
                    this.ErrorMessage = this.sharedLocalizer.GetHtmlString(ErrorMessages.EmailNotConfirmed);
                    this.ModelState.AddModelError(string.Empty, ErrorMessages.EmailNotConfirmed);
                    return(this.Page());
                }

                if (result.RequiresTwoFactor)
                {
                    return(this.RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = this.Input.RememberMe }));
                }

                if (result.IsLockedOut)
                {
                    this.logger.LogWarning("User account locked out.");
                    return(this.RedirectToPage("./Lockout"));
                }
                else
                {
                    this.ErrorMessage = this.sharedLocalizer.GetHtmlString(ErrorMessages.InvalidLoginAttempt);
                    this.ModelState.AddModelError(string.Empty, ErrorMessages.InvalidLoginAttempt);
                    return(this.Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(this.Page());
        }
        public async Task <IActionResult> Exchange(OpenIdConnectRequest request)
        {
            if (request.IsPasswordGrantType())
            {
                ApplicationUser user = await _userManager.FindByEmailAsync(request.Username) ??
                                       await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "Please check that your email and password is correct"
                    }));
                }

                // Ensure the user is enabled.
                if (!user.IsEnabled)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user account is disabled"
                    }));
                }


                // Validate the username/password parameters and ensure the account is not locked out.
                SignInResult result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, true);

                // Ensure the user is not already locked out.
                if (result.IsLockedOut)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user account has been suspended"
                    }));
                }

                // Reject the token request if two-factor authentication has been enabled by the user.
                if (result.RequiresTwoFactor)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "Invalid login procedure"
                    }));
                }

                // Ensure the user is allowed to sign in.
                if (result.IsNotAllowed)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in"
                    }));
                }

                if (!result.Succeeded)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "Please check that your email and password is correct"
                    }));
                }


                // Create a new authentication ticket.
                AuthenticationTicket ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }
            if (request.IsRefreshTokenGrantType())
            {
                // Retrieve the claims principal stored in the refresh token.
                AuthenticateResult info = await HttpContext.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationScheme);

                // Retrieve the user profile corresponding to the refresh token.
                // Note: if you want to automatically invalidate the refresh token
                // when the user password/roles change, use the following line instead:
                // var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
                ApplicationUser user = await _userManager.GetUserAsync(info.Principal);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The refresh token is no longer valid"
                    }));
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The user is no longer allowed to sign in"
                    }));
                }

                // Create a new authentication ticket, but reuse the properties stored
                // in the refresh token, including the scopes originally granted.
                AuthenticationTicket ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }
            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported"
            }));
        }
示例#27
0
        public async Task <IActionResult> ExternalResponse(string returnURL = "/")
        {
            ExternalLoginInfo userInfo = await SignInManager.GetExternalLoginInfoAsync();

            if (userInfo == null)
            {
                return(RedirectToAction("LogIn"));
            }
            else
            {
                Microsoft.AspNetCore.Identity.SignInResult result = await SignInManager.ExternalLoginSignInAsync(userInfo.LoginProvider, userInfo.ProviderKey, true);

                if (result.Succeeded)
                {
                    //TODO EmailConfirm
                    return(Redirect(returnURL));
                }
                else
                {
                    string  externalUserName = userInfo.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
                    UserApp user             = new UserApp()
                    {
                        Email     = userInfo.Principal.FindFirst(ClaimTypes.Email).Value,
                        BirthDate = Convert.ToDateTime(userInfo.Principal.FindFirst(ClaimTypes.DateOfBirth)?.Value)
                    };
                    if (userInfo.Principal.HasClaim(c => c.Type == ClaimTypes.Name))
                    {
                        string userName = userInfo.Principal.FindFirst(ClaimTypes.Name).Value.Replace(" ", string.Empty).ToLower() + externalUserName.Substring(0, 5);
                        user.UserName = userName;
                    }
                    else
                    {
                        user.UserName = user.Email;
                    }

                    UserApp userApp = await GetUserByEmailAsync(user.Email);

                    if (userApp == null)
                    {
                        IdentityResult createResult = await UserManager.CreateAsync(user);

                        if (createResult.Succeeded)
                        {
                            IdentityResult loginResult = await UserManager.AddLoginAsync(user, userInfo);

                            if (loginResult.Succeeded)
                            {
                                //TODO EmailConfirm
                                await SignInManager.ExternalLoginSignInAsync(userInfo.LoginProvider, userInfo.ProviderKey, true);

                                return(Redirect(returnURL));
                            }
                            else
                            {
                                AddModelError(loginResult);
                            }
                        }
                        else
                        {
                            AddModelError(createResult);
                        }
                    }
                    else
                    {
                        IdentityResult loginResult = await UserManager.AddLoginAsync(userApp, userInfo);

                        if (loginResult.Succeeded)
                        {
                            //TODO EmailConfirm
                            await SignInManager.ExternalLoginSignInAsync(userInfo.LoginProvider, userInfo.ProviderKey, true);

                            return(Redirect(returnURL));
                        }
                        else
                        {
                            AddModelError(loginResult);
                        }
                    }
                }
            }
            List <string> errors = ModelState.Values.SelectMany(e => e.Errors).Select(r => r.ErrorMessage).ToList();

            return(View("Error", errors));
        }
        //[HttpPost, Route("login"), AllowAnonymous]
        ////public async Task<IActionResult> Login([FromBody]JObject jo)
        //public async Task<IActionResult> Login()
        //{
        //    Console.WriteLine("call login~. No Parameter");
        //    //foreach (string key in Response.Headers.Keys)
        //    //{
        //    //    Console.WriteLine($"{key} : {Response.Headers[key]}");
        //    //}
        //    //Response.Cookies.Append("babo", "you~");
        //    //if (jo == null)
        //    //    return NoContent();
        //    //return await ClaimsLogin(jo);
        //    return Ok();
        //}

        //private async Task<IActionResult> ClaimsLogin([FromBody]JObject jo)
        //{
        //    bool isUservalid = false;
        //    LoginViewModel user = JsonConvert.DeserializeObject<LoginViewModel>(jo.ToString());

        //    if (ModelState.IsValid && isUservalid)
        //    {
        //        var claims = new List<Claim>();

        //        claims.Add(new Claim(ClaimTypes.Name, user.Email));


        //        var identity = new ClaimsIdentity(
        //            claims, JwtBearerDefaults.AuthenticationScheme);

        //        var principal = new ClaimsPrincipal(identity);

        //        var props = new AuthenticationProperties();
        //        props.IsPersistent = user.RememberMe;

        //        HttpContext.SignInAsync(
        //            IdentityConstants.ApplicationScheme,
        //            principal, props).Wait();
        //        string token = JasonWebTokenManager.GenerateToken(user.Email);
        //        return Ok(new { Token = token });
        //    }
        //    else
        //    {
        //        return BadRequest();
        //    }
        //}

        private async Task <IActionResult> OldLogin([FromBody] LoginModel user)
        {
            //[FromBody]
            //JObject jo = null;
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(user.Email) || string.IsNullOrEmpty(user.Password))
                {
                    Console.WriteLine("Invalid User");
                    return(BadRequest());
                }

                UserAccountEF account = await _userManager.FindByEmailAsync(user.Email);

                if (account == null)
                {
                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).UserNotFound();
                    IdentityResult _result = IdentityResult.Failed(error);
                    return(BadRequest(new { Result = _result }));
                }
                else if (account.SignInConfirm == false)
                {
                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).SignInNotConfirm(user.Email);
                    IdentityResult _result = IdentityResult.Failed(error);
                    return(BadRequest(new { Result = _result }));
                }

                Microsoft.AspNetCore.Identity.SignInResult signResult = await _signInManager.PasswordSignInAsync(user.Email, user.Password, true, false);

                if (signResult.Succeeded)
                {
                    var accountUser = await _userManager.FindByEmailAsync(user.Email);

                    IList <Claim> claims = await _userManager.GetClaimsAsync(accountUser);

                    claims.Add(new Claim(ClaimTypes.NameIdentifier, accountUser.Id));
                    claims.Add(new Claim(ClaimTypes.Name, accountUser.FirstName + accountUser.LastName));

                    string roleType = "";
                    string id       = "";
                    if (accountUser.UserType == RegisterType.Aggregator)
                    {
                        roleType = UserRoleTypes.Aggregator;
                        var agg = _accountContext.VwAggregatorusers.FirstOrDefault(x => x.UserId == accountUser.Id);
                        id = agg.AggGroupId;
                        claims.Add(new Claim(UserClaimTypes.AggregatorGroupIdentifier, agg.AggGroupId));
                        //claims.Add(new Claim("", ))
                        claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Aggregator));
                        if (string.IsNullOrEmpty(agg.AggName) == false)
                        {
                            claims.Add(new Claim(UserClaimTypes.AggregatorGroupName, agg.AggName));
                        }
                    }
                    else if (accountUser.UserType == RegisterType.Contrator)
                    {
                        var contractor = _accountContext.VwContractorusers.FirstOrDefault(x => x.UserId == accountUser.Id);
                        id = accountUser.Id;
                        claims.Add(new Claim(UserClaimTypes.AggregatorGroupIdentifier, contractor.AggGroupId));
                        claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Contractor));
                        roleType = UserRoleTypes.Contractor;
                        if (string.IsNullOrEmpty(contractor.AggName) == false)
                        {
                            claims.Add(new Claim(UserClaimTypes.AggregatorGroupName, contractor.AggName));
                        }
                    }
                    else if (accountUser.UserType == RegisterType.Supervisor)
                    {
                        claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Supervisor));
                        roleType = UserRoleTypes.Supervisor;
                    }

                    var siteids = ControlHelper.GetAvaliableRccCodes(_accountContext, roleType, id);

                    claims.Add(new Claim(SiteIdsByRccClaim, siteids));

                    string token = JasonWebTokenManager.GenerateToken(user.Email, claims);

                    string result = JasonWebTokenManager.ValidateToken(user.Email, token, ClaimTypes.NameIdentifier);

                    //if (string.IsNullOrEmpty(returnUrl) == false)
                    //{
                    //    Console.WriteLine("returnurl:" + returnUrl);
                    //    return Redirect(returnUrl);
                    //}
                    Console.WriteLine("Log-in Success: " + user.Email);
                    return(Ok(new { Result = signResult, Token = token, User = accountUser }));
                }
                else
                {
                    Console.WriteLine($"Login Failed");
                    //if (signResult.RequiresTwoFactor)
                    //{
                    //    return RedirectToAction("act", new { ReturnUrl = returnUrl, RememberMe = user.RememberMe });
                    //}
                    if (signResult.IsLockedOut)
                    {
                        IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).UserLockoutEnabled();
                        IdentityResult _result = IdentityResult.Failed(error);
                        return(BadRequest(new { Result = _result }));
                    }
                    else
                    {
                        IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).PasswordMismatch();
                        IdentityResult _result = IdentityResult.Failed(error);
                        return(BadRequest(new { Result = _result }));
                    }
                }
            }
            else
            {
                Console.WriteLine("Invalid LoginViewModel");
                return(Ok(StatusCodes.Status406NotAcceptable));
            }
        }
示例#29
0
        public void ExternalLoginCallbackCallsExternalLoginSignInAsyncThrowsFailResult(string returnUrl, SignInResult signInResult)
        {
            // Arrange
            string remoteError = null;

            var externalLoginInfo = this.CreateFakeLoginData();

            this.signInManagerMock
            .Setup(x => x.GetExternalLoginInfoAsync(null))
            .Returns(Task.FromResult(externalLoginInfo));

            this.signInManagerMock
            .Setup(x => x.ExternalLoginSignInAsync(
                       externalLoginInfo.LoginProvider,
                       externalLoginInfo.ProviderKey,
                       false))
            .Returns(Task.FromResult(signInResult));

            Func <Task> task = () => controller.ExternalLoginCallback(returnUrl, remoteError);

            // Act
            var ex = Assert.ThrowsAsync <InvalidOperationException>(task);

            // Assert
            Assert.NotNull(ex);

            this.signInManagerMock.Verify(x => x.ExternalLoginSignInAsync(
                                              externalLoginInfo.LoginProvider,
                                              externalLoginInfo.ProviderKey,
                                              false), Times.Once);
        }
        public async Task <ActionResult> Register(RegisterViewModel rvm)
        {
            //if registration data is valid, create a new user on the database
            Console.WriteLine("RVM Age " + rvm.Age);

            if (rvm.Age < 18 && rvm.MakeEmployee == true)
            {
                ViewBag.BirthdayErrorMessage = "Employee must be at least 18 years old to create an account";
                return(View(rvm));
            }

            if (ModelState.IsValid && rvm.Age >= 13)
            {
                //this code maps the RegisterViewModel to the AppUser domain model
                AppUser newUser = new AppUser
                {
                    UserName    = rvm.Email,
                    Email       = rvm.Email,
                    PhoneNumber = rvm.PhoneNumber,

                    //TODO: Add the rest of the custom user fields here
                    //FirstName is included as an example
                    FirstName     = rvm.FirstName,
                    MiddleInitial = rvm.MiddleInitial,
                    LastName      = rvm.LastName,
                    Address       = rvm.Address,
                    City          = rvm.City,
                    State         = rvm.State,
                    Zip           = rvm.Zip,
                    Birthday      = rvm.Birthday,
                };

                //This code uses the UserManager object to create a new user with the specified password
                IdentityResult result = await _userManager.CreateAsync(newUser, rvm.Password);

                //If the add user operation was successful, we need to do a few more things
                if (result.Succeeded)
                {
                    if (rvm.MakeEmployee == true)
                    {
                        await _userManager.AddToRoleAsync(newUser, "Employee");
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(newUser, "Customer");
                    }
                    //TODO: Add user to desired role. This example adds the user to the customer role

                    //NOTE: This code logs the user into the account that they just created
                    //You may or may not want to log a user in directly after they register - check
                    //the business rules!
                    if (User.Identity.IsAuthenticated == false)
                    {
                        Microsoft.AspNetCore.Identity.SignInResult result2 = await _signInManager.PasswordSignInAsync(rvm.Email, rvm.Password, false, lockoutOnFailure : false);
                    }

                    // sets up and creates the confirmation email
                    String EmailBody = $"Your account information is the following:\nUsername/Email: {newUser.Email}\nName: {newUser.FirstName} {newUser.MiddleInitial} {newUser.LastName}";
                    Utilities.Email.SendEmail(newUser.Email, "Your account has been created", EmailBody);

                    //Send the user to the home page
                    return(RedirectToAction("Index", "Home"));
                }
                else  //the add user operation didn't work, and we need to show an error message
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }

            if (rvm.Age < 13)
            {
                ViewBag.BirthdayErrorMessage = "You must be at least 13 years old to create an account";
            }
            //this is the sad path - something went wrong,
            //return the user to the register page to try again
            return(View(rvm));
        }