示例#1
0
        private void MarkPostUpOrDown(Post post, MembershipUser postWriter, MembershipUser voter, PostType postType)
        {
            // Check this user is not the post owner
            if (voter.Id != postWriter.Id)
            {
                // Not the same person, now check they haven't voted on this post before
                if (post.Votes.All(x => x.User.Id != LoggedOnUser.Id))
                {
                    // Points to add or subtract to a user
                    var usersPoints = (postType == PostType.Negative) ?
                                      (-SettingsService.GetSettings().PointsDeductedNagativeVote) : (SettingsService.GetSettings().PointsAddedPostiveVote);

                    // Update the users points who wrote the post
                    _membershipUserPointsService.Add(new MembershipUserPoints {
                        Points = usersPoints, User = postWriter
                    });

                    // Update the post with the new vote of the voter
                    var vote = new Vote
                    {
                        Post   = post,
                        User   = voter,
                        Amount = (postType == PostType.Negative) ? (-1) : (1),
                        VotedByMembershipUser = LoggedOnUser,
                        DateVoted             = DateTime.Now
                    };
                    _voteService.Add(vote);

                    // Update the post with the new points amount
                    var newPointTotal = (postType == PostType.Negative) ? (post.VoteCount - 1) : (post.VoteCount + 1);
                    post.VoteCount = newPointTotal;
                }
            }
        }
示例#2
0
 public bool Rule(MembershipUser user)
 {
     // Get all down votes
     var voteService = DependencyResolver.Current.GetService<IVoteService>();
     var downVotes = voteService.GetAllVotesByUser(user.Id).Where(x => x.Amount < 1).ToList();
     return downVotes.Count() >= 10;
 }
示例#3
0
 public static MemberEditViewModel UserToMemberEditViewModel(MembershipUser user)
 {
     var viewModel = new MemberEditViewModel
     {
         IsApproved = user.IsApproved,
         Id = user.Id,
         IsLockedOut = user.IsLockedOut,
         IsBanned = user.IsBanned,
         Roles = user.Roles.Select(x => x.RoleName).ToArray(),
         UserName = user.UserName,
         Age = user.Age,
         Comment = user.Comment,
         Email = user.Email,
         Facebook = user.Facebook,
         Location = user.Location,
         PasswordAnswer = user.PasswordAnswer,
         PasswordQuestion = user.PasswordQuestion,
         Signature = user.Signature,
         Twitter = user.Twitter,
         Website = user.Website,
         DisableEmailNotifications = (user.DisableEmailNotifications == true),
         DisablePosting = (user.DisablePosting == true),
         DisablePrivateMessages = (user.DisablePrivateMessages == true),
         DisableFileUploads = (user.DisableFileUploads == true),
         Avatar = user.Avatar
     };
     return viewModel;
 }
        private void UpdateUserRoles(MVCForum.Domain.DomainModel.MembershipUser user, IEnumerable <string> updatedRoles)
        {
            var updatedRolesSet = new List <MembershipRole>();

            foreach (var roleStr in updatedRoles)
            {
                var alreadyIsRoleForUser = false;
                foreach (var role in user.Roles)
                {
                    if (roleStr == role.RoleName)
                    {
                        // This role for this user is UNchanged
                        updatedRolesSet.Add(role);
                        alreadyIsRoleForUser = true;
                        break;
                    }
                }

                if (!alreadyIsRoleForUser)
                {
                    // This is a new role for this user
                    updatedRolesSet.Add(RoleService.GetRole(roleStr));
                }
            }

            // Replace the roles in the user's collection
            user.Roles.Clear();
            foreach (var role in updatedRolesSet)
            {
                user.Roles.Add(role);
            }
        }
        public IPagedList<PrivateMessageListItem> GetUsersPrivateMessages(int pageIndex, int pageSize, MembershipUser user)
        {
            var query = _context.PrivateMessage
                .AsNoTracking()
                .Include(x => x.UserFrom)
                .Include(x => x.UserTo)
                .Where(x => (x.UserTo.Id == user.Id && x.IsSentMessage != true) || (x.UserFrom.Id == user.Id && x.IsSentMessage == true))
                .Select(x => new PrivateMessageListItem
                {
                    Date = x.DateSent,
                    User = (x.IsSentMessage == true ? x.UserTo : x.UserFrom),
                    HasUnreadMessages = (x.IsSentMessage != true && x.UserFrom.Id != user.Id && (x.IsRead == false))
                })
                .GroupBy(x => x.User.Id)
                .Select(x => x.OrderByDescending(d => d.Date).FirstOrDefault())
                .OrderByDescending(x => x.Date);

            var total = query.Count();

            var results = query
                            .Skip((pageIndex - 1) * pageSize)
                            .Take(pageSize)
                            .ToList();

            // Return a paged list
            return new PagedList<PrivateMessageListItem>(results, pageIndex, pageSize, total);
        }
