Esempio n. 1
0
        public List <PemsCity> GetCitiesForUser(string username)
        {
            //we have to get the id of the user for our caching table
            var rbacEntities = new PEMRBACEntities();

            username = username.Trim();
            var user = rbacEntities.UserProfiles.FirstOrDefault(x => x.UserName == username);

            if (user != null)
            {
                int userId = user.UserId;
                //added caching to curcumvent azman performance issues
                //first, try to get a list of cities in the caching table
                var ucaManager          = new UserCustomerAccessManager();
                var existingCustomerIds = ucaManager.GetCustomersIds(userId);

                //if we found any, build a lsit of pems cities and return
                if (existingCustomerIds.Any())
                {
                    return(existingCustomerIds.Select(customerId => new PemsCity(customerId.ToString())).ToList());
                }

                //if we havent found any, we have to get them,
                var cities      = _azManager.GetAuthorizedCities(username);
                var customerIds = cities.Select(x => x.Id).Distinct().ToList();
                // save them to the caching table,
                ucaManager.SetCustomersIds(userId, customerIds);
                // then return them.
                return(cities);
            }
            return(new List <PemsCity>());
        }
Esempio n. 2
0
        public List <PasswordQuestion> GetQuestions()
        {
            // Get a list of security questions.
            // If they do not yet exist for this user then return empty ones.
            var rbacEntities = new PEMRBACEntities();
            var questionList = new List <PasswordQuestion>();

            var questions = from securityQuestions in rbacEntities.UserPasswordQuestions
                            orderby securityQuestions.QuestionNumber ascending
                            where securityQuestions.UserId == _userId select securityQuestions;

            foreach (var userPasswordQuestion in questions)
            {
                var question = new PasswordQuestion(userPasswordQuestion.QuestionNumber, userPasswordQuestion.Question, userPasswordQuestion.Answer);
                questionList.Add(question);
            }

            // Are there enough questions? (For now, assume 0 or 2.)
            if (questionList.Count == 0)
            {
                questionList.Add(new PasswordQuestion(1, "", ""));
                questionList.Add(new PasswordQuestion(2, "", ""));
            }

            return(questionList);
        }
Esempio n. 3
0
 /// <summary>
 ///     Gets a dictionary list of all items for a type and culture code.
 /// </summary>
 /// <param name="customerId">ID of the customer to get the data for</param>
 /// <returns></returns>
 public static IDictionary GetCustomResources(int customerId)
 {
     //make sure the customerid is valid
     //get resourrce where type and culture match
     using (var pemsRbacContext = new PEMRBACEntities())
     {
         var customResources = (from ss in pemsRbacContext.LocaleResourcesCustoms
                                where ss.CustomerId == customerId
                                select ss).Distinct().ToList();
         //return a dictionary list of items with the name and value
         //if there are custom resources for this customerTime of Complaint
         if (customResources.Any())
         {
             var dictionary = new Dictionary <string, string>();
             //DO NOT convert this to lambda
             foreach (var item in customResources)
             {
                 if (!dictionary.ContainsKey(item.Name))
                 {
                     dictionary.Add(item.Name, item.Value);
                 }
             }
             return(dictionary);
         }
     }
     return(new ListDictionary());
 }
Esempio n. 4
0
        public void SaveQuestion(PasswordQuestion question)
        {
            // Get a list of security questions.
            // If they do not yet exist for this user then return empty ones.
            var rbacEntities = new PEMRBACEntities();

            var securityQuestion = (from securityQuestions in rbacEntities.UserPasswordQuestions
                                    where securityQuestions.UserId == _userId && securityQuestions.QuestionNumber == question.QuestionNumber
                                    select securityQuestions).FirstOrDefault();

            if (securityQuestion == null)
            {
                // Add new record
                securityQuestion = new UserPasswordQuestion
                {
                    UserId         = _userId,
                    QuestionNumber = question.QuestionNumber,
                    Question       = question.Question,
                    Answer         = question.Answer // EncryptionManager.Hash(question.Answer.ToLower(), _salt)
                };
                rbacEntities.UserPasswordQuestions.Add(securityQuestion);
            }
            else
            {
                // Update existing record
                securityQuestion.Question = question.Question;
                securityQuestion.Answer   = question.Answer; // EncryptionManager.Hash(question.Answer.ToLower(), _salt);
            }

            rbacEntities.SaveChanges();
        }
