public void AddUser(User userToAdd, ref ValidationStateDictionary states) { var v = new UserValidator().Validate(userToAdd, validationRepositoryInstance); if (v.Errors.Count > 0) { states.Add(typeof(User), v); return; } var settings = SecurityConfig.GetCurrent(); if (settings.Cookie.PasswordHashed && !string.IsNullOrEmpty(userToAdd.Password)) { userToAdd.Password = PasswordHash.Hash(userToAdd.Username.ToLower(), userToAdd.Password); } else if (userToAdd.AccountType == Constants.AccountType.ADLocal) { userToAdd.Password = "******"; } userToAdd.ApprovalStatus = Constants.ApprovalStatus.Pending; userToAdd.IsFirstLogIn = true; userToAdd.RoleId = userToAdd.UserRole.RoleId; //check if the AccountExpires and set the number of days for Accountexpiry updateUserAccountExpiry(userToAdd); repositoryInstance.AddUser(userToAdd); RegistrationNotification(userToAdd, true); }
internal static bool IsSessionActive(string sessionId) { if (string.IsNullOrEmpty(sessionId)) { return(false); } var settings = SecurityConfig.GetCurrent(); var current = AuthCookie.GetCurrent(); ISecurityService authenticationService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve <ISecurityService>(); var userObject = authenticationService.GetUserBySessionId(sessionId); bool isActive = false; if (userObject != null) { if ((!userObject.CurrentSessionId.HasValue || sessionId != userObject.CurrentSessionId.ToString()) || (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) > Helper.GetLocalDate()) || ((userObject.ApprovalStatus != Constants.ApprovalStatus.Approved) || userObject.IsLockedOut || userObject.IsDeleted)) { if (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) > Helper.GetLocalDate()) { isActive = true; } } } return(isActive); }
public static string CheckAccessByCookie() { var current = AuthCookie.GetCurrent(); var settings = SecurityConfig.GetCurrent(); var cookieNotFound = (current == null || current.SessionUid == null); AuthenticationDataDto dto = null; if (cookieNotFound || (settings.Cookie.CookieOnlyCheck && current.AuthExpiry < Helper.GetLocalDate())) { return(null); } else if (!settings.Cookie.CookieOnlyCheck) { dto = Access.Renew(current.SessionUid); if (dto == null) { return(null); } else { return(string.Format("{0}||{1}", dto.Username.Trim(), dto.Roles.Trim())); } } else if (settings.Cookie.CookieOnlyCheck) { return(string.Format("{0}||{1}", current.Username.Trim(), current.UserRoles.Trim())); } return(null); }
public ActionResult LogOut() { Access.SignOut(_securityService); if (!string.IsNullOrEmpty((Request.QueryString["xxkeyxx"] as string))) { Danger(string.Format("You have been logged out due to inactivity for {0} minutes. Please log in again.", SecurityConfig.GetCurrent().Cookie.Timeout), true); } //var url = string.Format("{0}/{1}", Helper.GetRootURL(), SecurityConfig.GetCurrent().Login.Page); return(RedirectToAction(SecurityConfig.GetCurrent().Login.Page)); }
public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (!_authorizationStatus) { var settings = SecurityConfig.GetCurrent(); var current = AuthCookie.GetCurrent(); var sessionID = string.Empty; if (current != null) { sessionID = current.SessionUid; current.Delete(); } string loginUrl = (settings.Login.Url + settings.Login.Page).ToLower(); var rawUrl = filterContext.HttpContext.Request.RawUrl; var redirectUrl = string.Empty; if (!string.IsNullOrEmpty(rawUrl) && rawUrl != loginUrl) { if (!rawUrl.Contains("xxkeyxx")) //auto logout key { if (!Access.IsSessionActive(sessionID)) { redirectUrl = "?ReturnUrl=" + HttpUtility.UrlEncode(rawUrl, filterContext.HttpContext.Request.ContentEncoding); } else { redirectUrl = string.Empty; } AddAlert(AlertStyles.Danger, "Your session has expired or you do not have access to the page you are trying to access.", true); } else { AddAlert(AlertStyles.Danger, string.Format("You have been logged out due to inactivity for {0} minutes. Please log in again.", SecurityConfig.GetCurrent().Cookie.Timeout), true); } } if (!string.IsNullOrEmpty(sessionID)) { var context = HttpContext.Current; var securityService = ((IContainer)context.Application["container"]).Resolve <ISecurityService>(); securityService.SignOut(sessionID); } filterContext.Result = new RedirectResult(loginUrl + redirectUrl); return; } }
public AuthenticationDataDto Renew(string sessionId) { var userObject = repositoryInstance.GetUserBySessionId(sessionId); if (userObject == null) { return(null); } var settings = SecurityConfig.GetCurrent(); bool renewSucceed = true; if ((!userObject.CurrentSessionId.HasValue || sessionId != userObject.CurrentSessionId.ToString()) || (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) < Helper.GetLocalDate()) || ((userObject.ApprovalStatus != Constants.ApprovalStatus.Approved) || userObject.IsLockedOut || userObject.IsDeleted)) { if (userObject.LastActivityDate.Value.AddMinutes(settings.Cookie.Timeout) < Helper.GetLocalDate()) { userObject.IsOnline = false; userObject.CurrentSessionId = null; } renewSucceed = false; } else { if (settings.Cookie.SlidingExpiration) { userObject.LastActivityDate = Helper.GetLocalDate(); } } UpdateRenewSucceed(userObject); AuthenticationDataDto auth = null; if (renewSucceed) { auth = new AuthenticationDataDto(); { auth.SessionId = userObject.CurrentSessionId.Value.ToString(); auth.Username = userObject.Username; auth.BranchCode = userObject.BranchID; auth.Roles = userObject.UserRole == null ? null : userObject.UserRole.RoleName; auth.FullName = string.Format("{0} {1}", userObject.FirstName, userObject.LastName); auth.IsRoleSet = !(userObject.AccountType == Constants.AccountType.ADFinacle || userObject.AccountType == Constants.AccountType.LocalFinacle); } } return(auth); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { var settings = SecurityConfig.GetCurrent(); var rootURL = Helper.GetRootURL() + "/"; string loginUrl = (string.Format("{0}{1}", rootURL, settings.Login.Page)).ToLower(); string currentURL = Helper.GetCurrentURL(); var returnURLIndex = currentURL.IndexOf("?ReturnUrl"); currentURL = returnURLIndex > 0 ? currentURL.Substring(0, returnURLIndex) : currentURL; if (!string.IsNullOrEmpty(currentURL) && (currentURL.Equals(loginUrl, StringComparison.OrdinalIgnoreCase) || currentURL.Equals(rootURL, StringComparison.OrdinalIgnoreCase))) { _authorizationStatus = true; return(_authorizationStatus); } //var key = CreateKey(httpContext); //var isCached = HttpRuntime.Cache.Get(key) as string; //if (isCached != null) //{ // _authorizationStatus = bool.Parse(isCached); // return _authorizationStatus; //} if (_accessRequiredList != null) { _authorizationStatus = Access.IsAccessAllowed(httpContext, _moduleName, _accessRequiredList, _verifyAreaAccessRight); } else { _authorizationStatus = Access.IsAccessAllowed(httpContext, _moduleName, _accessRequired, _verifyAreaAccessRight); } //HttpRuntime.Cache.Insert(key, _authorizationStatus.ToString().ToLower()); return(_authorizationStatus); }
public void UserChangePassword(string userName, string oldPassword, string newPassword, string confirmNewPassword, ref ValidationStateDictionary states) { ValidationState v = new ValidationState(); if (string.IsNullOrEmpty(oldPassword)) { v.Errors.Add(new ValidationError("OldPassword.InvalidOldPassword", oldPassword, "Old Password is not set")); } if (string.IsNullOrEmpty(newPassword)) { v.Errors.Add(new ValidationError("NewPassword.InvalidNewPassword", newPassword, "New Password is not set")); } else if (newPassword.Length < 8) { v.Errors.Add(new ValidationError("NewPassword.InvalidNewPassword", newPassword, string.Format("New Password minimum length is {0}", 8))); } if (string.IsNullOrEmpty(confirmNewPassword)) { v.Errors.Add(new ValidationError("ConfirmNewPassword.InvalidConfirmPassword", confirmNewPassword, "Confirm New Password is not set")); } else if (newPassword.Length < 8) { v.Errors.Add(new ValidationError("ConfirmNewPassword.InvalidNewPassword", newPassword, string.Format("Confirm Password minimum length is {0}", 8))); } if (confirmNewPassword != newPassword) { v.Errors.Add(new ValidationError("ConfirmNewPassword.ConfirmPasswordNotMatch", confirmNewPassword, "Password and confirm password not equal.")); } if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(newPassword)) { if (userName.ToLower() == newPassword.ToLower()) { v.Errors.Add(new ValidationError("NewPassword.ConfirmPasswordNotMatch", newPassword, "Password cannot be user name.")); } } var userObject = repositoryInstance.GetUser(userName); if (userObject == null) { v.Errors.Add(new ValidationError("OldPassword.InvalidAccountDetails", userName, "Invalid user details, please check and try again.")); } else { if (userObject.AccountType != Constants.AccountType.LocalFinacle && userObject.AccountType != Constants.AccountType.LocalLocal) { v.Errors.Add(new ValidationError("OldPassword.InvalidAccountDetails", userName, "Password cannot be changed. Please contact your administrator")); } } if ((int)Utility.PasswordAdvisor.CheckStrength(newPassword) < 4) { v.Errors.Add(new ValidationError("Password.ComplexityViolationError", newPassword, "Password failed the company's password complexity policy check.")); } if (!v.IsValid) { states.Add(typeof(ChangePasswordDto), v); return; } var storePassword = userObject.Password; var settings = SecurityConfig.GetCurrent(); if (settings.Cookie.PasswordHashed) { oldPassword = PasswordHash.Hash(userName.ToLower(), oldPassword); newPassword = PasswordHash.Hash(userName.ToLower(), newPassword); } if (oldPassword != storePassword) { v.Errors.Add(new ValidationError("OldPassword.InvalidOldPassword", oldPassword, "Password change not successful. Old password is incorrect.")); states.Add(typeof(ChangePasswordDto), v); return; } int unUsablePreviousPasswordCount = 0; if (passwordHistoryServiceInstance.IsRepeatingPassword(new PasswordHistoryModel() { UserName = userName, Password = newPassword }, out unUsablePreviousPasswordCount)) { v.Errors.Add(new ValidationError("NewPassword.PreviouslyUsedError", oldPassword, "Password change not successful. Last " + unUsablePreviousPasswordCount + " Passwords cannot be used.")); states.Add(typeof(ChangePasswordDto), v); return; } repositoryInstance.ResetUserPassword(userName, newPassword, false); passwordHistoryServiceInstance.InsertPassword(new PasswordHistoryModel() { UserName = userName, Password = newPassword }); }
//public bool ActivateAccount(string activationCode) //{ // return repositoryInstance.ActivateAccount(activationCode); //} public void ResetPassword(string username, string email, ref ValidationStateDictionary states) { ValidationState v = new ValidationState(); string firstName = string.Empty; if (string.IsNullOrEmpty(username)) { v.Errors.Add(new ValidationError("Username.UsernameRequired", null, "Username is not set.")); } if (v.Errors.Count > 0) { states.Add(typeof(ChangePasswordDto), v); return; } var userObject = repositoryInstance.GetUser(username); if (userObject == null) { v.Errors.Add(new ValidationError("Username.InvalidAccountDetails", username, "Invalid user details, please check and try again.")); } else { if (userObject.AccountType != Constants.AccountType.LocalFinacle && userObject.AccountType != Constants.AccountType.LocalLocal) { v.Errors.Add(new ValidationError("Username.InvalidAccountDetails", username, "Password cannot be changed. Please contact your administrator")); } } if (v.Errors.Count > 0) { states.Add(typeof(ChangePasswordDto), v); return; } if (string.IsNullOrEmpty(email)) { v.Errors.Add(new ValidationError("Email.EmailRequired", null, "Email is not set.")); } else { if (!Helper.IsEmailValid(email)) { v.Errors.Add(new ValidationError("Email.EmailInvalid", null, "Email is Invalid.")); } if (userObject.Username.ToLower() != username.ToLower() || userObject.Email.ToLower() != email.ToLower()) { v.Errors.Add(new ValidationError("Username.UsernameAndEmailNotMatch", username, "Unable to do a password reset for this details.")); } } if (v.Errors.Count > 0) { states.Add(typeof(ChangePasswordDto), v); return; } string newPassword = (new PasswordGenerator()).GeneratePassword(12); var hashedPassword = string.Empty; var settings = SecurityConfig.GetCurrent(); if (settings.Cookie.PasswordHashed) { hashedPassword = PasswordHash.Hash(username.ToLower(), newPassword); } else { hashedPassword = newPassword; } repositoryInstance.ResetUserPassword(username, hashedPassword, true); bool status = SendPasswordResetMail(username, firstName, email, newPassword); if (!status) { v.Errors.Add(new ValidationError("Username.UnableToRetrievePassword", username, "Unable to do a password reset for this details.")); states.Add(typeof(ChangePasswordDto), v); } return; }
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); }
private static ISecurityService PerfomAccessCheck(HttpContextBase context) { var settings = SecurityConfig.GetCurrent(); var current = AuthCookie.GetCurrent(); ISecurityService authenticationService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve <ISecurityService>(); var cookieNotFound = (current == null || current.SessionUid == null); var cookiedDeleted = false; AuthenticationDataDto dto = null; if (cookieNotFound) { if (current != null) { current.Delete(); cookiedDeleted = true; } } else if (settings.Cookie.CookieOnlyCheck && current.AuthExpiry < Helper.GetLocalDate()) { current.Delete(); cookiedDeleted = true; } else if (!settings.Cookie.CookieOnlyCheck) { dto = Access.Renew(current.SessionUid, authenticationService); if (dto == null) { current.Delete(); cookiedDeleted = true; } } if (!cookiedDeleted) { if (dto == null) { dto = new AuthenticationDataDto(); } Identity identity = new Identity(new Guid(current.SessionUid), settings.Cookie.CookieOnlyCheck ? current.Username : dto.Username, settings.Cookie.CookieOnlyCheck ? current.UserRoles : dto.Roles, dto.FullName, settings.Cookie.CookieOnlyCheck ? current.BranchCode : dto.BranchCode, settings.Cookie.CookieOnlyCheck ? current.AccountType : dto.AccountType); var principal = new Principal(identity, identity.Roles, identity.AccountType); context.User = principal; Thread.CurrentPrincipal = principal; if (settings.Cookie.SlidingExpiration && settings.Cookie.CookieOnlyCheck) { current.AuthExpiry = Helper.GetLocalDate().AddMinutes(settings.Cookie.Timeout); current.Save(); } } var ip = context.Request.UserHostAddress; return(authenticationService); }
public static bool SignIn(string username, string password, string tokenCode, ISecurityService authenticationService, IFinacleRepository finacleRepository, out bool isFirstLogIn, ref ValidationStateDictionary states) { isFirstLogIn = false; AuthenticationDataDto currentUser = null; bool validateWithAD = false; bool useFinacleRole = false; var hashedPassword = string.Empty; var settings = SecurityConfig.GetCurrent(); if (settings.Cookie.PasswordHashed && !string.IsNullOrEmpty(password)) { var lowerUsername = string.Empty; if (!string.IsNullOrEmpty(username)) { lowerUsername = username.ToLower(); } hashedPassword = PasswordHash.Hash(lowerUsername, password); } currentUser = authenticationService.SignIn(username, hashedPassword, true, ref states); if (currentUser != null) { if (currentUser.AppAuthenticationFailed) { return(false); } } states.Clear(); SetAuthMode(currentUser, ref validateWithAD, ref useFinacleRole); AuthenticationResponse result = new AuthenticationResponse(); if (validateWithAD) { var ADResult = ADAuthentication(username, password, tokenCode, authenticationService, finacleRepository, states, settings, ref result); if (!ADResult) { if (currentUser != null) { authenticationService.SignOut(currentUser.SessionId); } return(false); } } if (useFinacleRole) { currentUser = FinacleAuthorization(username, authenticationService, finacleRepository, currentUser, result); } else { if (!ValidateLocalUserRole(states, currentUser)) { if (currentUser != null) { authenticationService.SignOut(currentUser.SessionId); } return(false); } } if (!ValidateRoleAndUser(username, authenticationService, states, currentUser)) { if (currentUser != null) { authenticationService.SignOut(currentUser.SessionId); } return(false); } if (!Check2FA(username, tokenCode, states, currentUser, settings)) { if (currentUser != null) { authenticationService.SignOut(currentUser.SessionId); } return(false); } CreateThreadPrincipalAndAuthCookie(currentUser, settings); isFirstLogIn = validateWithAD == true ? false : currentUser.IsFirstLogIn; //if (useFinacleRole) /no longer needed. //{ // //cache the role, so that we don't go back to finacle on every session renewal // ICacheService cacheService = ((IContainer)System.Web.HttpContext.Current.Application["container"]).Resolve<ICacheService>(); // CacheItemPolicy policy = new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0, settings.Cookie.Timeout + 1, 0) }; // cacheService.Add(string.Format("UserSessionID:{0}", currentUser.SessionId), currentUser.Roles, policy); //} return(true); }
public static bool Is2FAEnabled() { var settings = SecurityConfig.GetCurrent(); return(settings.Cookie.Enable2FA); }
public static int GetTimeOutInMilliseconds(this HtmlHelper htmlHelper) { return(SecurityConfig.GetCurrent().Cookie.Timeout * 60 * 1000); }