示例#6
0
        public void AddPost()
        {
            var postRepository = Substitute.For<IPostRepository>();
            var topicRepository = Substitute.For<ITopicRepository>();
            var roleService = Substitute.For<IRoleService>();
            var membershipUserPointsService = Substitute.For<IMembershipUserPointsService>();
            var settingsService = Substitute.For<ISettingsService>();
            settingsService.GetSettings().Returns(new Settings { PointsAddedPerPost = 20 });
            var localisationService = Substitute.For<ILocalizationService>();
            var postService = new PostService(membershipUserPointsService, settingsService, roleService, postRepository, topicRepository, localisationService, _api);

            var category = new Category();
            var role = new MembershipRole{RoleName = "TestRole"};

            var categoryPermissionForRoleSet = new List<CategoryPermissionForRole>
                                                   {
                                                       new CategoryPermissionForRole { Permission = new Permission { Name = AppConstants.PermissionEditPosts }, IsTicked = true},
                                                       new CategoryPermissionForRole { Permission = new Permission { Name = AppConstants.PermissionDenyAccess }, IsTicked = false},
                                                       new CategoryPermissionForRole { Permission = new Permission { Name = AppConstants.PermissionReadOnly  }, IsTicked = false}
                                                   };

            var permissionSet = new PermissionSet(categoryPermissionForRoleSet);
            roleService.GetPermissions(category, role).Returns(permissionSet);

            var topic = new Topic { Name = "Captain America", Category = category};
            var user = new MembershipUser {
                UserName = "******",
                Roles = new List<MembershipRole>{role}
            };

            var newPost = postService.AddNewPost("A test post", topic, user, out permissionSet);

            Assert.AreEqual(newPost.User, user);
            Assert.AreEqual(newPost.Topic, topic);
        }
        //public IPagedList<PrivateMessage> GetPagedSentMessagesByUser(int pageIndex, int pageSize, MembershipUser user)
        //{
        //    var totalCount = _context.PrivateMessage
        //                        .Include(x => x.UserTo)
        //                        .Include(x => x.UserFrom)
        //                        .Count(x => x.UserFrom.Id == user.Id && x.IsSentMessage == true);

        //    // Get the topics using an efficient
        //    var results = _context.PrivateMessage
        //                        .Include(x => x.UserTo)
        //                        .Include(x => x.UserFrom)
        //                        .Where(x => x.UserFrom.Id == user.Id)
        //                        .Where(x => x.IsSentMessage == true)
        //                        .OrderByDescending(x => x.DateSent)
        //                        .Skip((pageIndex - 1) * pageSize)
        //                        .Take(pageSize)
        //                        .ToList();

        //    // Return a paged list
        //    return new PagedList<PrivateMessage>(results, pageIndex, pageSize, totalCount);
        //}

        //public IPagedList<PrivateMessage> GetPagedReceivedMessagesByUser(int pageIndex, int pageSize, MembershipUser user)
        //{


        //    var totalCount = _context.PrivateMessage
        //                        .Include(x => x.UserTo)
        //                        .Include(x => x.UserFrom)                                
        //                        .OrderByDescending(x => x.DateSent)
        //                        .Count(x => (x.UserTo.Id == user.Id || x.UserFrom.Id == user.Id) && x.IsSentMessage != true);

        //    var results = _context.PrivateMessage
        //                        .Include(x => x.UserTo)
        //                        .Include(x => x.UserFrom)
        //                        .OrderByDescending(x => x.DateSent)
        //                        .Where(x => (x.UserTo.Id == user.Id || x.UserFrom.Id == user.Id) && x.IsSentMessage != true)
        //                        .Skip((pageIndex - 1) * pageSize)
        //                        .Take(pageSize)
        //                        .ToList();


        //    // Return a paged list
        //    return new PagedList<PrivateMessage>(results, pageIndex, pageSize, totalCount);
        //}

        public IPagedList<PrivateMessageListItem> GetUsersPrivateMessages(int pageIndex, int pageSize, MembershipUser user)
        {
            //TODO - Need to rework this as it's not very efficient

            // Get all received pms
            var members = user.PrivateMessagesReceived.Where(x => x.IsSentMessage == true).OrderByDescending(x => x.DateSent).DistinctBy(x => x.UserFrom.Id).Select(x => new PrivateMessageListItem
            {
                Date = x.DateSent,
                User = x.UserFrom
            }).ToList();

            // Get all sent pms + ISSent
            var sentToMembers = user.PrivateMessagesSent.Where(x => x.IsSentMessage != true).OrderByDescending(x => x.DateSent).DistinctBy(x => x.UserTo.Id).Select(x => new PrivateMessageListItem
            {
                Date = x.DateSent,
                User = x.UserTo
            }).ToList();

            // Add lists
            members.AddRange(sentToMembers);

            // Get the full amount
            var uniqueMembers = members.OrderByDescending(x => x.Date).DistinctBy(x => x.User.Id).ToList();
            var uniqueMembersCount = uniqueMembers.Count;

            // Now distinct the lists again
            members = uniqueMembers.Skip((pageIndex - 1) * pageSize)
                        .Take(pageSize)
                        .ToList();

            // Return a paged list
            return new PagedList<PrivateMessageListItem>(members, pageIndex, pageSize, uniqueMembersCount);
        }
        public bool Rule(MembershipUser user, IMVCForumAPI api)
        {
            //Post is marked as the answer to a topic - give the post author a badge
            var usersSolutions = api.Post.GetSolutionsWrittenByMember(user.Id);

            return (usersSolutions.Count >= 1);
        }