Esempio n. 5
0
        public ActionResult GetLink(string currentArea, string currentController, string currentAction, string currentLocale)
        {
            PEMRBACEntities rbacEntities = new PEMRBACEntities();
            HelpLinkModel   model        = null;

            Uri url     = Request.Url;
            var baseUrl = Request.IsLocal
                          ? String.Format("{0}://{1}:{2}", url.Scheme, url.Host, url.Port)
                          : String.Format("{0}://{1}", url.Scheme, url.Host);

            var helpMap = rbacEntities.HelpMaps.FirstOrDefault(x => x.Area == currentArea &&
                                                               x.Controller == currentController &&
                                                               x.Action == currentAction && x.CultureCode == currentLocale);

            if (helpMap != null)
            {
                model = new HelpLinkModel()
                {
                    Server = helpMap.Server == null ? baseUrl :
                             helpMap.Server.EndsWith("/") ? helpMap.Server.Remove(helpMap.Server.Length - 1) : helpMap.Server,
                    File  = helpMap.File.StartsWith("/") ? helpMap.File.Substring(1) : helpMap.File,
                    Topic = helpMap.Topic
                };
            }

            return(PartialView(model));
        }
Esempio n. 6
0
        public ActionResult ResetPassword(string id)
        {
            string token = id;

            using (var userContext = new PEMRBACEntities())
            {
                var user = userContext.Memberships.SingleOrDefault(u => u.PasswordVerificationToken == token);
                if (user != null && user.PasswordVerificationTokenExpirationDate != null)
                {
                    DateTime expiration = ((DateTime)user.PasswordVerificationTokenExpirationDate).ToLocalTime();
                    if (DateTime.Now > expiration)
                    {
                        // token expired
                        ModelState.AddModelError("", "This token has expired. You must complete the reset password process within 10 minutes.");
                        var model = new ResetPasswordModel {
                            Expired = true
                        };
                        return(View(model));
                    }
                    else
                    {
                        // token is valid, show password reset form
                        var model = new ResetPasswordModel {
                            Token = token, Expired = false
                        };
                        return(View(model));
                    }
                }
                else
                {
                    // no user exists with this token
                    return(SendToLoginPage());
                }
            }
        }
Esempio n. 7
0
        //public static int CustomerId { get; set; }

        /// <summary>
        ///     Gets a dictionary list of all items for a type and culture code.
        /// </summary>
        /// <param name="type">Type to get (Glossary, Config, etc)</param>
        /// <param name="cultureCode">Culture code for the resource items to get (en-US, es-EC, etc)</param>
        /// <returns></returns>
        public static IDictionary GetResources(string type, string cultureCode)
        {
            //get resourrce where type and culture match
            using (var pemsRbacContext = new PEMRBACEntities())
            {
                var result = (from ss in pemsRbacContext.LocaleResources
                              where ss.Type == type
                              where ss.CultureCode == cultureCode
                              select ss).Distinct().ToList();

                //return a dictionary list of items with the name and value
                if (result.Any())
                {
                    var dictionary = new Dictionary <string, string>();
                    //DO NOT convert this to lambda
                    foreach (var item in result)
                    {
                        if (!dictionary.ContainsKey(item.Name))
                        {
                            dictionary.Add(item.Name, item.Value);
                        }
                    }

                    return(dictionary);
                }
            }
            return(new ListDictionary());
        }
Esempio n. 8
0
        /// <summary>
        /// Attempts to change the user password.  Adds the password to user password history.
        /// Hashes password appropriately.
        /// </summary>
        /// <param name="password">New password.</param>
        /// <param name="token">Token from WebSecurity.GeneratePasswordResetToken</param>
        public ChangeResult ChangePassword(string password, string token, bool adminOverride = false)
        {
            // Can this password be used?
            ChangeResult changeResult = CheckPasswordHistory(password);

            if (changeResult == ChangeResult.Ok || adminOverride)
            {
                changeResult = WebSecurity.ResetPassword(token, password) ? ChangeResult.Ok : ChangeResult.TokenResetFailed;

                if (changeResult == ChangeResult.Ok)
                {
                    //dont update the pw history if the admin is doing it
                    if (!adminOverride)
                    {
                        AddPasswordToHistory(password);
                    }

                    //we also need to reset their password attempts here
                    var rbacEntities = new PEMRBACEntities();
                    var membership   = rbacEntities.Memberships.FirstOrDefault(x => x.UserId == _userId);
                    if (membership != null)
                    {
                        membership.PasswordFailuresSinceLastSuccess = 0;
                        rbacEntities.SaveChanges();
                    }
                }
            }

            SetLastError(changeResult);
            return(changeResult);
        }
