Beispiel #1
0
        public async Task <bool> LoginFailed(string userId)
        {
            int            failedLoginCount = _userManager.MaxFailedAccessAttemptsBeforeLockout = 3;
            IdentityResult accessFailed     = await _userManager.AccessFailedAsync(userId);

            return(accessFailed.Succeeded);
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            else
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                var role = UserManager.GetRoles(user.Id);

                var Iscredential = await UserManager.FindAsync(model.Email, model.Password);

                if (user != null)
                {
                    if (await UserManager.IsLockedOutAsync(user.Id))
                    {
                        ModelState.AddModelError("", string.Format("Account has been lock out for {0} minute", 5));
                    }
                    else if (await UserManager.GetLockoutEnabledAsync(user.Id) && Iscredential == null)
                    {
                        await UserManager.AccessFailedAsync(user.Id);

                        string message;
                        if (await UserManager.IsLockedOutAsync(user.Id))
                        {
                            message = string.Format("Account has been lock out for {0} minute", 5);
                        }
                        else
                        {
                            int accessFailedCount = await UserManager.GetAccessFailedCountAsync(user.Id);

                            int attempleft = 3 - accessFailedCount;
                            message = string.Format(" Invalid Credential Try Again");
                        }
                        ModelState.AddModelError("", message);
                    }
                    else if (Iscredential == null)
                    {
                        ModelState.AddModelError("", string.Format(" Invalid Credential Try Again"));
                    }
                    else
                    {
                        await SignInManager.SignInAsync(user, true, model.RememberMe);

                        await UserManager.ResetAccessFailedCountAsync(user.Id);

                        return(RedirectToLocal(returnUrl));
                    }
                }
            }
            return(View(model));


            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
        }