示例#9
0
        public bool Rule(MembershipUser user)
        {
            //Post is marked as the answer to a topic - give the post author a badge
            var postService = DependencyResolver.Current.GetService<IPostService>();
            var usersSolutions = postService.GetSolutionsByMember(user.Id);

            return (usersSolutions.Count >= 10);
        }
示例#10
0
        /// <summary>
        /// Add a new post
        /// </summary>
        /// <param name="postContent"> </param>
        /// <param name="topic"> </param>
        /// <param name="user"></param>
        /// <param name="permissions"> </param>
        /// <returns>True if post added</returns>
        public Post AddNewPost(string postContent, Topic topic, MembershipUser user, out PermissionSet permissions)
        {
            // Get the permissions for the category that this topic is in
            permissions = _roleService.GetPermissions(topic.Category, UsersRole(user));

            // Check this users role has permission to create a post
            if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked)
            {
                // Throw exception so Ajax caller picks it up
                throw new ApplicationException(_localizationService.GetResourceString("Errors.NoPermission"));
            }

            // Has permission so create the post
            var newPost = new Post
                               {
                                   PostContent = postContent,
                                   User = user,
                                   Topic = topic,
                                   IpAddress = StringUtils.GetUsersIpAddress(),
                                   DateCreated = DateTime.UtcNow,
                                   DateEdited = DateTime.UtcNow
                               };

            // Sort the search field out

            var category = topic.Category;
            if (category.ModeratePosts == true)
            {
                newPost.Pending = true;
            }

            var e = new PostMadeEventArgs { Post = newPost };
            EventManager.Instance.FireBeforePostMade(this, e);

            if (!e.Cancel)
            {
                // create the post
                Add(newPost);

                // Update the users points score and post count for posting
                _membershipUserPointsService.Add(new MembershipUserPoints
                                                     {
                                                         Points = _settingsService.GetSettings().PointsAddedPerPost,
                                                         User = user,
                                                         PointsFor = PointsFor.Post,
                                                         PointsForId = newPost.Id
                                                     });

                // add the last post to the topic
                topic.LastPost = newPost;

                EventManager.Instance.FireAfterPostMade(this, new PostMadeEventArgs { Post = newPost });

                return newPost;
            }

            return newPost;
        }
 public void Delete(MembershipUser user, PointsFor type, Guid referenceId)
 {
     var mp =
         _context.MembershipUserPoints.Where(
             x => x.User.Id == user.Id && x.PointsFor == type && x.PointsForId == referenceId);
     var mpoints = new List<MembershipUserPoints>();
     mpoints.AddRange(mp);
     Delete(mpoints);
 }
 public bool Rule(MembershipUser user)
 {
     var lastPost = user.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();
     if (lastPost != null && lastPost.PostContent.ToLower().Contains("umbraco"))
     {
         return true;
     }
     return false;
 }
 /// <summary>
 /// Return notifications for a specified user and category
 /// </summary>
 /// <param name="user"></param>
 /// <param name="category"></param>
 /// <param name="addTracking"></param>
 /// <returns></returns>
 public IList<CategoryNotification> GetByUserAndCategory(MembershipUser user, Category category, bool addTracking = false)
 {
     var notifications = _context.CategoryNotification
         .Where(x => x.Category.Id == category.Id && x.User.Id == user.Id);
     if (addTracking)
     {
         return notifications.ToList();
     }
     return notifications.AsNoTracking().ToList();
 }