Esempio n. 9
0
        /// <summary>
        /// Adds the password to user password history.  Hashes password appropriately.
        /// </summary>
        /// <param name="password">Password to add to history.</param>
        public void AddPasswordToHistory(string password)
        {
            var rbacEntities = new PEMRBACEntities();

            rbacEntities.UserPasswordHistories.Add(
                new UserPasswordHistory {
                Password = EncryptionManager.Hash(password, _salt), UserId = _userId, ChangeDate = DateTime.Now
            }
                );
            rbacEntities.SaveChanges();
        }
 public static bool IsCustomerMaintenanceGroup(string cityname)
 {
     //we are using a new rbac entities here since this has to be a static method
     using (var rbacEntities = new PEMRBACEntities())
     {
         var existingCustomer = rbacEntities.CustomerProfiles.FirstOrDefault(x => x.DisplayName == cityname);
         if (existingCustomer != null)
         {
             return(existingCustomer.CustomerTypeId == (int)CustomerProfileType.MaintenanceGroup);
         }
     }
     return(false);
 }
Esempio n. 11
0
        /// <summary>
        /// Adds the password to user password history.  Hashes password appropriately.
        /// </summary>
        public void ClearPasswordHistory()
        {
            var rbacEntities = new PEMRBACEntities();
            var oldPasswords = (from pwdHistory in rbacEntities.UserPasswordHistories
                                orderby pwdHistory.ChangeDate descending
                                where pwdHistory.UserId == _userId
                                select pwdHistory).ToList();

            foreach (var oldPassword in oldPasswords)
            {
                rbacEntities.UserPasswordHistories.Remove(oldPassword);
            }
            rbacEntities.SaveChanges();
        }
Esempio n. 12
0
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                //get the user to reset the password for
                using (var userContext = new PEMRBACEntities())
                {
                    var user = userContext.Memberships.SingleOrDefault(u => u.PasswordVerificationToken == model.Token);
                    if (user != null && user.PasswordVerificationTokenExpirationDate != null)
                    {
                        DateTime expiration = ((DateTime)user.PasswordVerificationTokenExpirationDate).ToLocalTime();
                        if (DateTime.Now > expiration)
                        {
                            // token expired
                            ModelState.AddModelError("", "This token has expired. You must complete the reset password process within 10 minutes.");
                            var newModel = new ResetPasswordModel {
                                Expired = false
                            };
                            return(View(newModel));
                        }
                        else
                        {
                            // token is valid, reset their password
                            var passwordManager = new PasswordManager(user.UserProfile.UserName);
                            var returnValue     = passwordManager.ChangePassword(model.NewPassword, model.Token);

                            if (returnValue != PasswordManager.ChangeResult.Ok)
                            {
                                ModelState.AddModelError("", passwordManager.LastError);
                                return(View(model));
                            }
                            //return ContactSupport(passwordManager.LastError);


                            return(ReturnLoginRedirectView("Your password has been reset.", "Password Reset - Success"));
                        }
                    }
                    else
                    {
                        // no user exists with this token
                        return(SendToLoginPage());
                    }
                }
            }

            // If we got this far, something failed. redisplay form
            return(View(model));
        }
Esempio n. 13
0
        /// <summary>
        ///     Gets a dictionary list of all items for a type and culture code.
        /// </summary>
        /// <param name="type">Type to get (Glossary, Config, etc)</param>
        /// <param name="cultureCode">Culture code for the resource items to get (en-US, es-EC, etc)</param>
        /// <param name="customerId">Customer Id </param>
        /// <returns></returns>
        public static IDictionary GetCustomerLocaleResources(string type, string cultureCode, int customerId)
        {
            //get resourrce where type and culture match
            using (var pemsRbacContext = new PEMRBACEntities())
            {
                var result = (from ss in pemsRbacContext.LocaleResources
                              where ss.Type == type
                              where ss.CultureCode == cultureCode
                              select ss).Distinct().ToList();

                //return a dictionary list of items with the name and value
                if (result.Any())
                {
                    var customResources = (from ss in pemsRbacContext.LocaleResourcesCustoms
                                           where ss.Type == type
                                           where ss.CustomerId == customerId
                                           select ss).Distinct().ToList();

                    //if there are custom resources for this customer
                    if (customResources.Any())
                    {
                        foreach (var resource in result)
                        {
                            //check to see if there is a custom value
                            var localeResourcesCustom =
                                customResources.FirstOrDefault(x => x.Name == resource.Name);
                            if (localeResourcesCustom != null)
                            {
                                resource.Value = localeResourcesCustom.Value;
                            }
                        }
                    }

                    var dictionary = new Dictionary <string, string>();
                    //DO NOT convert this to lambda
                    foreach (var item in result)
                    {
                        if (!dictionary.ContainsKey(item.Name))
                        {
                            dictionary.Add(item.Name, item.Value);
                        }
                    }

                    return(dictionary);
                }
            }
            return(new ListDictionary());
        }
