Beispiel #1
0
        private static UserValidationResult GetUserViaSessionToken(bool requirePin)
        {
            var sessionToken = HttpContext.Current.Request.Headers["SessionToken"];

            if (string.IsNullOrEmpty(sessionToken))
            {
                //DbUtil.LogActivity("GetUserViaSession==null");
                return(null);
            }

            var result = ApiSessionModel.DetermineApiSessionStatus(Guid.Parse(sessionToken), requirePin, HttpContext.Current.Request.Headers["PIN"].ToInt2());

            //DbUtil.LogActivity("GetUserViaSession==" + result.Status.ToString());

            switch (result.Status)
            {
            case ApiSessionStatus.SessionTokenNotFound:
                return(UserValidationResult.Invalid(UserValidationStatus.SessionTokenNotFound));

            case ApiSessionStatus.SessionTokenExpired:
                return(UserValidationResult.Invalid(UserValidationStatus.SessionTokenExpired, user: result.User));

            case ApiSessionStatus.PinExpired:
                return(UserValidationResult.Invalid(UserValidationStatus.PinExpired, user: result.User));

            case ApiSessionStatus.PinInvalid:
                return(UserValidationResult.Invalid(UserValidationStatus.PinInvalid));
            }

            return(ValidateUserBeforeLogin(result.User.Username, HttpContext.Current.Request.Url.OriginalString, result.User, userExists: true));
        }
Beispiel #2
0
        private static UserValidationResult ValidateUserBeforeLogin(string userName, string url, User user, bool userExists, int failedPasswordCount = 0, bool impersonating = false)
        {
            var          maxInvalidPasswordAttempts = CMSMembershipProvider.provider.MaxInvalidPasswordAttempts;
            const string DEFAULT_PROBLEM            = "There is a problem with your username and password combination. If you are using your email address, it must match the one we have on record. Try again or use one of the links below.";

            if (user == null && userExists)
            {
                DbUtil.LogActivity($"failed password #{failedPasswordCount} by {userName}");

                if (failedPasswordCount == maxInvalidPasswordAttempts)
                {
                    return(UserValidationResult.Invalid(UserValidationStatus.TooManyFailedPasswordAttempts,
                                                        "Your account has been locked out for too many failed attempts, use the forgot password link, or notify an Admin"));
                }

                return(UserValidationResult.Invalid(UserValidationStatus.IncorrectPassword, DEFAULT_PROBLEM));
            }

            if (user == null)
            {
                DbUtil.LogActivity("attempt to login by non-user " + userName);
                return(UserValidationResult.Invalid(UserValidationStatus.NoUserFound, DEFAULT_PROBLEM));
            }

            if (user.IsLockedOut)
            {
                NotifyAdmins($"{userName} locked out #{user.FailedPasswordAttemptCount} on {url}",
                             $"{userName} tried to login at {Util.Now} but is locked out");

                return(UserValidationResult.Invalid(UserValidationStatus.LockedOut,
                                                    $"Your account has been locked out for {maxInvalidPasswordAttempts} failed attempts in a short window of time, please use the forgot password link or notify an Admin"));
            }

            if (!user.IsApproved)
            {
                NotifyAdmins($"unapproved user {userName} logging in on {url}",
                             $"{userName} tried to login at {Util.Now} but is not approved");

                return(UserValidationResult.Invalid(UserValidationStatus.UserNotApproved, DEFAULT_PROBLEM));
            }

            if (impersonating)
            {
                if (user.Roles.Contains("Finance"))
                {
                    NotifyAdmins($"cannot impersonate Finance user {userName} on {url}",
                                 $"{userName} tried to login at {Util.Now}");

                    return(UserValidationResult.Invalid(UserValidationStatus.CannotImpersonateFinanceUser, DEFAULT_PROBLEM));
                }
            }

            if (user.Roles.Contains("APIOnly"))
            {
                return(UserValidationResult.Invalid(UserValidationStatus.NoUserFound,
                                                    "Api User is limited to API use only, no interactive login allowed."));
            }

            return(UserValidationResult.Valid(user));
        }
Beispiel #3
0
        public static UserValidationResult ResetSessionExpiration(string sessionToken)
        {
            if (string.IsNullOrEmpty(sessionToken))
            {
                return(UserValidationResult.Invalid(UserValidationStatus.ImproperHeaderStructure, "Could not authenticate user, Authorization or SessionToken headers likely missing.", null));
            }
            //throw new ArgumentNullException("sessionToken");

            var userStatus = AuthenticateMobile(requirePin: true);

            if (userStatus.Status == UserValidationStatus.Success ||
                userStatus.Status == UserValidationStatus.PinExpired ||
                userStatus.Status == UserValidationStatus.SessionTokenExpired)
            {
                var result = ApiSessionModel.ResetSessionExpiration(userStatus.User, HttpContext.Current.Request.Headers["PIN"].ToInt2());
                if (!result)
                {
                    return(UserValidationResult.Invalid(UserValidationStatus.PinInvalid));
                }

                userStatus.Status = UserValidationStatus.Success;
            }

            return(userStatus);
        }