示例#14
0
        public MembershipUser Create(string name)
        {
            var newUser = new MembershipUser
                              {
                                  UserName = name
                              };

            // Id is created by API
            return _api.Member.Create(newUser);
        }
        public PrivateMessageController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService,
            ILocalizationService localizationService, IRoleService roleService, ISettingsService settingsService, IPrivateMessageService privateMessageService,
            IEmailService emailService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _privateMessageService = privateMessageService;
            _emailService = emailService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
        }
 public IList<TagNotification> GetByUserAndTag(MembershipUser user, TopicTag tag, bool addTracking = false)
 {
     var notifications = _context.TagNotification
        .Where(x => x.User.Id == user.Id && x.Tag.Id == tag.Id);
     if (addTracking)
     {
         return notifications.ToList();
     }
     return notifications.AsNoTracking().ToList();
 }
 public IEnumerable<MembershipUserPoints> GetByUser(MembershipUser user, bool removeTracking = true)
 {            
     var users = _context.MembershipUserPoints
             .Where(x => x.User.Id == user.Id);
     if (removeTracking)
     {
         return users.AsNoTracking();    
     }
     return users;
 }
示例#18
0
        private void MarkPostUpOrDown(Post post, MembershipUser postWriter, MembershipUser voter, PostType postType)
        {
            var settings = SettingsService.GetSettings();

            // Check this user is not the post owner
            if (voter.Id != postWriter.Id)
            {
                // Not the same person, now check they haven't voted on this post before
                var votes = post.Votes.Where(x => x.VotedByMembershipUser.Id == LoggedOnReadOnlyUser.Id).ToList();
                if (votes.Any())
                {
                    // Already voted, so delete the vote and remove the points
                    var votesToDelete = new List <Vote>();
                    votesToDelete.AddRange(votes);
                    foreach (var vote in votesToDelete)
                    {
                        _voteService.Delete(vote);
                    }

                    // Update the post with the new points amount
                    var newPointTotal = (postType == PostType.Negative) ? (post.VoteCount + 1) : (post.VoteCount - 1);
                    post.VoteCount = newPointTotal;
                }
                else
                {
                    // Points to add or subtract to a user
                    var usersPoints = (postType == PostType.Negative) ? (-settings.PointsDeductedNagativeVote) : (settings.PointsAddedPostiveVote);

                    // Update the post with the new vote of the voter
                    var vote = new Vote
                    {
                        Post   = post,
                        User   = postWriter,
                        Amount = (postType == PostType.Negative) ? (-1) : (1),
                        VotedByMembershipUser = voter,
                        DateVoted             = DateTime.UtcNow
                    };
                    _voteService.Add(vote);

                    // Update the users points who wrote the post
                    _membershipUserPointsService.Add(new MembershipUserPoints
                    {
                        Points      = usersPoints,
                        User        = postWriter,
                        PointsFor   = PointsFor.Vote,
                        PointsForId = vote.Id
                    });

                    // Update the post with the new points amount
                    var newPointTotal = (postType == PostType.Negative) ? (post.VoteCount - 1) : (post.VoteCount + 1);
                    post.VoteCount = newPointTotal;
                }
            }
        }
        public void MemberJoinedActivityAdd()
        {
            const string guidStr = "515b7240-3be1-43d4-8846-c0b589cd1cd2";
            var activityRepository = Substitute.For<IActivityRepository>();
            IActivityService activityService = new ActivityService(activityRepository, _badgeRepository, _membershipRepository, _loggingService);
            var user = new MembershipUser { Id = new Guid(guidStr), UserName = "******" };

            activityService.MemberJoined(user);

            activityRepository.Received().Add((Arg.Is<Activity>(x => x.Data == MemberJoinedActivity.KeyUserId + "=" + guidStr)));
        }
        public bool Rule(MembershipUser user)
        {
            //Post is marked as the answer to a topic - give the post author a badge

            // Get all categories as we want to check all the members solutions, even across
            // categories that he no longer is allowed to access
            var cats = _categoryService.GetAll();
            var usersSolutions = _postService.GetSolutionsByMember(user.Id, cats);

            return (usersSolutions.Count >= 1);
        }
示例#21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="loggingService"> </param>
        /// <param name="unitOfWorkManager"> </param>
        /// <param name="membershipService"></param>
        /// <param name="localizationService"> </param>
        /// <param name="settingsService"> </param>
        public BaseAdminController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, ILocalizationService localizationService, ISettingsService settingsService)
        {
            UnitOfWorkManager = unitOfWorkManager;
            MembershipService = membershipService;
            LocalizationService = localizationService;
            LocalizationService.CurrentLanguage = LocalizationService.DefaultLanguage;
            SettingsService = settingsService;
            LoggingService = loggingService;

            LoggedOnReadOnlyUser = MembershipService.GetUser(System.Web.HttpContext.Current.User.Identity.Name, true);
        }