Esempio n. 14
0
 /// <summary>
 ///     Adds a Locale Resource to the system for the specified culture and type. Defaults the value to the name of the item if the value isnt passed in
 /// </summary>
 /// <param name="name">Name of hte resource item</param>
 /// <param name="type">Type of the item (Glossary, config, etc)</param>
 /// <param name="cultureCode">Culture code for the resource (en-US, etc)</param>
 /// <param name="value">(Optional) Value for the resource</param>
 public static void AddLocaleResource(string name, string type, string cultureCode, string value = null)
 {
     using (var pemsRbacContext = new PEMRBACEntities())
     {
         //create the item and add it to the system
         var item = new LocaleResource
         {
             CultureCode = cultureCode,
             Name        = name,
             Value       = value ?? name,
             Type        = type
         };
         pemsRbacContext.LocaleResources.Add(item);
         pemsRbacContext.SaveChanges();
     }
 }
Esempio n. 15
0
        public PasswordManager(string userName)
        {
            _userName = userName;

            // Get user id.
            var rbacEntities = new PEMRBACEntities();
            var user         = (from userProfiles in rbacEntities.UserProfiles
                                where userProfiles.UserName == _userName
                                select userProfiles).SingleOrDefault();

            _userId = user != null ? user.UserId : -1;


            _saltLength = 32;
            _salt       = new byte[_saltLength];
        }
Esempio n. 16
0
        public bool Login(string username, string password)
        {
            // Validate credentials
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            bool credentialsAreValid = WebSecurity.Login(username, password);

            if (credentialsAreValid)
            {
                // Must add object to session in order to create a _persistent_ session id
                HttpContext.Current.Session.Add("sessionPlaceholder", "");

                // Log event
                PEMRBACEntities context = new PEMRBACEntities();
                context.AccessLogMembershipEvents.Add(new AccessLogMembershipEvent()
                {
                    EventTypeId = (int)MembershipEvent.Login,
                    UserId      = WebSecurity.GetUserId(username),
                    IPAddress   = HttpContext.Current.Request.GetIpAddress().ToString(),
                    SessionID   = HttpContext.Current.Session.SessionID,
                    TimeStamp   = DateTime.Now
                });
                context.SaveChanges();
            }
            else
            {
                if (WebSecurity.UserExists(username))
                {
                    // username is valid, so password must have been invalid
                    PEMRBACEntities context = new PEMRBACEntities();
                    context.AccessLogMembershipEvents.Add(new AccessLogMembershipEvent()
                    {
                        EventTypeId = (int)MembershipEvent.LoginFailure,
                        UserId      = WebSecurity.GetUserId(username),
                        IPAddress   = HttpContext.Current.Request.GetIpAddress().ToString(),
                        SessionID   = null,
                        TimeStamp   = DateTime.Now
                    });
                    context.SaveChanges();
                }
            }

            return(credentialsAreValid);
        }
Esempio n. 17
0
        public static void Logout()
        {
            PEMRBACEntities context = new PEMRBACEntities();

            context.AccessLogMembershipEvents.Add(new AccessLogMembershipEvent()
            {
                EventTypeId = (int)MembershipEvent.Logout,
                UserId      = WebSecurity.CurrentUserId,
                IPAddress   = HttpContext.Current.Request.GetIpAddress().ToString(),
                SessionID   = HttpContext.Current.Session.SessionID,
                TimeStamp   = DateTime.Now
            });
            context.SaveChanges();

            DeleteSessionCookie();
            WebSecurity.Logout();
        }
