Exemplo n.º 1
0
        public AuthenticationDataDto SignIn(string username, string password, bool sessionBased, ref ValidationStateDictionary states)
        {
            ValidationState v = new ValidationState();

            if (string.IsNullOrEmpty(username))
            {
                v.Errors.Add(new ValidationError("Username.UsernameRequiredError", username, "Username is not set."));
            }
            if (string.IsNullOrEmpty(password))
            {
                v.Errors.Add(new ValidationError("Password.PasswordRequiredError", password, "Password is not set"));
            }

            if (v.Errors.Count > 0)
            {
                states.Add(typeof(LogInDto), v);
                return(new AuthenticationDataDto()
                {
                    AppAuthenticationFailed = true
                });
            }

            var userObject = repositoryInstance.GetUser(username);

            if (userObject == null)
            {
                v.Errors.Add(new ValidationError("Password.InvalidUsername", username, "Invalid Username or Password"));
                states.Add(typeof(LogInDto), v);
                return(null);
            }

            string lastLogin = userObject.LastLogInDate.HasValue ?
                               userObject.LastLogInDate.Value.ToString("dd-MM-yyyy HH:mm:ss")
                : Helper.GetLocalDate().ToString("dd-MM-yyyy HH:mm:ss");

            cacheService.AddAndTieToSession(string.Format("UserLastLogIn-{0}", userObject.Username), lastLogin);

            var roleID = GetRoleList().Where(f => f.RoleName == Constants.General.AdministratorRoleName).Select(r => r.RoleId).FirstOrDefault();

            if (!IsBusinessHour())
            {
                //allow administrator log in outside business hours.
                if (roleID != userObject.RoleId)
                {
                    v.Errors.Add(new ValidationError("User.NonBusinessHoursLoginError", username, "Login outside business hours is not allowed, Please try logging in during business hours."));
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            //Check if account is not locked,is approved and not deleted.
            if ((userObject.ApprovalStatus != Constants.ApprovalStatus.Approved) || userObject.IsLockedOut || userObject.IsDeleted)
            {
                v.Errors.Add(new ValidationError("Username.AccountLocked", username, "This account is inactive, has been locked or has been Deleted."));
                states.Add(typeof(LogInDto), v);

                return(new AuthenticationDataDto()
                {
                    AppAuthenticationFailed = true
                });
            }

            //check if user is Dormented.
            if (userObject.LastLogInDate == null)
            {
                //exclude administrator account from being dormant
                if (roleID != userObject.RoleId)
                {
                    int dormentNumberOfDays = NewUserIDDormentNumberDays();
                    if ((Helper.GetLocalDate() - (DateTime)userObject.CreationDate).Days >= dormentNumberOfDays)
                    {
                        UpdateUserDetails(userObject, isDorment: true);
                        v.Errors.Add(new ValidationError("Username.AccountDormented", username, "This account is Dormant as user has not logged for " + dormentNumberOfDays + " days from the day of account creation. Please contact the administrator."));
                        states.Add(typeof(LogInDto), v);
                        return(new AuthenticationDataDto()
                        {
                            AppAuthenticationFailed = true
                        });
                    }
                }
            }

            //prevent multi terminal login
            if (userObject.IsOnline)
            {
                var settings    = SecurityConfig.GetCurrent();
                var timeOutDate = Helper.GetLocalDate().AddMinutes(settings.Cookie.Timeout * -1);
                if (userObject.LastActivityDate.HasValue && userObject.LastActivityDate.Value >= timeOutDate)
                {
                    v.Errors.Add(new ValidationError("Username.MultiTeminalLogin", username, "You are currently logged in on another terminal. Kindly log out there and retry."));
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            //if last log in date/last activity date more than 90 days ago, refuse log in and lock the account
            if (userObject.LastLogInDate.HasValue && userObject.LastLogInDate.Value.Date < Helper.GetLocalDate().AddDays(ActiveUserIDDormentNumberDays()))
            {
                //exclude administrator account from being dormant
                if (roleID != userObject.RoleId)
                {
                    repositoryInstance.UpdateBadPasswordCount(username, true);
                    UpdateUserDetails(userObject, isDorment: true);
                    v.Errors.Add(new ValidationError("Username.AccountDormented", username, "This account is Dormant. Please contact the administrator."));
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            //Check if the Account is Expired
            if (userObject.AccountExpiryDate != null)
            {
                if (userObject.AccountExpiryDate < DateTime.Now)
                {
                    //exclude administrator account from expiring
                    if (roleID != userObject.RoleId)
                    {
                        UpdateUserDetails(userObject, isAccountExpired: true);
                        v.Errors.Add(new ValidationError("Username.AccountExpired", username, "This account is Expired. Please contact the administrator."));
                        states.Add(typeof(LogInDto), v);
                        return(new AuthenticationDataDto()
                        {
                            AppAuthenticationFailed = true
                        });
                    }
                }
            }

            if (userObject.Password != "Dummy" && (userObject.AccountType == Constants.AccountType.LocalLocal || userObject.AccountType == Constants.AccountType.LocalFinacle))
            {
                //check the password match
                if (userObject.Password != password)
                {
                    //v.Errors.Add(new ValidationError("Username.InvalidUsername", username, "Invalid Username or Password"));
                    v.Errors.Add(new ValidationError("Password.InvalidPassword", password, "Invalid Username or Password"));
                    var settings    = SecurityConfig.GetCurrent();
                    var lockAccount = userObject.BadPasswordCount + 1 >= settings.Cookie.MaximumPasswordRetries;
                    repositoryInstance.UpdateBadPasswordCount(username, lockAccount);
                    states.Add(typeof(LogInDto), v);
                    return(new AuthenticationDataDto()
                    {
                        AppAuthenticationFailed = true
                    });
                }
            }

            AuthenticationDataDto auth = new AuthenticationDataDto();

            {
                auth.SessionId     = Helper.GetNextGuid().ToString();
                auth.Username      = username;
                auth.Roles         = userObject.UserRole != null ? userObject.UserRole.RoleName : null;
                auth.BranchCode    = userObject.BranchID;
                auth.IsFirstLogIn  = userObject.IsFirstLogIn;
                auth.FullName      = string.Format("{0} {1}", userObject.FirstName, userObject.LastName);
                auth.IsPasswordSet = userObject.Password != "Dummy" && (userObject.AccountType == Constants.AccountType.LocalLocal || userObject.AccountType == Constants.AccountType.LocalFinacle);
                auth.IsRoleSet     = userObject.AccountType == Constants.AccountType.ADLocal || userObject.AccountType == Constants.AccountType.LocalLocal; // userObject.UserRole != null && !string.IsNullOrEmpty(userObject.UserRole.RoleName);
                auth.AccountType   = userObject.AccountType;
            }

            if (sessionBased)
            {
                UpdateLogInSucceed(username, auth.SessionId);
            }

            return(auth);
        }