Beispiel #4
0
        public static UserValidationResult AuthenticateLogon(string userName, string password, string url)
        {
            var userQuery = DbUtil.Db.Users.Where(uu =>
                                                  uu.Username == userName ||
                                                  uu.Person.EmailAddress == userName ||
                                                  uu.Person.EmailAddress2 == userName
                                                  );

            var  impersonating = false;
            User user          = null;
            var  userExists    = false;

            try
            {
                userExists = userQuery.Any();
            }
            catch
            {
                return(UserValidationResult.Invalid(UserValidationStatus.BadDatabase, "bad database"));
            }

            var failedPasswordCount = 0;

            foreach (var u in userQuery.ToList())
            {
                if (u.TempPassword != null && password == u.TempPassword)
                {
                    u.TempPassword = null;
                    if (password == "bvcms") // set this up so Admin/bvcms works until password is changed
                    {
                        u.Password           = "";
                        u.MustChangePassword = true;
                    }
                    u.IsLockedOut = false;
                    DbUtil.Db.SubmitChanges();
                    user = u;
                    break;
                }

                if (password == DbUtil.Db.Setting("ImpersonatePassword", Guid.NewGuid().ToString()))
                {
                    user          = u;
                    impersonating = true;
                    break;
                }

                if (Membership.Provider.ValidateUser(u.Username, password))
                {
                    DbUtil.Db.Refresh(RefreshMode.OverwriteCurrentValues, u);
                    user = u;
                    break;
                }

                failedPasswordCount = Math.Max(failedPasswordCount, u.FailedPasswordAttemptCount);
            }

            return(ValidateUserBeforeLogin(userName, url, user, userExists, failedPasswordCount, impersonating));
        }
Beispiel #5
0
        public static UserValidationResult AuthenticateLogon(string userName, string password, HttpRequestBase Request, CMSDataContext db, CMSImageDataContext idb)
        {
            var status = AuthenticateLogon(userName, password, Request.Url.OriginalString, db);

            if (status.IsValid)
            {
                return(UserValidationResult.Valid(status.User));
            }
            return(UserValidationResult.Invalid(UserValidationStatus.IncorrectPassword, status.ErrorMessage));
        }
Beispiel #6
0
        public static UserValidationResult AuthenticateMobile(string role = null, bool checkOrgLeadersOnly = false, bool requirePin = false)
        {
            var userStatus = GetUserViaCredentials() ?? GetUserViaSessionToken(requirePin);

            if (userStatus == null)
            {
                return(UserValidationResult.Invalid(UserValidationStatus.ImproperHeaderStructure, "Could not authenticate user, Authorization or SessionToken headers likely missing.", null));
            }
            //throw new Exception("Could not authenticate user, Authorization or SessionToken headers likely missing.");

            if (!userStatus.IsValid)
            {
                return(userStatus);
            }

            var user = userStatus.User;

            var roleProvider = CMSRoleProvider.provider;

            if (role == null)
            {
                role = "Access";
            }

            if (roleProvider.RoleExists(role))
            {
                if (!roleProvider.IsUserInRole(user.Username, role))
                {
                    userStatus.Status = UserValidationStatus.UserNotInRole;
                    return(userStatus);
                }
            }

            UserName2 = user.Username;
            SetUserInfo(user.Username, HttpContext.Current.Session, deleteSpecialTags: false);
            //DbUtil.LogActivity("iphone auth " + user.Username);

            if (checkOrgLeadersOnly && !Util2.OrgLeadersOnlyChecked)
            {
                DbUtil.LogActivity("iphone leadersonly check " + user.Username);
                if (!Util2.OrgLeadersOnly && roleProvider.IsUserInRole(user.Username, "OrgLeadersOnly"))
                {
                    Util2.OrgLeadersOnly = true;
                    DbUtil.Db.SetOrgLeadersOnly();
                    DbUtil.LogActivity("SetOrgLeadersOnly");
                }
                Util2.OrgLeadersOnlyChecked = true;
            }

            ApiSessionModel.SaveApiSession(userStatus.User, requirePin, HttpContext.Current.Request.Headers["PIN"].ToInt2());

            return(userStatus);
        }
        private UserValidationResult AuthenticateUser(bool requirePin = false)
        {
            // Username and password checks are only necessary for the old iOS application
            var hasInvalidAuthHeaders        = (string.IsNullOrEmpty(Request.Headers["Authorization"]) && (string.IsNullOrEmpty(Request.Headers["username"]) || string.IsNullOrEmpty(Request.Headers["password"])));
            var hasInvalidSessionTokenHeader = string.IsNullOrEmpty(Request.Headers["SessionToken"]);

            if (hasInvalidAuthHeaders && hasInvalidSessionTokenHeader)
            {
                //DbUtil.LogActivity("authentication headers bad");
                return(UserValidationResult.Invalid(UserValidationStatus.ImproperHeaderStructure, "Either the Authorization or SessionToken headers are required.", null));
            }

            //DbUtil.LogActivity("calling authenticatemobile2");
            return(AccountModel.AuthenticateMobile2(requirePin: requirePin, checkOrgMembersOnly: true));
        }