Esempio n. 18
0
        private ChangeResult CheckPasswordHistory(string password)
        {
            // Does password match user name?
            if (password.Trim().Equals(_userName, StringComparison.CurrentCultureIgnoreCase))
            {
                return(ChangeResult.MatchesUserName);
            }

            // Has pasword already been used?
            var rbacEntities = new PEMRBACEntities();

            var oldPasswords = (from pwdHistory in rbacEntities.UserPasswordHistories
                                orderby pwdHistory.ChangeDate descending
                                where pwdHistory.UserId == _userId
                                select pwdHistory).Take(5);

            string passwordHash = EncryptionManager.Hash(password, _salt);

            foreach (var oldPassword in oldPasswords)
            {
                if (oldPassword.Password.Equals(passwordHash))
                {
                    return(ChangeResult.AlreadyUsed);
                }

                // If user has just been created then allow password change even though
                // before the 24 hour mark.
                var userProfile = rbacEntities.UserProfiles.FirstOrDefault(m => m.UserName.Equals(_userName));
                if (userProfile == null)
                {
                    // This should never happen but...
                    return(ChangeResult.GeneralError);
                }

                // Is user more than 24 hours old then enforce the 24-hour rule.
                if ((DateTime.Now - userProfile.CreatedDate).TotalHours > 24.0)
                {
                    if ((DateTime.Now - oldPassword.ChangeDate).TotalHours < 24.0)
                    {
                        return(ChangeResult.OnlyOneChangePerDay);
                    }
                }
            }
            return(ChangeResult.Ok);
        }
Esempio n. 19
0
        public bool CheckAnswer(PasswordQuestion question)
        {
            bool answerMatches = false;
            var  rbacEntities  = new PEMRBACEntities();

            var securityQuestion = (from securityQuestions in rbacEntities.UserPasswordQuestions
                                    where securityQuestions.UserId == _userId && securityQuestions.QuestionNumber == question.QuestionNumber
                                    select securityQuestions).First();

            if (securityQuestion != null)
            {
                answerMatches =
                    securityQuestion.Answer.Equals(question.Answer, StringComparison.CurrentCultureIgnoreCase);
//                securityQuestion.Answer.Equals(EncryptionManager.Hash(question.Answer.ToLower(), _salt));
            }

            return(answerMatches);
        }
Esempio n. 20
0
        /// Log login attempts.  This can be enabled/disabled in the web.config.
        ///  <appSettings>
        ///    <add key="pems.logging.log_attempts" value="true" />
        ///  </appSettings>
        public void LogLogin(string username, string password, string url)
        {
            var key = System.Configuration.ConfigurationManager.AppSettings["pems.logging.log_attempts"];

            if (key != null && key.Equals("true", StringComparison.InvariantCultureIgnoreCase))
            {
                var             ipAddress = url == null? "-" :GetDomainName(url);
                PEMRBACEntities context   = new PEMRBACEntities();
                context.LoginAttemptHistories.Add(new LoginAttemptHistory()
                {
                    UserName   = username ?? "-",
                    Password   = password ?? "-",
                    IpAddress  = url == null ? "-" : url.Substring(0, Math.Min(url.Length, 128)),
                    AccessDate = DateTime.Now
                });
                context.SaveChanges();
            }
        }
Esempio n. 21
0
        public PasswordQuestion.QuestionState QuestionState(PasswordQuestion question)
        {
            // Is question number valid?
            if (question.QuestionNumber == 0)
            {
                if (!string.IsNullOrEmpty(question.Question) && !string.IsNullOrEmpty(question.Answer))
                {
                    return(PasswordQuestion.QuestionState.New);
                }
                return(PasswordQuestion.QuestionState.Empty);
            }


            var rbacEntities = new PEMRBACEntities();

            var securityQuestion = (from securityQuestions in rbacEntities.UserPasswordQuestions
                                    where securityQuestions.UserId == _userId && securityQuestions.QuestionNumber == question.QuestionNumber
                                    select securityQuestions).FirstOrDefault();

            if (securityQuestion == null)
            {
                if (!string.IsNullOrEmpty(question.Question) && !string.IsNullOrEmpty(question.Answer))
                {
                    return(PasswordQuestion.QuestionState.New);
                }
                return(PasswordQuestion.QuestionState.Invalid);
            }

            // Has the question changed?
            if (!securityQuestion.Question.Equals(question.Question, StringComparison.CurrentCultureIgnoreCase))
            {
                //if ( securityQuestion.Answer.Equals( Utilities.Constants.Security.DummyAnswer ) )
                //{
                //    return PasswordQuestion.QuestionState.QuestionChangedNeedAnswer;
                //}
                return(PasswordQuestion.QuestionState.Changed);
            }

            // At this point only thing left to check is whether the Answer is still the same as the original stored answer.
            //return securityQuestion.Answer.Equals( EncryptionManager.Hash(question.Answer.ToLower(), _salt))
            //    ? PasswordQuestion.QuestionState.NoChange : PasswordQuestion.QuestionState.Changed;
            return(securityQuestion.Answer.Equals(question.Answer, StringComparison.CurrentCultureIgnoreCase)
                ? PasswordQuestion.QuestionState.NoChange : PasswordQuestion.QuestionState.Changed);
        }
