private static void FilteredLog(ILogService logger, LogLevel level, string message, Exception exception = null, User user = null)
        {
            // Don't bother logging thread abort exception
            if ((exception != null) && (exception is System.Threading.ThreadAbortException))
                return;

            string fullMessage = exception == null ? string.Empty : exception.ToString();
            logger.InsertLog(level, message, fullMessage, user);
        }
        /// <summary>
        /// Authorize permission
        /// </summary>
        /// <param name="permission">Permission record</param>
        /// <param name="user">User</param>
        /// <returns>true - authorized; otherwise, false</returns>
        public virtual bool Authorize(PermissionRecord permission, User user)
        {
            if (permission == null)
                return false;

            if (user == null)
                return false;

            var userRoles = user.UserRoles.Where(ur => ur.Active);
            foreach (var role in userRoles)
                foreach (var userPermission in role.PermissionRecords)
                    if (userPermission.SystemName.Equals(permission.SystemName, StringComparison.InvariantCultureIgnoreCase))
                        return true;

            return false;
        }
        /// <summary>
        /// Inserts a log item
        /// </summary>
        /// <param name="logLevel">Log level</param>
        /// <param name="shortMessage">The short message</param>
        /// <param name="fullMessage">The full message</param>
        /// <param name="user">The user to associate log record with</param>
        /// <returns>A log item</returns>
        public Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", User user = null)
        {
            var log = new Log
            {
                LogLevel = logLevel,
                ShortMessage = shortMessage,
                FullMessage = fullMessage,
                IpAddress = _webHelper.GetCurrentIpAddress(),
                User = user,
                PageUrl = _webHelper.GetThisPageUrl(true),
                ReferrerUrl = _webHelper.GetUrlReferrer(),
                CreatedOnUtc = DateTime.UtcNow
            };

            _logRepository.Insert(log);

            return log;
        }
        protected User GetCurrentUser()
        {
            if (_cachedUser != null)
                return _cachedUser;

            if (_httpContext != null)
            {
                var user = _authenticationService.GetAuthenticatedUser();
                if (user != null && user.Active)
                {
                    if (user.LastLoginDate.AddMinutes(1.0) < DateTime.Now)
                    {
                        user.LastLoginDate = DateTime.Now;
                        _userService.UpdateUser(user);
                    }

                    _cachedUser = user;
                }
            }

            return _cachedUser;
        }
        /// <summary>
        /// Return the current authenticated user
        /// </summary>
        /// <returns>User</returns>
        public User GetAuthenticatedUser()
        {
            if (_cachedUser != null)
                return _cachedUser;

            if (_httpContext == null)
                return null;

            if (_httpContext.Request == null)
                return null;

            if (!_httpContext.Request.IsAuthenticated)
                return null;

            if (!(_httpContext.User.Identity is FormsIdentity))
                return null;

            var formsIdentity = (FormsIdentity)_httpContext.User.Identity;
            var user = GetAuthenticatedUserFromTicket(formsIdentity.Ticket);
            if (user != null && user.Active)
                _cachedUser = user;
            return _cachedUser;
        }
 /// <summary>
 /// Signs out the current authenticated user
 /// </summary>
 public void SignOut()
 {
     _cachedUser = null;
     FormsAuthentication.SignOut();
 }
        private UserEditModel PrepareUserEditModel(User user)
        {
            var model = new UserEditModel
            {
                CanEditRoles = _permissionService.Authorize(PermissionProvider.PromoteUsers),
                IsSiteOwner = _workContext.CurrentUser.UserRoles.Any(x => x.SystemName == SystemUserRoleNames.SiteOwner),
                User = PrepareUserModel(user)
            };

            return model;
        }
        private UserProfileModel PrepareUserProfileModel(User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            AddHomeBreadcrumb();
            AddBreadcrumb("Profile for " + user.DisplayName, Url.RouteUrl("UserProfile", new { userName = user.UserName }));

            var model = new UserProfileModel
            {
                FinishedProjects = _projectService.GetFinishedProjectsByUserId(user.Id).Select(x => x.ToModel()).ToList(),
                IsOwnProfile = (_workContext.CurrentUser != null && user.Id == _workContext.CurrentUser.Id),
                MetaTitle = string.Format("User profile for {0} | Volunteer on #WeWillGather", user.DisplayName),
                OrganisedProjects = _projectService.GetOrganisedProjectsByUserId(user.Id).Select(x => x.ToModel()).ToList(),
                UpcomingProjects = _projectService.GetUpcomingProjectsByUserId(user.Id).Select(x => x.ToModel()).ToList(),
                User = user.ToModel()
            };

            if (model.IsOwnProfile)
            {
                model.User.AvailableDisclosureLevels = _webHelper.GetAllEnumListItems<DisclosureLevel>();
            }
            else
            {
                if (_workContext.CurrentUser != null)
                {
                    if (model.OrganisedProjects.Any(x => x.Volunteers.Any(y => y.Id == _workContext.CurrentUser.Id) || x.Owners.Any(y => y.Id == _workContext.CurrentUser.Id)))
                        model.VisitorIsVolunteer = true;
                }
            }

            return model;
        }
        private ApiAuthenticationModel PrepareApiEditProfileModel(User user, int id)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            AddHomeBreadcrumb();
            AddBreadcrumb("Profile for " + user.DisplayName, Url.RouteUrl("UserProfile", new { userName = user.UserName }));
            AddBreadcrumb("Api Details", Url.RouteUrl("UserProfileApi"));
            AddBreadcrumb("Edit Api Details", Url.RouteUrl("UserProfileApiEdit", new { id }));

            var model = _apiAuthenticationService.GetApiAuthenticationByUserIdandId(user.Id, id).ToModel();

            return model;
        }
        private StepFourModel PrepareStepFourModel(StepFourModel model = null, User siteOwner = null)
        {
            if (model == null)
            {
                model = new StepFourModel
                            {
                                MailHost = "localhost",
                                MailPort = 21
                            };
            }

            if (siteOwner != null)
            {
                model.AuthenticationMethod = siteOwner.PrimaryAuthMethod.ToString();
                model.DisplayName = siteOwner.DisplayName;
                model.Email = siteOwner.Email;
                model.UserName = siteOwner.UserName;
            }

            return model;
        }
        /// <summary>
        /// Sends a single message to a user
        /// </summary>
        /// <param name="project">The project to send a message about</param>
        /// <param name="messageType">he message type to send</param>
        /// <param name="user">User to send the message to</param>
        /// <param name="authorMessage">Moderator comments to author</param>
        public void ProjectUserMessage(Project project, MessageType messageType, User user, string authorMessage = "")
        {
            string messageUrl = MessageUrl();
            var message = new MessageQueue
            {
                Priority = 10,
                User = user
            };

            switch (messageType)
            {
                case MessageType.ProjectDisputeRejected:

                    message.Subject = _siteSettings.TwitterHashTag + " - Action Dispute Rejected";
                    message.ShortBody = "Your action dispute request has been rejected. " + messageUrl;
                    message.Body = WrapStringInHtml("Your action dispute request - " + project.Name + ", has been rejected, you are still not an owner of this project.") + WrapStringInHtml(authorMessage);

                    break;
                case MessageType.ProjectDisputeApproved:

                    message.Subject = _siteSettings.TwitterHashTag + " - Action Dispute Approved";
                    message.ShortBody = "Your action dispute request has been approved. " + messageUrl;
                    message.Body = WrapStringInHtml("Your action dispute request - " + project.Name + ", has been approved. We have reinstated you as an owner.") + WrapStringInHtml(authorMessage);

                    break;
                case MessageType.ProjectDisputeOwnerRemoved:

                    message.Subject = _siteSettings.TwitterHashTag + " - Action Dispute Owner Removed";
                    message.ShortBody = "You have been removed from - " + project.Name + " due to a dispute." + messageUrl;
                    message.Body = WrapStringInHtml("You have been removed from - " + project.Name + ".") + WrapStringInHtml(authorMessage);

                    break;
            }

            if (!string.IsNullOrEmpty(message.Body))
                InsertMessageQueue(message);
        }
        public void InstallUsers(User siteOwner)
        {
            var siteOwnerRole = new UserRole
            {
                Name = "Site Owner",
                SystemName = SystemUserRoleNames.SiteOwner
            };

            var administratorRole = new UserRole
            {
                Name = "Administrators",
                SystemName = SystemUserRoleNames.Administrators
            };

            var moderatorRole = new UserRole
            {
                Name = "Moderators",
                SystemName = SystemUserRoleNames.Moderators
            };

            var memberRole = new UserRole
            {
                Name = "Members",
                SystemName = SystemUserRoleNames.Members
            };

            var roles = new List<UserRole>
            {
                siteOwnerRole,
                administratorRole,
                moderatorRole,
                memberRole
            };

            // Insert each roles
            foreach (var role in roles)
            {
                role.Active = true;
                role.CreatedDate = DateTime.Now;
                role.IsSystemRole = true;
                _userRoleRepository.Insert(role);
            }

            // Create the site owner
            siteOwner.Active = true;
            siteOwner.CreatedDate = DateTime.Now;
            siteOwner.LastLoginDate = DateTime.Now;
            siteOwner.UserRoles.Add(siteOwnerRole);
            _userRepository.Insert(siteOwner);

            // Login the user
            _authService.SignIn(siteOwner, true);
        }
 public void InstallUserData(User siteOwner, string mailFromDisplayName, string mailFromEmail, string mailHost, int mailPort, string mailUsername, string mailPassword, string twitterAccessToken, string twitterAccessTokenSecret)
 {
     InstallUsers(siteOwner);
     InstallPermissions();
     InstallPages();
     InstallSuccessStories();
     InstallUserSettings(mailFromDisplayName, mailFromEmail, mailHost, mailPort, mailUsername, mailPassword, twitterAccessToken, twitterAccessTokenSecret);
 }
        /// <summary>
        /// Change the owner of a comment
        /// </summary>
        /// <param name="currentUserId">Current user id</param>
        /// <param name="newUser">New user</param>
        public void MigrateCommentOwnership(int currentUserId, User newUser)
        {
            if (currentUserId == 0 || newUser == null)
                return;

            var comments = _commentRepository.Table.Where(x => x.CreatedBy == currentUserId).ToList();

            foreach (var comment in comments)
            {
                comment.Author = newUser;
                comment.CreatedBy = newUser.Id;
            }

            _commentRepository.BulkUpdate(comments);
        }
        /// <summary>
        /// Signs in a new user
        /// </summary>
        /// <param name="user">User entity</param>
        /// <param name="createPersistentCookie">True/false</param>
        public void SignIn(User user, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1,
                user.DisplayName,
                now,
                now.Add(FormsAuthentication.Timeout),
                createPersistentCookie,
                user.Id.ToString(),
                FormsAuthentication.FormsCookiePath
            );

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true,
                Expires = now.Add(FormsAuthentication.Timeout),
                Secure = FormsAuthentication.RequireSSL,
                Path = FormsAuthentication.FormsCookiePath
            };

            if (FormsAuthentication.CookieDomain != null)
                cookie.Domain = FormsAuthentication.CookieDomain;

            _httpContext.Response.Cookies.Add(cookie);
            _cachedUser = user;
        }
        public static User ToEntity(this UserModel model)
        {
            if (model == null)
                return null;

            var entity = new User
            {
                Active = model.Active,
                ContactUsBio = model.ContactUsBio,
                CreatedDate = model.CreatedDate,
                DisplayName = model.DisplayName,
                Email = model.Email,
                EmailDisclosureId = model.EmailDisclosureId,
                EmailDisclosureLevel = model.EmailDisclosureLevel,
                FacebookProfile = model.FacebookProfile,
                Id = model.Id,
                LastLoginDate = model.LastLoginDate,
                ShowOnContactUs = model.ShowOnContactUs,
                Telephone = model.Telephone,
                TelephoneDisclosureId = model.TelephoneDisclosureId,
                TelephoneDisclosureLevel = model.TelephoneDisclosureLevel,
                TwitterProfile = model.TwitterProfile,
                UserName = model.UserName,
                UserRoles = model.UserRoles.Select(ToEntity).ToList(),
                Website = model.Website,
                WebsiteDisclosureId = model.WebsiteDisclosureId,
                WebsiteDisclosureLevel = model.WebsiteDisclosureLevel
            };

            return entity;
        }
        /// <summary>
        /// Change ownership of projects
        /// </summary>
        /// <param name="currentUserId">Current user id</param>
        /// <param name="newUser">New user</param>
        public void MigrateProjectOwnership(int currentUserId, User newUser)
        {
            if (currentUserId == 0 || newUser == null)
                return;

            var createdProjects = _projectRepository.Table.Where(x => x.CreatedBy == currentUserId).ToList();
            foreach (var project in createdProjects)
                project.CreatedBy = newUser.Id;
            _projectRepository.BulkUpdate(createdProjects);

            var volunteeredProjects = _projectRepository.Table.Where(x => x.Owners.Any(o => o.Id == currentUserId) || x.Volunteers.Any(v => v.Id == currentUserId)).ToList();
            foreach (var project in volunteeredProjects)
            {
                var owner = project.Owners.FirstOrDefault(x => x.Id == currentUserId);
                if (owner != null)
                {
                    project.Owners.Remove(owner);
                    if (!project.Owners.Any(x => x.Id == newUser.Id))
                        project.Owners.Add(newUser);
                }

                var volunteer = project.Volunteers.FirstOrDefault(x => x.Id == currentUserId);
                if (volunteer != null)
                {
                    project.Volunteers.Remove(volunteer);
                    if (!project.Volunteers.Any(x => x.Id == newUser.Id))
                        project.Volunteers.Add(newUser);
                }
            }

            _projectRepository.BulkUpdate(volunteeredProjects);
        }
        private UserApiModel PrepareApiProfileModel(User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            AddHomeBreadcrumb();
            AddBreadcrumb("Profile for " + user.DisplayName, Url.RouteUrl("UserProfile", new { userName = user.UserName }));
            AddBreadcrumb("Api Details", Url.RouteUrl("UserProfileApi"));

            var model = new UserApiModel
            {
                CurrentApiAuthentication = _apiAuthenticationService.GetApiAuthenticationByUser(user.Id).Select(x => x.ToModel()).ToList()
            };

            return model;
        }
        /// <summary>
        /// Change the author of success stories
        /// </summary>
        /// <param name="currentUserId"></param>
        /// <param name="newUser"></param>
        public void MigrateSuccessStoryAuthor(int currentUserId, User newUser)
        {
            if (currentUserId == 0 || newUser == null)
                return;

            var stories = _successStoryRepository.Table.Where(x => x.CreatedBy == currentUserId || x.Author.Id == currentUserId).ToList();

            foreach (var story in stories)
            {
                if (story.Author.Id == currentUserId)
                    story.Author = newUser;

                if (story.CreatedBy == currentUserId)
                    story.CreatedBy = newUser.Id;
            }

            _successStoryRepository.BulkUpdate(stories);
        }
        private UserModel PrepareListUserModel(User user)
        {
            var model = user.ToModel();

            if ((user.UserRoles.All(x => x.SystemName != SystemUserRoleNames.SiteOwner) &&
                (user.UserRoles.All(x => x.SystemName != SystemUserRoleNames.Administrators) || _permissionService.Authorize(PermissionProvider.EditAdmins))) ||
                (_workContext.CurrentUser != null && _workContext.CurrentUser.UserRoles.Any(x => x.SystemName == SystemUserRoleNames.SiteOwner)))
            {
                model.Actions.Add(new ModelActionLink
                {
                    Alt = "Edit",
                    Icon = Url.Content("~/Areas/Admin/Content/images/icon-edit.png"),
                    Target = Url.Action("edit", new {id = user.Id})
                });

                if (user.UserRoles.All(x => x.SystemName != SystemUserRoleNames.SiteOwner))
                    model.Actions.Add(new DeleteActionLink(user.Id));
            }

            return model;
        }
        /// <summary>
        /// Unassociates all success stories from a user
        /// </summary>
        /// <param name="userId">User id</param>
        /// /// <param name="newUser">User to replace with</param>
        public void UnassociateSuccessStoryUser(int userId, User newUser = null)
        {
            if (userId == 0)
                return;

            if (newUser == null)
                newUser = _userService.GetSiteOwner();

            var stories = _successStoryRepository.Table.Where(s => s.Author.Id == userId || s.CreatedBy == userId).ToList();

            foreach (var story in stories)
            {
                if (story.CreatedBy == userId)
                    story.CreatedBy = newUser.Id;

                if (story.Author.Id == userId)
                    story.Author = newUser;
            }

            _successStoryRepository.BulkUpdate(stories);
        }
        private UserModel PrepareUserModel(User user)
        {
            var model = user.ToModel();

            model.AvailableDisclosureLevels = _webHelper.GetAllEnumListItems<DisclosureLevel>();
            model.AvailableUserRoles = _userService.GetAllUserRoles(true).Select(x => x.ToModel()).ToList();

            return model;
        }
 public static void Warning(this ILogService logger, string message, Exception exception = null, User user = null)
 {
     FilteredLog(logger, LogLevel.Warning, message, exception, user);
 }