示例#22
0
        public HomeController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IActivityService activityService, IMembershipService membershipService,
            ITopicService topicService, ILocalizationService localizationService, IRoleService roleService,
            ISettingsService settingsService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _topicService = topicService;
            _activityService = activityService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole = LoggedOnUser == null ? RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
示例#23
0
        public UploadController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager,
            IMembershipService membershipService, ILocalizationService localizationService, IRoleService roleService, ISettingsService settingsService,
            IPostService postService, IUploadedFileService uploadedFileService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _postService = postService;
            _uploadedFileService = uploadedFileService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole = LoggedOnUser == null ? RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
示例#24
0
        public PollController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, 
            ILocalizationService localizationService, IRoleService roleService, ISettingsService settingsService, IPollService pollService, IPollVoteService pollVoteService, 
            IPollAnswerService pollAnswerService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _pollService = pollService;
            _pollAnswerService = pollAnswerService;
            _pollVoteService = pollVoteService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
        }
示例#25
0
        //private readonly MembershipUser _loggedInUser;
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="loggingService"> </param>
        /// <param name="unitOfWorkManager"> </param>
        /// <param name="membershipService"></param>
        /// <param name="localizationService"> </param>
        /// <param name="roleService"> </param>
        /// <param name="settingsService"> </param>
        public BaseController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, ILocalizationService localizationService, IRoleService roleService, ISettingsService settingsService)
        {
            UnitOfWorkManager = unitOfWorkManager;
            MembershipService = membershipService;
            LocalizationService = localizationService;
            RoleService = roleService;
            SettingsService = settingsService;
            LoggingService = loggingService;

            LoggedOnReadOnlyUser = UserIsAuthenticated ? MembershipService.GetUser(Username, true) : null;
            UsersRole = LoggedOnReadOnlyUser == null ? RoleService.GetRole(AppConstants.GuestRoleName, true) : LoggedOnReadOnlyUser.Roles.FirstOrDefault();
        }
示例#26
0
 public static SingleMemberListViewModel UserToSingleMemberListViewModel(MembershipUser user)
 {
     var viewModel = new SingleMemberListViewModel
     {
         IsApproved = user.IsApproved,
         Id = user.Id,
         IsLockedOut = user.IsLockedOut,
         Roles = user.Roles.Select(x => x.RoleName).ToArray(),
         UserName = user.UserName
     };
     return viewModel;
 }
示例#27
0
        public EmailController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, 
            ILocalizationService localizationService, IRoleService roleService, ISettingsService settingsService,
            ITopicNotificationService topicNotificationService, ICategoryNotificationService categoryNotificationService, ICategoryService categoryService,
            ITopicService topicService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _topicNotificationService = topicNotificationService;
            _categoryNotificationService = categoryNotificationService;
            _categoryService = categoryService;
            _topicService = topicService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
        }
示例#28
0
        /// <summary>
        /// Add a new post
        /// </summary>
        /// <param name="postContent"> </param>
        /// <param name="topic"> </param>
        /// <param name="user"></param>
        /// <param name="permissions"> </param>
        /// <returns>True if post added</returns>
        public Post AddNewPost(string postContent, Topic topic, MembershipUser user, out PermissionSet permissions)
        {
            // Get the permissions for the category that this topic is in
            permissions = _roleService.GetPermissions(topic.Category, UsersRole(user));

            // Check this users role has permission to create a post
            if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked)
            {
                // Throw exception so Ajax caller picks it up
                throw new ApplicationException(_localizationService.GetResourceString("Errors.NoPermission"));
            }

            // Has permission so create the post
            var newPost = new Post
                               {
                                   PostContent = postContent,
                                   User = user,
                                   Topic = topic,
                                   IpAddress = StringUtils.GetUsersIpAddress()
                               };

            newPost = SanitizePost(newPost);

            var e = new PostMadeEventArgs { Post = newPost, Api = _api };
            EventManager.Instance.FireBeforePostMade(this, e);

            if (!e.Cancel)
            {
                // create the post
                Add(newPost);

                // Update the users points score and post count for posting
                _membershipUserPointsService.Add(new MembershipUserPoints
                                                     {
                                                         Points = _settingsService.GetSettings().PointsAddedPerPost,
                                                         User = user
                                                     });

                // add the last post to the topic
                topic.LastPost = newPost;

                // Removed as its updated via the commit
                //_topicRepository.Update(topic);

                EventManager.Instance.FireAfterPostMade(this, new PostMadeEventArgs { Post = newPost, Api = _api });

                return newPost;
            }

            return newPost;
        }