Esempio n. 22
0
        /// <summary>
        /// Gets the local time for a customer
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public DateTime GetCustomerLocalTime(int customerId)
        {
            // Get the basic UTC offset of server.
            var utcOffset       = (int)System.TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours;
            var rbacEntities    = new PEMRBACEntities();
            var customerProfile = rbacEntities.CustomerProfiles.SingleOrDefault(cp => cp.CustomerId == customerId);

            if (customerProfile != null)
            {
                var timeZone = rbacEntities.CustomerTimeZones.FirstOrDefault(m => m.TimeZoneID == customerProfile.TimeZoneID);
                // LocalTimeUTCDifference is in minutes in the [TimeZones] table.  Convert it to hours.
                if (timeZone != null)
                {
                    // If timeZone.DaylightSavingAdjustment != 0 add 1 hour to UTCOffset to handle Daylight Saving Time
                    utcOffset = timeZone.LocalTimeUTCDifference / 60 + (timeZone.DaylightSavingAdjustment != 0 ? 1 : 0);
                }
            }
            var localTime = DateTime.UtcNow + new TimeSpan(0, utcOffset, 0, 0);

            return(localTime);
        }
Esempio n. 23
0
        /// <summary>
        ///     Updates the value of a resource inthe system for the type, name, and culture code passed in.
        /// </summary>
        /// <param name="name">Name if the Locale Resource item</param>
        /// <param name="type">Type of the resourse (Glossary, Config, etc)</param>
        /// <param name="cultureCode">Culture code for the item (en-US, es-EC, etc)</param>
        /// <param name="value">Value of the resource for that paricular culture</param>
        public static void UpdateLocaleResource(string name, string type, string cultureCode, string value)
        {
            using (var pemsRbacContext = new PEMRBACEntities())
            {
                //get the item
                var result = (from ss in pemsRbacContext.LocaleResources
                              where ss.Type == type
                              where ss.CultureCode == cultureCode
                              where ss.Name == name
                              select ss).FirstOrDefault();

                //update the item
                if (result != null)
                {
                    result.Value = value;
                    pemsRbacContext.SaveChanges();
                }
                //if it wasnt found, add the item
                else
                {
                    AddLocaleResource(name, type, cultureCode, value);
                }
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Add the RBAC entry for the admin site.
        /// </summary>
        private void AddAdminSite()
        {
            var authorizationManager = new AuthorizationManager();

            Log = "Creating RBAC store for the Admin site.";

            if (authorizationManager.CreateCity(_options.AdminSiteId, "Admin", "PEMS Administration"))
            {
                Log = "Created RBAC Admin store";
            }
            else
            {
                LogError = "Failed to create RBAC Admin store";
            }


            Log = "Creating RBAC entries for the administration site...";
            bool success = authorizationManager.SetConfiguration(_options.AdminSiteTemplate);

            // Now write out the process log.
            foreach (var xmlProcessLog in authorizationManager.XmlProcessLogs)
            {
                Log = xmlProcessLog;
            }

            if (success)
            {
                Log = "***** RBAC entries successfully processed. *****";
            }
            else
            {
                LogError = "***** Errors were encountered creating the RBAC entries.  See below. *****";

                // Now write out errors.
                foreach (var xmlProcessError in authorizationManager.XmlProcessErrors)
                {
                    LogError = xmlProcessError;
                }
            }


            // Create an entry in [CustomerProfiles] if required.
            var RbacEntities = new PEMRBACEntities();

            // Get the user id that is adding this Admin site.
            UserFactory userFactory = new UserFactory();
            int         userId      = userFactory.GetUserId(_options.AdminUserName);

            if (userId != (int)Constants.User.InvalidUserId)
            {
                CustomerProfile customerProfile = RbacEntities.CustomerProfiles.FirstOrDefault(m => m.DisplayName.Equals("Admin"));
                if (customerProfile == null)
                {
                    customerProfile = new CustomerProfile()
                    {
                        CustomerId                    = _options.AdminSiteId,
                        DisplayName                   = "Admin",
                        CreatedOn                     = DateTime.Now,
                        CreatedBy                     = userId,
                        StatusChangeDate              = DateTime.Now,
                        PEMSConnectionStringName      = null,
                        ReportingConnectionStringName = null,
                        CustomerTypeId                = (int)CustomerProfileType.Admin,
                        Status = (int)CustomerStatus.Active
                    };
                    RbacEntities.CustomerProfiles.Add(customerProfile);
                    RbacEntities.SaveChanges();
                    Log = "Created entry in CustomerProfiles for Admin.";
                }
            }
            else
            {
                LogError = "Unable to create an entry in CustomerProfiles for Admin - Invalid admin user name.";
            }
        }
Esempio n. 25
0
        public ActionResult SecurityQuestions(SecurityQuestionsModel model, string username, string failureCount, string questionID)
        {
            if (ModelState.IsValid)
            {
                // string username = model.UserName;
                if (WebSecurity.UserExists(username))
                {
                    //get the question being tested
                    var pwMgr = new PasswordManager(username);
                    //get the questions for this user
                    var questions = pwMgr.GetQuestions();



                    var question = questions.FirstOrDefault(x => x.QuestionNumber.ToString() == model.QuestionID);

                    //check to see if the answer is valid
                    bool questionMatch = false;
                    if (question != null)
                    {
                        question.Answer = model.QuestionValue;
                        questionMatch   = pwMgr.CheckAnswer(question);
                    }

                    //if it is, email the user the link and display the redirect to login view
                    if (questionMatch)
                    {
                        string token = WebSecurity.GeneratePasswordResetToken(username, 10);
                        string email = "";

                        using (var userContext = new PEMRBACEntities())
                        {
                            var profile = userContext.UserProfiles.SingleOrDefault(u => u.UserName == username);
                            if (profile != null)
                            {
                                email = profile.Email;
                            }
                        }

                        if (!String.IsNullOrEmpty(email) && !String.IsNullOrEmpty(token))
                        {
                            // Send password reset email
                            var mailer = new UserMailer();
                            mailer.PasswordReset(token, email).Send();
                        }
                        else
                        {
                            ModelState.AddModelError("",
                                                     "Could not send email at this time. If the problem perists please contact your system administrator");
                        }

                        //if everythign was successful, then we need to return the login redirect view
                        return(ReturnLoginRedirectView("You have been emailed a link to reset your password.",
                                                       "Password Reset - Emailed"));
                    }

                    //if the question didnt match, and this is the first failure (0), then retry with the other question
                    //also, lets make sure we are telling hte user why they have to answer again
                    if (model.FailureCount == "0")
                    {
                        ModelState.AddModelError("", "Incorrect Answer. Please Try Again.");
                        //get the question that we did NOT just ask
                        var unansweredQuestion = questions.FirstOrDefault(x => x.QuestionNumber.ToString() != model.QuestionID);
                        //re-ask them

                        var secModel = new SecurityQuestionsModel
                        {
                            UserName      = username,
                            FailureCount  = "1",
                            QuestionID    = unansweredQuestion.QuestionNumber.ToString(),
                            QuestionText  = unansweredQuestion.Question,
                            QuestionValue = string.Empty
                        };

                        return(View("SecurityQuestions", secModel));
                    }

                    //they didnt answer their quesitons correctly, display the system admin contact view.
                    return(View("CustomerService", new CustomerSupportModel()));
                }
                else
                {
                    ModelState.AddModelError("", "No account with that username found. Please enter a valid username");
                }
            }

            // If we got this far, something failed. redisplay form
            return(View(model));
        }
Esempio n. 26
0
        public void Log(string area, string city, string controller, string action,
                        string sessionID, int userId, AuthorizationManager.AccessRights accessRights,
                        double accessDuration, double accessOverhead)
        {
            if (!Enabled)
            {
                return;
            }

            var rbacEntities = new PEMRBACEntities();


            if (!_logAjax)
            {
                if (string.IsNullOrEmpty(area) && string.IsNullOrEmpty(city))
                {
                    return;
                }
            }

            if (!_logPages)
            {
                if (!string.IsNullOrEmpty(area) && !string.IsNullOrEmpty(city))
                {
                    return;
                }
            }

            if (!_logAccessAllowed)
            {
                if (accessRights == AuthorizationManager.AccessRights.Allowed)
                {
                    return;
                }
            }

            if (!_logAccessUndefined)
            {
                if (((int)accessRights) > 0)
                {
                    return;
                }
            }

            if (!_logAccessDenied)
            {
                if (((int)accessRights) < 0)
                {
                    return;
                }
            }


            rbacEntities.AccessLogs.Add(new AccessLog()
            {
                Area           = area,
                City           = city,
                Controller     = controller,
                Action         = action,
                SessionID      = sessionID,
                UserId         = userId,
                AccessRights   = (int)accessRights,
                AccessDuration = accessDuration,
                AccessOverhead = accessOverhead,
                AccessDate     = DateTime.Now
            });

            rbacEntities.SaveChanges();
        }
Esempio n. 27
0
        public ActionResult Landing()
        {
            //check to see if they have a city. if they do, then send them to the correct city homepage.
            var cityCookie  = GetCityCookie();
            var userFactory = new UserFactory();

            //if they have a cookie (which they should at this point
            if (cityCookie != null)
            {
                //check to see if a city is set, if it is, then send them to that city
                string username         = WebSecurity.CurrentUserName;
                string emptyCookieValue = username + "|None|" + CustomerLoginType.Unknown;
                if (cityCookie.Value != emptyCookieValue)
                {
                    return(SendToCityHomePage(cityCookie.Value.Split('|')[1]));
                }
            }
            //if the cookie is null, send them to the login page
            else
            {
                return(SendToLoginPage());
            }

            ViewBag.PWExpiration = userFactory.GetPasswordExpirationInDays();
            var model      = new LandingDropDownModel();
            var secMgr     = new SecurityManager();
            var userCities = secMgr.GetCitiesForUser(WebSecurity.CurrentUserName);

            // Need to check if CustomerProfile.Status == CustomerStatus.Active
            var rbacEntities = new PEMRBACEntities();
            var landingItems = new List <LandingDropDownItem>();

            foreach (var userCity in userCities)
            {
                var customerProfile = rbacEntities.CustomerProfiles.FirstOrDefault(m => m.CustomerId == userCity.Id);
                if (customerProfile != null && customerProfile.Status == (int)CustomerStatus.Active)
                {
                    landingItems.Add(new LandingDropDownItem
                    {
                        Text      = userCity.DisplayName,
                        Value     = userCity.InternalName,
                        LoginType = CustomerLoginType.Customer
                    });

                    var _secMgr = new SecurityManager();
                    //if this is a amaintenance group, then you need to add all of the active
                    if (userCity.CustomerType == CustomerProfileType.MaintenanceGroup)
                    {
                        //t add the maint group customers login optoipns
                        foreach (var maintCustomer in userCity.MaintenanceCustomers.Where(x => x.IsActive))
                        {
                            //only add this option if they are a technician.
                            //first, go check to see if they have access ot this customer -
                            var cityGroups = _secMgr.GetGroupsForUser(maintCustomer, WebSecurity.CurrentUserName, true);
                            var authMgr    = new AuthorizationManager(maintCustomer);
                            var storeRole  = authMgr.GetMaintenanceUsersForStore(maintCustomer.InternalName);

                            var isMaintGroup = storeRole.Any(x => x == Constants.Security.DefaultMaintenanceGroupName);

                            //then test for the _maintenance group
                            var isPartOfMainGroup = cityGroups.Any(x => x.Key == Constants.Security.DefaultMaintenanceGroupName && x.Value);
                            if (isPartOfMainGroup || isMaintGroup)
                            {
                                landingItems.Add(new LandingDropDownItem
                                {
                                    Text      = maintCustomer.DisplayName,
                                    Value     = maintCustomer.InternalName,
                                    LoginType = CustomerLoginType.MaintenanceGroupCustomer
                                });
                            }
                        }
                    }
                }
            }

            //if the user only has one city, set their cookie and send them to the city homepage
            if (landingItems.Count == 1)
            {
                //set the cookie and send them to ttheir new homepage.
                var city = landingItems.FirstOrDefault();
                SetCityCookie(WebSecurity.CurrentUserName + "|" + city.Value + "|" + city.LoginType);
                return(SendToCityHomePage(city.Value));
            }

            model.Items = landingItems;
            return(View(model));
        }