Beispiel #3
0
        public async Task <IActionResult> Exchange()
        {
            var request = HttpContext.GetOpenIdConnectRequest();

            if (request.IsPasswordGrantType())
            {
                var user = await usermanager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                // Ensure the password is valid.
                if (!await usermanager.CheckPasswordAsync(user, request.Password))
                {
                    if (usermanager.SupportsUserLockout)
                    {
                        await usermanager.AccessFailedAsync(user);
                    }

                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                if (usermanager.SupportsUserLockout)
                {
                    await usermanager.ResetAccessFailedCountAsync(user);
                }

                var identity = await usermanager.CreateIdentityAsync(user, request.GetScopes());

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    OpenIdConnectServerDefaults.AuthenticationScheme);

                ticket.SetResources(request.GetResources());
                ticket.SetScopes(request.GetScopes());

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            }));
        }
        public async Task <Tuple <bool, string[]> > LoginAsync(UserDTO user)
        {
            var existingUser = _appUserManager.FindByNameAsync(user.UserName).Result;

            List <string> errorList = new List <string>();

            string[] errors = new string[1];

            if (existingUser == null)
            {
                //return invalid user name or password
                errorList.Add("Invalid user name or password");
                return(Tuple.Create(false, errorList.ToArray()));
            }

            if (!existingUser.ActiveStatus)
            {
                //return user disabled
                errorList.Add("User disabled");
                return(Tuple.Create(false, errorList.ToArray()));
            }

            //can sign in part
            //  bool b = _appUserManager.GetLockoutEnabledAsync(existingUser.Id).Result;

            if (_appUserManager.SupportsUserLockout && _appUserManager.IsLockedOutAsync(existingUser.Id).Result)
            {
                //return user locked out
                errorList.Add("User locked");
                return(Tuple.Create(false, errorList.ToArray()));
            }


            //checks the password
            if (!_appUserManager.CheckPasswordAsync(existingUser, user.Password).Result)
            {
                if (_appUserManager.SupportsUserLockout)
                {
                    await _appUserManager.AccessFailedAsync(existingUser.Id); // updates the access fail count
                }

                errorList.Add("User name or password invalid");
                return(Tuple.Create(false, errorList.ToArray()));
            }

            if (_appUserManager.SupportsUserLockout)
            {
                await _appUserManager.ResetAccessFailedCountAsync(existingUser.Id);
            }

            errorList.Add(existingUser.Id);
            return(Tuple.Create(true, errorList.ToArray()));
        }
        public async Task <IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (!User.Identity.IsAuthenticated && string.IsNullOrEmpty(model.Email))
            {
                return(BadRequest("No username or bearer token provided"));
            }

            string userId;

            if (User.Identity.IsAuthenticated)
            {
                userId = User.Identity.GetUserId();
            }
            else
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (await UserManager.IsLockedOutAsync(user.Id))
                {
                    return(BadRequest("The user name or password is incorrect."));
                }

                var validCredentials = await UserManager.FindAsync(user.UserName, model.OldPassword);

                if (validCredentials == null)
                {
                    // increment failed login attempt
                    if (await UserManager.GetLockoutEnabledAsync(user.Id))
                    {
                        await UserManager.AccessFailedAsync(user.Id);
                    }
                    return(BadRequest("The user name or password is incorrect."));
                }

                userId = user.Id;
            }
            IdentityResult result = await UserManager.ChangePasswordAsync(userId, model.OldPassword,
                                                                          model.NewPassword);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Beispiel #6
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            var user = await UserManager.FindByNameAsync(model.Email);

            switch (result)
            {
            case SignInStatus.Success:
                // When token is verified correctly, clear the access failed count used for lockout
                await UserManager.ResetAccessFailedCountAsync(user.Id);

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                if (user != null)
                {
                    await UserManager.AccessFailedAsync(user.Id);    // Record the failure

                    if (await UserManager.IsLockedOutAsync(user.Id))
                    {
                        ModelState.AddModelError("", "Your account has been locked out for 5 minutes due to multiple failed login attempts.");
                    }
                    else
                    {
                        int accessFailedCount = await UserManager.GetAccessFailedCountAsync(user.Id);

                        string attemptsLeft = (5 - accessFailedCount).ToString();
                        ModelState.AddModelError("", "You have " + attemptsLeft + " more attempt(s) before your account gets locked out.");
                    }
                }
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // これは、アカウント ロックアウトの基準となるログイン失敗回数を数えません。
            // パスワード入力失敗回数に基づいてアカウントがロックアウトされるように設定するには、shouldLockout: true に変更してください。
            var user = await UserManager.FindByUserNameOrEmailAsync(model.EmailOrUserName, model.Password);
            if (user != null)
            {
                if (await UserManager.IsLockedOutAsync(user.Id))
                {
                    ModelState.AddModelError("", "アカウントはロックされています。しばらくしてからアクセスしてください。");
                    return View(model);
                }

                // パスワードが正しい場合はリトライをクリア
                await UserManager.ResetAccessFailedCountAsync(user.Id);

                AuthenticationManager.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, 
                    await user.GenerateUserIdentityAsync(UserManager));
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // パスワード抜きで取得しなおす
                user = await UserManager.FindByUserNameOrEmailAsync(model.EmailOrUserName);
                if (user != null)
                {
                    await UserManager.SetLockoutEnabledAsync(user.Id, true);
                    await UserManager.AccessFailedAsync(user.Id);

                    // アカウントをロック
                    if (await UserManager.IsLockedOutAsync(user.Id))
                    {
                        ModelState.AddModelError("", "ログインの失敗の上限回数を超過したため、アカウントをロックしました。しばらくしてからアクセスしてください。");
                        return View(model);
                    }
                }

                ModelState.AddModelError("", "ユーザー名またはパスワードが無効です。");
            }

            return View(model);
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var flag = false;

                var user = await UserManager.FindByNameAsync(model.Email);

                if (user != null)
                {
                    if (await UserManager.IsLockedOutAsync(user.Id))
                    {
                        ModelState.AddModelError("", "アカウントがロックアウトされています。");
                        return(View(model));
                    }

                    if (await UserManager.CheckPasswordAsync(user, model.Password))
                    {
                        flag = true;
                    }
                    else
                    {
                        await UserManager.AccessFailedAsync(user.Id);
                    }
                }

                if (flag)
                {
                    await SignInAsync(user, model.RememberMe);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("", "ユーザー名またはパスワードが無効です。");
                }
            }

            return(View(model));
        }