示例#29
0
        public MembersController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, ILocalizationService localizationService,
            IRoleService roleService, ISettingsService settingsService, IPostService postService, IReportService reportService, IEmailService emailService, IPrivateMessageService privateMessageService, IBannedEmailService bannedEmailService, IBannedWordService bannedWordService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _postService = postService;
            _reportService = reportService;
            _emailService = emailService;
            _privateMessageService = privateMessageService;
            _bannedEmailService = bannedEmailService;
            _bannedWordService = bannedWordService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole = LoggedOnUser == null ? RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
示例#30
0
        public void BadgeAwardedActivityAdd()
        {
            const string guidStrBadge = "515b7240-3be1-43d4-8846-c0b589cd1cd2";
            const string guidStrUser = "******";

            var activityRepository = Substitute.For<IActivityRepository>();
            IActivityService activityService = new ActivityService(activityRepository, _badgeRepository, _membershipRepository, _loggingService);
            var user = new MembershipUser { Id = new Guid(guidStrUser), UserName = "******" };
            var badge = new Badge { Id = new Guid(guidStrBadge) };

            activityService.BadgeAwarded(badge, user, DateTime.UtcNow);

            activityRepository.Received().Add((Arg.Is<Activity>(x => x.Data == BadgeActivity.KeyBadgeId + "=" + guidStrBadge + "," + BadgeActivity.KeyUserId + "=" + guidStrUser)));
        }
示例#31
0
 /// <summary>
 /// Maps the posts for a specific topic
 /// </summary>
 /// <param name="posts"></param>
 /// <param name="votes"></param>
 /// <param name="permission"></param>
 /// <param name="topic"></param>
 /// <param name="loggedOnUser"></param>
 /// <param name="settings"></param>
 /// <param name="favourites"></param>
 /// <returns></returns>
 public static List<PostViewModel> CreatePostViewModels(IEnumerable<Post> posts, List<Vote> votes, PermissionSet permission, Topic topic, MembershipUser loggedOnUser, Settings settings, List<Favourite> favourites)
 {
     var viewModels = new List<PostViewModel>();
     var groupedVotes = votes.ToLookup(x => x.Post.Id);
     var groupedFavourites = favourites.ToLookup(x => x.Post.Id);
     foreach (var post in posts)
     {
         var id = post.Id;
         var postVotes = (groupedVotes.Contains(id) ? groupedVotes[id].ToList() : new List<Vote>());
         var postFavs = (groupedFavourites.Contains(id) ? groupedFavourites[id].ToList() : new List<Favourite>());
         viewModels.Add(CreatePostViewModel(post, postVotes, permission, topic, loggedOnUser, settings, postFavs));
     }
     return viewModels;
 }
        private bool ProcessSocialLogonUser(MembershipUser user, bool doCommit)
        {
            // Secondly see if the email is banned
            if (_bannedEmailService.EmailIsBanned(user.Email))
            {
                doCommit = false;
                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                {
                    Message = LocalizationService.GetResourceString("Error.EmailIsBanned"),
                    MessageType = GenericMessages.error
                };
            }
            else
            {
                // Check not already someone with that user name, if so append count
                var exists = MembershipService.GetUser(user.UserName);
                if (exists != null)
                {
                    var howMany = MembershipService.SearchMembers(user.UserName, int.MaxValue);
                    user.UserName = string.Format("{0} ({1})", user.UserName, howMany != null ? howMany.Count : 1);
                }

                // Now check settings, see if users need to be manually authorised
                var manuallyAuthoriseMembers = SettingsService.GetSettings().ManuallyAuthoriseNewMembers;
                var memberEmailAuthorisationNeeded = SettingsService.GetSettings().NewMemberEmailConfirmation ?? false;
                if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded)
                {
                    user.IsApproved = false;
                }

                var createStatus = MembershipService.CreateUser(user);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    doCommit = false;
                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message = MembershipService.ErrorCodeToString(createStatus),
                        MessageType = GenericMessages.error
                    };
                }
                else
                {
                    // Set the view bag message here
                    SetRegisterViewBagMessage(manuallyAuthoriseMembers, memberEmailAuthorisationNeeded, user);
                }
            }

            return doCommit;
        }
示例#33
0
        public SearchController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager,
            IMembershipService membershipService, ILocalizationService localizationService,
            IRoleService roleService, ISettingsService settingsService,
            IPostService postService, ITopicService topicService, IVoteService voteService, IFavouriteService favouriteService, ICategoryService categoryService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _postService = postService;
            _topicsService = topicService;
            _voteService = voteService;
            _favouriteService = favouriteService;
            _categoryService = categoryService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole = LoggedOnUser == null ? RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