Beispiel #8
0
        public static UserValidationResult AuthenticateMobile2(CMSDataContext cmsdb, CMSImageDataContext cmsidb, bool checkOrgLeadersOnly = false, bool requirePin = false)
        {
            var userStatus = GetUserViaCredentials() ?? GetUserViaSessionToken(cmsdb, requirePin);

            if (userStatus == null)
            {
                //DbUtil.LogActivity("userStatus==null");
                return(UserValidationResult.Invalid(UserValidationStatus.ImproperHeaderStructure, "Could not authenticate user, Authorization or SessionToken headers likely missing.", null));
                //throw new Exception("Could not authenticate user, Authorization or SessionToken headers likely missing.");
            }

            if (!userStatus.IsValid)
            {
                return(userStatus);
            }

            var user = userStatus.User;

            var roleProvider = CMSRoleProvider.provider;

            UserName2 = user.Username;
            SetUserInfo(cmsdb, cmsidb, user.Username, deleteSpecialTags: false);

            if (checkOrgLeadersOnly && !Util2.OrgLeadersOnlyChecked)
            {
                if (!Util2.OrgLeadersOnly && roleProvider.IsUserInRole(user.Username, "OrgLeadersOnly"))
                {
                    Util2.OrgLeadersOnly = true;
                    cmsdb.SetOrgLeadersOnly();
                    CmsData.DbUtil.LogActivity("SetOrgLeadersOnly");
                }
                Util2.OrgLeadersOnlyChecked = true;
            }

            CMSMembershipProvider.provider.SetAuthCookie(user.Username, false);
            ApiSessionModel.SaveApiSession(cmsdb, userStatus.User, requirePin, HttpContextFactory.Current.Request.Headers["PIN"].ToInt2());

            return(userStatus);
        }
Beispiel #9
0
        public static UserValidationResult ResetSessionExpiration(CMSDataContext cmsdb, CMSImageDataContext cmsidb, string sessionToken)
        {
            if (string.IsNullOrEmpty(sessionToken))
            {
                return(UserValidationResult.Invalid(UserValidationStatus.ImproperHeaderStructure, "Could not authenticate user, Authorization or SessionToken headers likely missing.", null));
            }

            var userStatus = AuthenticateMobile(cmsdb, cmsidb, requirePin: true);

            if (userStatus.Status == UserValidationStatus.Success ||
                userStatus.Status == UserValidationStatus.PinExpired ||
                userStatus.Status == UserValidationStatus.SessionTokenExpired)
            {
                var result = ApiSessionModel.ResetSessionExpiration(cmsdb, userStatus.User, HttpContextFactory.Current.Request.Headers["PIN"].ToInt2());
                if (!result)
                {
                    return(UserValidationResult.Invalid(UserValidationStatus.PinInvalid));
                }

                userStatus.Status = UserValidationStatus.Success;
            }

            return(userStatus);
        }
Beispiel #10
0
        public static UserValidationResult AuthenticateLogon(string userName, string password, string url, CMSDataContext db)
        {
            var userQuery = db.Users.Where(uu =>
                                           uu.Username == userName ||
                                           uu.Person.EmailAddress == userName ||
                                           uu.Person.EmailAddress2 == userName
                                           );

            var  impersonating = false;
            User user          = null;
            var  userExists    = false;

            try
            {
                userExists = userQuery.Any();
            }
            catch (Exception ex)
            {
                Elmah.ErrorLog.Default.Log(new Elmah.Error(ex));
                return(UserValidationResult.Invalid(UserValidationStatus.BadDatabase, "bad database"));
            }

            var failedPasswordCount = 0;

            foreach (var u in userQuery.ToList())
            {
                if (u.TempPassword != null && password == u.TempPassword)
                {
                    u.TempPassword = null;
                    if (password == "bvcms") // set this up so Admin/bvcms works until password is changed
                    {
                        u.Password           = "";
                        u.MustChangePassword = true;
                    }
                    else
                    {
                        var mu = CMSMembershipProvider.provider.GetUser(userName, false);
                        mu?.UnlockUser();
                        CMSMembershipProvider.provider.AdminOverride = true;
                        mu?.ChangePassword(mu.ResetPassword(), password);
                        CMSMembershipProvider.provider.AdminOverride = false;
                        u.MustChangePassword = true;
                    }
                    u.IsLockedOut = false;
                    db.SubmitChanges();
                    user = u;
                    break;
                }

                if (password == db.Setting("ImpersonatePassword", Guid.NewGuid().ToString()))
                {
                    user          = u;
                    impersonating = true;
                    HttpContextFactory.Current.Session["IsNonFinanceImpersonator"] = "true";
                    break;
                }

                if (CMSMembershipProvider.provider.ValidateUser(u.Username, password))
                {
                    db.Refresh(RefreshMode.OverwriteCurrentValues, u);
                    user = u;
                    break;
                }

                failedPasswordCount = Math.Max(failedPasswordCount, u.FailedPasswordAttemptCount);
            }

            return(ValidateUserBeforeLogin(userName, url, user, userExists, failedPasswordCount, impersonating));
        }