Beispiel #9
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindAsync(model.UserName, model.Password);

                if (user != null)
                {
                    if (user.LockoutEnabled)
                    {
                        ModelState.AddModelError("", "Invalid username or password Blocked.");
                    }
                    else
                    {
                        await SignInAsync(user, model.RememberMe);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                else
                {
                    try
                    {
                        user = await _userManager.FindByNameAsync(model.UserName);

                        IdentityResult x = await _userManager.AccessFailedAsync(user.Id);

                        ModelState.AddModelError("", "Invalid username or password.");
                    }
                    catch (Exception e)
                    {
                        returnUrl = e.Message;
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        /// <summary>
        /// oAuth Resource Password Login Flow
        /// 1. Checks the password with the Identity API
        /// 2. Create a user identity for the bearer token
        /// 3. Create a user identity for the cookie
        /// 4. Calls the context.Validated(ticket) to tell the oAuth2 server to protect the ticket as an access token and send it out in JSON payload
        /// 5. Signs the cookie identity so it can send the authentication cookie
        /// </summary>
        /// <param name="context">The authorization context</param>
        /// <returns>Task</returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (ApplicationUserManager userManager = _userManagerFactory())
            {
                userManager.MaxFailedAccessAttemptsBeforeLockout = 5;
                userManager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);

                UserProfile user = await userManager.FindByNameAsync(context.UserName);

                if (user == null)
                {
                    context.SetError("invalid_grant", "Invalid username");
                    return;
                }

                if (await userManager.IsLockedOutAsync(user.Id))
                {
                    var timeleft = user.LockoutEndDateUtc.GetValueOrDefault().Subtract(DateTime.UtcNow);

                    var timetype  = timeleft.Minutes == 0 ? "seconds" : "minute(s)";
                    var timevalue = timeleft.Minutes == 0 ? timeleft.Seconds : timeleft.Minutes;

                    context.SetError("invalid_grant", string.Format("Your account is locked for {0} more {1}", timevalue, timetype));
                    return;
                }

                if (!(await userManager.CheckPasswordAsync(user, context.Password)))
                {
                    await userManager.AccessFailedAsync(user.Id);

                    if (await userManager.IsLockedOutAsync(user.Id))
                    {
                        context.SetError("invalid_grant", string.Format("Your account has been locked for {0} minutes", userManager.DefaultAccountLockoutTimeSpan.Minutes));
                        return;
                    }

                    var possibleAttempts = userManager.MaxFailedAccessAttemptsBeforeLockout;
                    var currentcount     = await userManager.GetAccessFailedCountAsync(user.Id);

                    context.SetError("invalid_grant", string.Format("Invalid password. Your account will be locked after {0} more failed attempts.", possibleAttempts - currentcount));
                    return;
                }


                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                                                                                     context.Options.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                                                                                       CookieAuthenticationDefaults.AuthenticationType);

                var justCreatedIdentity = await userManager.FindByNameAsync(user.UserName);

                var roles = await userManager.GetRolesAsync(justCreatedIdentity.Id);

                AuthenticationProperties properties = CreateProperties(user.UserName, roles.ToArray(), user.EmailConfirmed);
                AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                // find user by username first
                var user = await UserManager.FindByNameAsync(model.username);

                IList <string> role = await UserManager.GetRolesAsync(user.Id);


                if (user != null)
                {
                    var validCredentials = await UserManager.FindAsync(model.username, 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 UserManager.IsLockedOutAsync(user.Id))
                    {
                        if (user.ban == true)
                        {
                            ModelState.AddModelError("", string.Format("Your account has been locked out for 3 days due to ban by the administrator"));
                        }
                        else if (UserManager.MaxFailedAccessAttemptsBeforeLockout >= 3)
                        {
                            ModelState.AddModelError("", string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString()));
                        }
                    }
                    // 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 UserManager.GetLockoutEnabledAsync(user.Id) && validCredentials == null)
                    {
                        // Record the failure which also may cause the user to be locked out
                        await UserManager.AccessFailedAsync(user.Id);

                        string message;

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

                            int attemptsLeft =
                                Convert.ToInt32(
                                    ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"].ToString()) -
                                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 == null)
                    {
                        ModelState.AddModelError("", "Invalid credentials. Please try again.");
                    }
                    else
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        // When token is verified correctly, clear the access failed count used for lockout
                        await UserManager.ResetAccessFailedCountAsync(user.Id);

                        var usr = await user.GenerateUserIdentityAsync(UserManager);

                        if (usr.IsAuthenticated)
                        {
                            //Role Member
                            if (role[0] == "Member")
                            {
                                return(RedirectToAction("About", "Home"));
                            }
                            else //Role Admin
                            if (role[0] == "Administrator")
                            {
                                return(RedirectToAction("Index", "Admin"));
                            }
                            else if (role[0] == "Event_Organizer")
                            {
                                return(RedirectToAction("Index", "Admin"));
                            }
                            else
                            {
                                return(RedirectToAction("Error", "Home"));
                            }
                        }
                        else
                        {
                            return(RedirectToAction("Error", "Home"));
                        }
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <UserViewModel> Authenticate(string username, string password)
        {
            try
            {
                string message = null;
                User   user    = await this.UserManager.FindByNameAsync(username);

                if (user != null)
                {
                    var tempUser = await UserManager.FindAsync(username, password);

                    UserViewModel validCredentials = null;

                    if (tempUser != null)
                    {
                        validCredentials = new UserViewModel(tempUser);
                    }


                    //account can be locked by administrator
                    if (user.PermanentLock)
                    {
                        message = "This account has been locked.";
                        throw new ValidationException(message);
                    }


                    // When user is locked, 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 UserManager.IsLockedOutAsync(user.Id))
                    {
                        message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ((int)(user.LockoutEndDateUtc.Value - DateTime.UtcNow).TotalMinutes).ToString());
                        throw new ValidationException(message);
                    }

                    // 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 UserManager.GetLockoutEnabledAsync(user.Id) && validCredentials == null)
                    {
                        // Record the failure which also may cause the user to be locked out
                        await UserManager.AccessFailedAsync(user.Id);

                        if (await UserManager.IsLockedOutAsync(user.Id))
                        {
                            message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", Config.DefaultAccountLockoutTimeSpan.ToString());
                        }
                        else
                        {
                            int accessFailedCount = await UserManager.GetAccessFailedCountAsync(user.Id);

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

                        throw new ValidationException(message);
                    }
                    else if (validCredentials == null)
                    {
                        throw new ValidationException("Invalid credentials. Please try again.");
                    }

                    // All is ok
                    await UserManager.ResetAccessFailedCountAsync(validCredentials.Id);

                    return(validCredentials); // Return user object
                }
                else
                {
                    throw new ValidationException("Invalid username !");
                }
            }
            catch (ValidationException exe)
            {
                throw exe;
            }
            catch (Exception e)
            {
                await LogError("Authenticate", e);

                Trace.TraceError(string.Format("Authenticate in account service error: {0}", e.Message));
                throw e;
            }
        }
        public async Task <IActionResult> OnPost()
        {
            using var logContext = LogContext.PushProperty("UserIdentifier", UserIdentifier);

            if (!ModelState.IsValid)
            {
                _logger.Verbose("Invalid {@Input}", ModelState.Values);
                return(Page());
            }

            var context = await _interactionService.GetAuthorizationContextAsync(ReturnUrl);

            if (context == null)
            {
                _logger.Verbose("ReturnUrl invalid, cannot find authorization context", ModelState.Values);
                ModelState.AddModelError("Unauthorized", "Unauthorized");
                return(Page());
            }

            var    existingUser = (await _userManager.FindAllByAnyIdentifierAsync(UserIdentifier)).SingleOrDefault();
            string otpCode;

            if (existingUser == null)
            {
                _logger.Information("User not exists, trying to authenticate for registration", ModelState.Values);
                ModelState.AddModelError("Unauthorized", "Unauthorized");
                return(Page());
            }

            using var l1 = LogContext.PushProperty("UserMobile", existingUser.MobileNumber);
            using var l2 = LogContext.PushProperty("UserEmail", existingUser.Email);
            using var l3 = LogContext.PushProperty("Username", existingUser.UserName);
            var isUserLockedOut = await _userManager.IsLockedOutAsync(existingUser);

            if (isUserLockedOut)
            {
                _logger.Information("{@User} locked-out prior to anomaly", existingUser);
                await _eventService.RaiseAsync(new UserLoginFailureEvent(existingUser.UserName, "account locked-out",
                                                                         clientId : context?.Client.ClientId));

                await _userManager.AccessFailedAsync(existingUser);

                ModelState.AddModelError("Unauthorized", "Unauthorized");
                return(Page());
            }

            var isUserLogonEnabled = await _userManager.IsUserLogonEnabledAsync(existingUser);

            if (!isUserLogonEnabled)
            {
                _logger.Information("{@User} logon is not enabled", existingUser);
                await _eventService.RaiseAsync(new UserLoginFailureEvent(existingUser.UserName,
                                                                         "account logon not enabled", clientId : context?.Client.ClientId));

                await _userManager.AccessFailedAsync(existingUser);

                ModelState.AddModelError("Unauthorized", "Unauthorized");
                return(Page());
            }

            var isValidPassword = await _userManager.CheckPasswordAsync(existingUser, Password);

            if (!isValidPassword)
            {
                _logger.Information("{@User} entered invalid password", existingUser);
                await _eventService.RaiseAsync(new UserLoginFailureEvent(existingUser.UserName, "invalid credentials",
                                                                         clientId : context?.Client.ClientId));

                await _userManager.AccessFailedAsync(existingUser);

                ModelState.AddModelError("Unauthorized", "Unauthorized");
                return(Page());
            }

            await _signinManager.SignIn(existingUser, context.Client.ClientId);

            return(Redirect(ReturnUrl));
        }
Beispiel #14
0
        public async Task <ResultModel <AuthenticateModel> > Login([FromBody] JObject Body)
        {
            string Username = Body["Username"].ToString();
            string Password = Body["Password"].ToString();

            ApplicationUserManager UserManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationUser        User        = await UserManager.FindByNameAsync(Username);

            // Check Lockout
            if (User != null && UserManager.SupportsUserLockout && UserManager.IsLockedOut(User.Id))
            {
                return new ResultModel <AuthenticateModel>()
                       {
                           ResultCode = HttpStatusCode.Forbidden.GetHashCode(),
                           Message    = $"{User.UserName} has been suspended.",
                           Result     = null
                       }
            }
            ;

            // LDAP Authentication
            try
            {
                DirectoryEntry de = new DirectoryEntry(CurrentDomainPath, Username, Password);

                DirectorySearcher dsearch = new DirectorySearcher(de);
                SearchResult      res     = null;
                dsearch.PageSize = 100000;
                res = dsearch.FindOne();
            }
            catch
            {
                if (User != null && UserManager.SupportsUserLockout)
                {
                    await UserManager.AccessFailedAsync(User.Id);
                }
                return(new ResultModel <AuthenticateModel>()
                {
                    ResultCode = HttpStatusCode.Unauthorized.GetHashCode(),
                    Message = $"No User",
                    Result = new AuthenticateModel()
                    {
                        AccessToken = ""
                    }
                });
            }

            // Register if null
            if (User == null)
            {
                User = new ApplicationUser()
                {
                    UserName = Username,
                    JoinDate = DateTime.UtcNow
                };
                IdentityResult Result = await UserManager.CreateAsync(User, Password);
            }
            else
            {
                //string ResetToken = await UserManager.GeneratePasswordResetTokenAsync(User.Id);
                //var x = await UserManager.ResetPasswordAsync(User.Id, ResetToken, Password);
                User.PasswordHash = UserManager.PasswordHasher.HashPassword(Password);
                var x = await UserManager.UpdateAsync(User);
            }

            //// Check Lockout Enable?
            //if (UserManager.SupportsUserLockout)
            //{
            //    // Check Password Correct?
            //    if (await UserManager.CheckPasswordAsync(User, Password)) await UserManager.ResetAccessFailedCountAsync(User.Id);
            //    else
            //    {
            //        await UserManager.AccessFailedAsync(User.Id);
            //        return new ResultModel<AuthenticateModel>()
            //        {
            //            ResultCode = HttpStatusCode.Unauthorized.GetHashCode(),
            //            Message = $"Username or Password is incorrect.",
            //            Result = new AuthenticateModel()
            //            {
            //                UserCode = "",
            //                AccessToken = ""
            //            }
            //        };
            //    }
            //}

            // Get Token
            TokenResponseModel TokenRes = new TokenResponseModel();

            using (var client = new HttpClient())
            {
                var values = new Dictionary <string, string>()
                {
                    { "grant_type", "password" },
                    { "username", Username },
                    { "password", Password }
                };
                var BodyParam = new FormUrlEncodedContent(values);
                client.BaseAddress = new Uri("https://gpscweb.pttgrp.com");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                // Post for Token
                try
                {
                    var response = await client.PostAsync("GPSC-Plant-monitoring-API/token", BodyParam);

                    if (response.IsSuccessStatusCode)
                    {
                        string outputJson = await response.Content.ReadAsStringAsync();

                        TokenRes = JsonConvert.DeserializeObject <TokenResponseModel>(outputJson);
                    }
                }
                catch
                {
                    return(new ResultModel <AuthenticateModel>()
                    {
                        ResultCode = HttpStatusCode.Unauthorized.GetHashCode(),
                        Message = $"Authorization Fail.",
                        Result = new AuthenticateModel()
                        {
                            AccessToken = ""
                        }
                    });
                }
            }

            return(new ResultModel <AuthenticateModel>()
            {
                ResultCode = HttpStatusCode.OK.GetHashCode(),
                Message = "",
                Result = new AuthenticateModel()
                {
                    AccessToken = TokenRes.access_token
                }
            });
        }
    }
Beispiel #15
0
        //[ValidateAntiForgeryToken]
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var userName = model.Email;
                Advisr.Domain.DbModels.ApplicationUser user = null;
                using (IUnitOfWork unitOfWork = UnitOfWork.Create())
                {
                    //Get user
                    user = unitOfWork.UserRepository.GetAll().FirstOrDefault(a => a.Email == model.Email || a.UserName == model.Email);

                    if (user != null)
                    {
                        string message = null;
                        userName = user.UserName;

                        if ((await UserManager.IsEmailConfirmedAsync(user.Id)) == false)
                        {
                            message = "Email not confirmed, please check your inbox to confirm the email.";
                        }
                        else
                        {
                            await UserManager.SetLockoutEnabledAsync(user.Id, true);

                            var validCredentials = await UserManager.FindAsync(userName, 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 UserManager.IsLockedOutAsync(user.Id))
                            {
                                message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts. **", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString());
                            }

                            // 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 UserManager.GetLockoutEnabledAsync(user.Id) && validCredentials == null)
                            {
                                // Record the failure which also may cause the user to be locked out
                                await UserManager.AccessFailedAsync(user.Id);

                                if (await UserManager.IsLockedOutAsync(user.Id))
                                {
                                    message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts. **", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString());
                                }
                                else
                                {
                                    int accessFailedCount = await UserManager.GetAccessFailedCountAsync(user.Id);

                                    int attemptsLeft = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"].ToString()) - accessFailedCount;

                                    message = string.Format("Invalid credentials. You have {0} more attempt(s) before your account gets locked out.", attemptsLeft);
                                }
                            }
                            else if (validCredentials == null)
                            {
                                message = "Invalid login attempt **";
                            }
                            else
                            {
                                if (user.LockedByAdmin)
                                {
                                    message = "Your account has been locked by admin.";
                                    return(JsonError(HttpStatusCode.BadRequest, 10, message, ModelState));
                                }

                                if ((await SignInManager.PasswordSignInAsync(userName, model.Password, model.RememberMe, shouldLockout: false)) != SignInStatus.Success)
                                {
                                    message = "Invalid login attempt **";
                                }
                                else
                                {
                                    // When token is verified correctly, clear the access failed count used for lockout
                                    await UserManager.ResetAccessFailedCountAsync(user.Id);

                                    var customer = unitOfWork.CustomerDetailsRepository.GetAll().FirstOrDefault(a => a.UserId == user.Id);

                                    if (user.AutopilotTrack && !string.IsNullOrEmpty(user.AutopilotContactId))
                                    {
                                        StartUpdatingAutopilot(customer.User.AutopilotContactId, customer.UserId);
                                    }

                                    var redirectUrl = Url.Action("Index", "Dashboard", new { }, protocol: Request.Url.Scheme);

                                    if (returnUrl != null && returnUrl != "empty")
                                    {
                                        redirectUrl = returnUrl;
                                    }

                                    if (customer != null && customer.Status == Domain.DbModels.CustomerStatus.Pending)
                                    {
                                        redirectUrl = string.Format("{0}/Dashboard/#/user/profile", Request.Url.GetLeftPart(UriPartial.Authority));
                                    }

                                    var resultJson = new
                                    {
                                        success = true,
                                        user    = new
                                        {
                                            id        = user.Id,
                                            firstName = user.FirstName,
                                            lastName  = user.LastName
                                        },
                                        redirectUrl = redirectUrl
                                    };

                                    return(Json(resultJson));
                                }
                            }
                        }

                        ModelState.AddModelError("validationInfo", message);

                        return(JsonError(HttpStatusCode.BadRequest, 10, "Warning", ModelState));
                    }
                    else
                    {
                        ModelState.AddModelError("validationInfo", "Invalid login attempt **");

                        return(JsonError(HttpStatusCode.BadRequest, 10, "Warning", ModelState));
                    }
                }
            }
            else
            {
                return(JsonError(HttpStatusCode.BadRequest, 10, "Warning", ModelState));
            }
        }
Beispiel #16
0
 public async Task AccessFailedAsync(string userId)
 {
     await _userManager.AccessFailedAsync(userId);
 }
Beispiel #17
0
        public async Task <IHttpActionResult> LogIn(LoginBindingModel model)
        {
            try
            {
                _logger.Debug("ini LogIn - process");

                if (ModelState.IsValid)
                {
                    User user = await _appUserManager.FindByEmailAsync(model.Email);

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

                        var validCredentials = await _appUserManager.FindAsync(user.UserName, 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 _appUserManager.IsLockedOutAsync(user.Id))
                        {
                            ModelState.AddModelError("", string.Format(
                                                         "Your account has been locked out for {0} minutes due to multiple failed login attempts.",
                                                         ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"]));
                        }
                        // 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 _appUserManager.GetLockoutEnabledAsync(user.Id) && validCredentials == null)
                        {
                            // Record the failure which also may cause the user to be locked out
                            await _appUserManager.AccessFailedAsync(user.Id);

                            string message;

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

                                int attemptsLeft =
                                    Convert.ToInt32(
                                        ConfigurationManager.AppSettings["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 == null)
                        {
                            ModelState.AddModelError("", "Invalid credentials. Please try again.");
                        }
                        else
                        {
                            await _appUserManager.ResetAccessFailedCountAsync(user.Id);

                            var signInStatus = await _appSignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, false);

                            switch (signInStatus)
                            {
                            case SignInStatus.Success:
                            {
                                _logger.Debug("LogIn - Success");
                                _logger.Debug(string.Format("user LogIn info email:{0}, idUser:{1}", user.Email, user.Id));
                                return(Ok(ModelFactory.Create(user)));
                            }

                            case SignInStatus.Failure:
                            {
                                _logger.Debug("LogIn - Invalid password");
                                ModelState.AddModelError("", "Invalid credentials. Please try again");
                                break;
                            }
                            }
                        }
                    }
                    else
                    {
                        _logger.Debug("LogIn - invalid email.");
                        ModelState.AddModelError("", "Invalid credentials. Please try again");
                    }
                }

                _logger.Debug("LogIn - BadRequest.");
                return(BadRequest(ModelState));
            }
            catch (Exception ex)
            {
                LogError(ex);
                return(InternalServerError(ex));
            }
        }
Beispiel #18
0
        public async Task <IActionResult> OnPost()
        {
            _logger.Verbose("Trying to authenticate user partially");
            var authResult = await HttpContext.AuthenticateAsync(Core.Constants.PartialAuthenticationSchemeName);

            var authUser = authResult.Principal;

            if (!authResult.Succeeded ||
                authResult.Ticket.AuthenticationScheme != Core.Constants.PartialAuthenticationSchemeName)
            {
                _logger.Information("Cannot authenticate user {@Result}", authResult);
                return(Unauthorized());
            }

            var mobileNumber = authUser.FindFirstValue(Core.Constants.Claims.MobileNumber);

            using var logContext2 = LogContext.PushProperty("MobileNumber", mobileNumber);

            var context = await _interactionService.GetAuthorizationContextAsync(ReturnUrl);

            if (context == null)
            {
                _logger.Verbose("ReturnUrl invalid, cannot find authorization context", ModelState.Values);
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                _logger.Verbose("Invalid {@Input}", ModelState.Values);
                return(BadRequest(ModelState));
            }

            var existingUser = await _userManager.FindByNameAsync(authUser.Identity.Name);

            if (existingUser == null)
            {
                _logger.Warning("Invalid user, cannot find user");
                return(BadRequest());
            }

            if (existingUser.MobileNumber != mobileNumber)
            {
                _logger.Warning("Selected {@User} does not belong to mobile number", existingUser);
                return(BadRequest());
            }

            var isUserLockedOut = await _userManager.IsLockedOutAsync(existingUser);

            if (isUserLockedOut)
            {
                _logger.Information("{@User} locked-out prior to anomaly", existingUser);
                await _eventService.RaiseAsync(new UserLoginFailureEvent(mobileNumber, "account locked-out",
                                                                         clientId : context?.Client.ClientId));

                await _userManager.AccessFailedAsync(existingUser);

                return(Unauthorized());
            }

            var isUserLogonEnabled = await _userManager.IsUserLogonEnabledAsync(existingUser);

            if (!isUserLogonEnabled)
            {
                _logger.Information("{@User} logon is not enabled", existingUser);
                await _eventService.RaiseAsync(new UserLoginFailureEvent(mobileNumber, "account logon not enabled",
                                                                         clientId : context?.Client.ClientId));

                await _userManager.AccessFailedAsync(existingUser);

                return(Unauthorized());
            }

            await _signinManager.SignIn(existingUser, context.Client.ClientId);

            return(Redirect(ReturnUrl));
        }