示例#34
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="loggingService"> </param>
        /// <param name="unitOfWorkManager"> </param>
        /// <param name="membershipService"></param>
        /// <param name="localizationService"> </param>
        /// <param name="roleService"> </param>
        /// <param name="settingsService"> </param>
        public BaseController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, ILocalizationService localizationService, IRoleService roleService, ISettingsService settingsService)
        {
            UnitOfWorkManager   = unitOfWorkManager;
            MembershipService   = membershipService;
            LocalizationService = localizationService;
            RoleService         = roleService;
            SettingsService     = settingsService;
            LoggingService      = loggingService;

            using (UnitOfWorkManager.NewUnitOfWork())
            {
                LoggedOnReadOnlyUser = UserIsAuthenticated ? MembershipService.GetUser(Username, true) : null;
                UsersRole            = LoggedOnReadOnlyUser == null?RoleService.GetRole(AppConstants.GuestRoleName, true) : LoggedOnReadOnlyUser.Roles.FirstOrDefault();
            }
        }
示例#35
0
        public VoteController(ILoggingService loggingService,
                              IUnitOfWorkManager unitOfWorkManager,
                              IMembershipService membershipService,
                              ILocalizationService localizationService,
                              IRoleService roleService,
                              IPostService postService,
                              IVoteService voteService,
                              ISettingsService settingsService,
                              ITopicService topicService,
                              IMembershipUserPointsService membershipUserPointsService,
                              IBadgeService badgeService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _postService  = postService;
            _voteService  = voteService;
            _topicService = topicService;
            _membershipUserPointsService = membershipUserPointsService;
            _badgeService = badgeService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
        }
示例#36
0
        public TopicController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, IRoleService roleService, ITopicService topicService, IPostService postService,
                               ICategoryService categoryService, ILocalizationService localizationService, ISettingsService settingsService, ITopicTagService topicTagService, IMembershipUserPointsService membershipUserPointsService,
                               ICategoryNotificationService categoryNotificationService, IEmailService emailService, ITopicNotificationService topicNotificationService, ILuceneService luceneService, IPollService pollService,
                               IPollAnswerService pollAnswerService, IBannedWordService bannedWordService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _topicService                = topicService;
            _postService                 = postService;
            _categoryService             = categoryService;
            _topicTagService             = topicTagService;
            _membershipUserPointsService = membershipUserPointsService;
            _categoryNotificationService = categoryNotificationService;
            _emailService                = emailService;
            _topicNotificationService    = topicNotificationService;
            _luceneService               = luceneService;
            _pollService                 = pollService;
            _pollAnswerService           = pollAnswerService;
            _bannedWordService           = bannedWordService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole    = LoggedOnUser == null?RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
示例#37
0
        /// <summary>
        /// Take a set of role names and update a user's collection of roles accordingly
        /// </summary>
        /// <param name="user"></param>
        /// <param name="updatedRoles"></param>
        private void UpdateUserRoles(MembershipUser user, IEnumerable <string> updatedRoles)
        {
            // ---------------------------------------------------------------------
            // IMPORTANT - If you call this it MUST be within a unit of work
            // ---------------------------------------------------------------------

            // Not done in automapper to avoid handling services in the mapper
            var updatedRolesSet = new List <MembershipRole>();

            foreach (var roleStr in updatedRoles)
            {
                var alreadyIsRoleForUser = false;
                foreach (var role in user.Roles)
                {
                    if (roleStr == role.RoleName)
                    {
                        // This role for this user is UNchanged
                        updatedRolesSet.Add(role);
                        alreadyIsRoleForUser = true;
                        break;
                    }
                }

                if (!alreadyIsRoleForUser)
                {
                    // This is a new role for this user
                    updatedRolesSet.Add(_roleService.GetRole(roleStr));
                }
            }

            // Replace the roles in the user's collection
            user.Roles.Clear();
            foreach (var role in updatedRolesSet)
            {
                user.Roles.Add(role);
            }
        }
示例#38
0
        private void DeleteUsersPostsPollsVotesAndPoints(MembershipUser user, IUnitOfWork unitOfWork)
        {
            // Delete all file uploads
            var files     = _uploadedFileService.GetAllByUser(user.Id);
            var filesList = new List <UploadedFile>();

            filesList.AddRange(files);
            foreach (var file in filesList)
            {
                // store the file path as we'll need it to delete on the file system
                var filePath = file.FilePath;

                // Now delete it
                _uploadedFileService.Delete(file);

                // And finally delete from the file system
                System.IO.File.Delete(Server.MapPath(filePath));
            }

            // Delete all posts
            var posts    = user.Posts;
            var postList = new List <Post>();

            postList.AddRange(posts);
            foreach (var post in postList)
            {
                post.Files.Clear();
                _postService.Delete(post);
            }

            unitOfWork.SaveChanges();

            // Also clear their poll votes
            var userPollVotes = user.PollVotes;

            if (userPollVotes.Any())
            {
                var pollList = new List <PollVote>();
                pollList.AddRange(userPollVotes);
                foreach (var vote in pollList)
                {
                    vote.User = null;
                    _pollVoteService.Delete(vote);
                }
                user.PollVotes.Clear();
            }

            unitOfWork.SaveChanges();


            // Also clear their polls
            var userPolls = user.Polls;

            if (userPolls.Any())
            {
                var polls = new List <Poll>();
                polls.AddRange(userPolls);
                foreach (var poll in polls)
                {
                    //Delete the poll answers
                    var pollAnswers = poll.PollAnswers;
                    if (pollAnswers.Any())
                    {
                        var pollAnswersList = new List <PollAnswer>();
                        pollAnswersList.AddRange(pollAnswers);
                        foreach (var answer in pollAnswersList)
                        {
                            answer.Poll = null;
                            _pollAnswerService.Delete(answer);
                        }
                    }

                    poll.PollAnswers.Clear();
                    poll.User = null;
                    _pollService.Delete(poll);
                }
                user.Polls.Clear();
            }

            unitOfWork.SaveChanges();

            // Delete all topics
            var topics    = user.Topics;
            var topicList = new List <Topic>();

            topicList.AddRange(topics);
            foreach (var topic in topicList)
            {
                _topicService.Delete(topic);
            }

            // Also clear their points
            var userPoints = user.Points;

            if (userPoints.Any())
            {
                var pointsList = new List <MembershipUserPoints>();
                pointsList.AddRange(userPoints);
                foreach (var point in pointsList)
                {
                    point.User = null;
                    _membershipUserPointsService.Delete(point);
                }
                user.Points.Clear();
            }

            unitOfWork.SaveChanges();

            // Now clear all activities for this user
            var usersActivities = _activityService.GetDataFieldByGuid(user.Id);

            _activityService.Delete(usersActivities.ToList());
        }
        private HttpResponseMessage MemberRegisterLogic(MemberAddViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var userToSave = new MVCForum.Domain.DomainModel.MembershipUser
                {
                    UserName    = _bannedWordService.SanitiseBannedWords(userModel.UserName),
                    Email       = userModel.Email,
                    Password    = userModel.Password,
                    IsApproved  = userModel.IsApproved,
                    Comment     = userModel.Comment,
                    UniversalId = userModel.UniversalId
                };

                var createStatus = _membershipService.CreateUser(userToSave);
                if (createStatus != MVCForum.Domain.DomainModel.MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, _membershipService.ErrorCodeToString(createStatus));
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }
                else
                {
                    // See if this is a social login and we have their profile pic
                    if (!string.IsNullOrWhiteSpace(userModel.SocialProfileImageUrl))
                    {
                        // We have an image url - Need to save it to their profile
                        var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl);

                        // Set upload directory - Create if it doesn't exist
                        var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.UploadFolderPath, userToSave.Id));
                        if (!Directory.Exists(uploadFolderPath))
                        {
                            Directory.CreateDirectory(uploadFolderPath);
                        }

                        // Get the file name
                        var fileName = Path.GetFileName(userModel.SocialProfileImageUrl);

                        // Create a HttpPostedFileBase image from the C# Image
                        using (var stream = new MemoryStream())
                        {
                            image.Save(stream, ImageFormat.Jpeg);
                            stream.Position = 0;
                            HttpPostedFileBase formattedImage = new MemoryFile(stream, "image/jpeg", fileName);

                            // Upload the file
                            var uploadResult = AppHelpers.UploadFile(formattedImage, uploadFolderPath, LocalizationService);

                            // Don't throw error if problem saving avatar, just don't save it.
                            if (uploadResult.UploadSuccessful)
                            {
                                userToSave.Avatar = uploadResult.UploadedFileName;
                            }
                        }
                    }

                    // Store access token for social media account in case we want to do anything with it
                    if (userModel.LoginType == LoginType.Facebook)
                    {
                        userToSave.FacebookAccessToken = userModel.UserAccessToken;
                    }
                    if (userModel.LoginType == LoginType.Google)
                    {
                        userToSave.GoogleAccessToken = userModel.UserAccessToken;
                    }

                    if (userModel.Roles != null && userModel.Roles.Any())
                    {
                        UpdateUserRoles(userToSave, userModel.Roles);
                    }

                    try
                    {
                        userToSave.IsApproved = userModel.IsApproved;
                        unitOfWork.Commit();
                        return(Request.CreateResponse(HttpStatusCode.OK, userToSave.Id));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                    }
                }
            }
        }