public IList<CategoryPermissionForRole> GetCategoryRow(MembershipRole role, Category cat)
 {
     return _context.CategoryPermissionForRole
         .Where(x => x.Category.Id == cat.Id &&
                     x.MembershipRole.Id == role.Id)
                     .ToList();
 }
Пример #2
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);
        }
Пример #3
0
        public void Delete_Check_In_Use_By()
        {
            var roleRepository = Substitute.For<IRoleRepository>();
            var categoryPermissionForRoleRepository = Substitute.For<ICategoryPermissionForRoleRepository>();
            var permissionRepository = Substitute.For<IPermissionRepository>();
            var roleService = new RoleService(roleRepository, categoryPermissionForRoleRepository, permissionRepository);

            var role = new MembershipRole
            {
                Users = new List<MembershipUser>
                                           {
                                               new MembershipUser {UserName = "******"},
                                               new MembershipUser {UserName = "******"}
                                           },
                RoleName = "Role Name"
            };

            try
            {
                roleService.Delete(role);
            }
            catch (InUseUnableToDeleteException ex)
            {
                Assert.IsTrue(ex.BlockingEntities.Any());
            }
        }
Пример #4
0
 public static MembershipRole RoleViewModelToRole(RoleViewModel roleViewModel)
 {
     var viewModel = new MembershipRole
     {
         RoleName = roleViewModel.RoleName
     };
     return viewModel;
 }
Пример #5
0
 public void Update(MembershipRole item)
 {
     // Check there's not an object with same identifier already in context
     if (_context.MembershipRole.Local.Select(x => x.Id == item.Id).Any())
     {
         throw new ApplicationException("Object already exists in context - you do not need to call Update. Save occurs on Commit");
     }
     _context.Entry(item).State = EntityState.Modified; 
 }
Пример #6
0
 public static RoleViewModel RoleToRoleViewModel(MembershipRole role)
 {
     var viewModel = new RoleViewModel
     {
         Id = role.Id,
         RoleName = role.RoleName
     };
     return viewModel;
 }
 /// <summary>
 /// Returns a row with the permission and CPFR
 /// </summary>
 /// <param name="role"></param>
 /// <param name="cat"></param>
 /// <returns></returns>
 public Dictionary<Permission, CategoryPermissionForRole> GetCategoryRow(MembershipRole role, Category cat)
 {
     var catRowList = _context.CategoryPermissionForRole
                     .Include(x => x.MembershipRole)
                     .Include(x => x.Category)
                     .AsNoTracking()
                     .Where(x => x.Category.Id == cat.Id &&
                                 x.MembershipRole.Id == role.Id)
                                 .ToList();
     return catRowList.ToDictionary(catRow => catRow.Permission);
 }
Пример #8
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();
        }
Пример #9
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();
        }
Пример #10
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();
        }
Пример #11
0
 /// <summary>
 /// Return allowed categories based on the users role
 /// </summary>
 /// <param name="role"></param>
 /// <returns></returns>
 public IEnumerable<Category> GetAllowedCategories(MembershipRole role)
 {
     var filteredCats = new List<Category>();
     var allCats = _categoryRepository.GetAll().ToList();
     foreach (var category in allCats)
     {
         var permissionSet = _roleService.GetPermissions(category, role);
         if (!permissionSet[AppConstants.PermissionDenyAccess].IsTicked)
         {
             filteredCats.Add(category);
         }
     }
     return filteredCats;
 }
Пример #12
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();
        }
Пример #13
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();
        }
Пример #14
0
        public void Delete_Exception_If_Role_Has_Multiple_Users()
        {
            var roleRepository = Substitute.For<IRoleRepository>();
            var categoryPermissionForRoleRepository = Substitute.For<ICategoryPermissionForRoleRepository>();
            var permissionRepository = Substitute.For<IPermissionRepository>();
            var roleService = new RoleService(roleRepository, categoryPermissionForRoleRepository, permissionRepository);

            var role = new MembershipRole
                           {
                               Users = new List<MembershipUser>
                                           {
                                               new MembershipUser {UserName = "******"},
                                               new MembershipUser {UserName = "******"}
                                           },
                               RoleName = "Role Name"
                           };

            roleService.Delete(role);
        }
Пример #15
0
        public PostController(ILoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, IMembershipService membershipService, 
            ILocalizationService localizationService, IRoleService roleService, ITopicService topicService, IPostService postService, 
            ISettingsService settingsService, ICategoryService categoryService, ITopicTagService topicTagService, 
            ITopicNotificationService topicNotificationService, IEmailService emailService, IReportService reportService, ILuceneService luceneService, IPollAnswerService pollAnswerService, 
            IPollService pollService, IBannedWordService bannedWordService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _topicService = topicService;
            _postService = postService;
            _categoryService = categoryService;
            _topicTagService = topicTagService;
            _topicNotificationService = topicNotificationService;
            _emailService = emailService;
            _reportService = reportService;
            _luceneService = luceneService;
            _pollAnswerService = pollAnswerService;
            _pollService = pollService;
            _bannedWordService = bannedWordService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole = LoggedOnUser == null ? RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
Пример #16
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, IPollService pollService,
            IPollAnswerService pollAnswerService, IBannedWordService bannedWordService, IVoteService voteService, IFavouriteService favouriteService, IUploadedFileService uploadedFileService)
            : base(loggingService, unitOfWorkManager, membershipService, localizationService, roleService, settingsService)
        {
            _topicService = topicService;
            _postService = postService;
            _categoryService = categoryService;
            _topicTagService = topicTagService;
            _membershipUserPointsService = membershipUserPointsService;
            _categoryNotificationService = categoryNotificationService;
            _emailService = emailService;
            _topicNotificationService = topicNotificationService;
            _pollService = pollService;
            _pollAnswerService = pollAnswerService;
            _bannedWordService = bannedWordService;
            _voteService = voteService;
            _favouriteService = favouriteService;
            _uploadedFileService = uploadedFileService;

            LoggedOnUser = UserIsAuthenticated ? MembershipService.GetUser(Username) : null;
            UsersRole = LoggedOnUser == null ? RoleService.GetRole(AppConstants.GuestRoleName) : LoggedOnUser.Roles.FirstOrDefault();
        }
Пример #17
0
        /// <summary>
        /// Delete a role
        /// </summary>
        /// <param name="role"></param>
        public void Delete(MembershipRole role)
        {
            // Check if anyone else if using this role
                var okToDelete = role.Users.Count == 0;

                if (okToDelete)
                {
                        // Get any categorypermissionforoles and delete these first
                        var rolesToDelete = _categoryPermissionForRoleRepository.GetByRole(role.Id);

                        foreach (var categoryPermissionForRole in rolesToDelete)
                        {
                            _categoryPermissionForRoleRepository.Delete(categoryPermissionForRole);
                        }

                        _roleRepository.Delete(role);
                }
                else
                {
                    var inUseBy = new List<Entity>();
                    inUseBy.AddRange(role.Users);
                    throw new InUseUnableToDeleteException(inUseBy);
                }
        }
Пример #18
0
        /// <summary>
        /// Get permissions for roles other than those specially treated in this class
        /// </summary>
        /// <param name="category"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        private PermissionSet GetOtherPermissions(Category category, MembershipRole role)
        {
            // Get all permissions
                    var permissionList = _permissionRepository.GetAll();

                    // Get the known permissions for this role and category
                    var categoryRow = _categoryPermissionForRoleRepository.GetCategoryRow(role, category);
                    var categoryRowPermissions = categoryRow.ToDictionary(catRow => catRow.Permission);

                    // Load up the results with the permisions for this role / cartegory. A null entry for a permissions results in a new
                    // record with a false value
                    var permissions = new List<CategoryPermissionForRole>();
                    foreach (var permission in permissionList)
                    {
                        permissions.Add(categoryRowPermissions.ContainsKey(permission)
                                            ? categoryRowPermissions[permission]
                                            : new CategoryPermissionForRole { Category = category, MembershipRole = role, IsTicked = false, Permission = permission });
                    }

                    var permissionSet = new PermissionSet(permissions);

            return permissionSet;
        }
Пример #19
0
 private List<Category> GetAllowedCategoriesCode(MembershipRole role, string actionType)
 {
     var filteredCats = new List<Category>();
     var allCats = GetAll();
     foreach (var category in allCats)
     {
         var permissionSet = _roleService.GetPermissions(category, role);
         if (!permissionSet[actionType].IsTicked)
         {
             filteredCats.Add(category);
         }
     }
     return filteredCats;
 }
Пример #20
0
 public List<Category> GetAllowedCategories(MembershipRole role, string actionType)
 {
     if (HttpContext.Current != null)
     {
         // Store per request
         var key = string.Concat("allowed-categories", role.Id, actionType);
         if (!HttpContext.Current.Items.Contains(key))
         {
             HttpContext.Current.Items.Add(key, GetAllowedCategoriesCode(role, actionType));
         }
         return (List<Category>)HttpContext.Current.Items[key];
     }
     return GetAllowedCategoriesCode(role, actionType);
 }
Пример #21
0
 /// <summary>
 /// Return allowed categories based on the users role
 /// </summary>
 /// <param name="role"></param>
 /// <returns></returns>
 public List<Category> GetAllowedCategories(MembershipRole role)
 {
     return GetAllowedCategories(role, AppConstants.PermissionDenyAccess);
 }
Пример #22
0
        private InstallerResult CreateInitialData()
        {
            var installerResult = new InstallerResult { Successful = true, Message = "Congratulations, MVC Forum has installed successfully" };

            // I think this is all I need to call to kick EF into life
            //EFCachingProviderConfiguration.DefaultCache = new AspNetCache();
            //EFCachingProviderConfiguration.DefaultCachingPolicy = CachingPolicy.CacheAll;

            // Now setup the services as we can't do it in the constructor
            InitialiseServices();

            // First UOW to create the data needed for other saves
            using (var unitOfWork = _UnitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    // Check if category exists or not, we only do a single check for the first object within this
                    // UOW because, if anything failed inside. Everything else would be rolled back to because of the 
                    // transaction
                    const string exampleCatName = "Example Category";
                    if (_categoryService.GetAll().FirstOrDefault(x => x.Name == exampleCatName) == null)
                    {
                        // Doesn't exist so add the example category
                        var exampleCat = new Category { Name = exampleCatName, ModeratePosts = false, ModerateTopics = false};
                        _categoryService.Add(exampleCat);

                        // Add the default roles
                        var standardRole = new MembershipRole { RoleName = "Standard Members" };
                        var guestRole = new MembershipRole { RoleName = "Guest" };
                        var moderatorRole = new MembershipRole { RoleName = "Moderator" };
                        var adminRole = new MembershipRole { RoleName = "Admin" };
                        _roleService.CreateRole(standardRole);
                        _roleService.CreateRole(guestRole);
                        _roleService.CreateRole(moderatorRole);
                        _roleService.CreateRole(adminRole);

                        unitOfWork.Commit();
                    }

                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    installerResult.Exception = ex.InnerException;
                    installerResult.Message = "Error creating the initial data >> Category & Roles";
                    installerResult.Successful = false;
                    return installerResult;
                }
            }

            // Add / Update the default language strings
            installerResult = AddOrUpdateTheDefaultLanguageStrings(installerResult);
            if (!installerResult.Successful)
            {
                return installerResult;
            }   

            // Now we have saved the above we can create the rest of the data
            using (var unitOfWork = _UnitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    // if the settings already exist then do nothing
                    if (_settingsService.GetSettings(false) == null)
                    {
                        // Get the default language
                        var startingLanguage = _localizationService.GetLanguageByName("en-GB");

                        // Get the Standard Members role
                        var startingRole = _roleService.GetRole("Standard Members");

                        // create the settings
                        var settings = new Settings
                        {
                            ForumName = "MVC Forum",
                            ForumUrl = "http://www.mydomain.com",
                            IsClosed = false,
                            EnableRSSFeeds = true,
                            DisplayEditedBy = true,
                            EnablePostFileAttachments = false,
                            EnableMarkAsSolution = true,
                            EnableSpamReporting = true,
                            EnableMemberReporting = true,
                            EnableEmailSubscriptions = true,
                            ManuallyAuthoriseNewMembers = false,
                            EmailAdminOnNewMemberSignUp = true,
                            TopicsPerPage = 20,
                            PostsPerPage = 20,
                            EnablePrivateMessages = true,
                            MaxPrivateMessagesPerMember = 50,
                            PrivateMessageFloodControl = 1,
                            EnableSignatures = false,
                            EnablePoints = true,
                            PointsAllowedToVoteAmount = 1,
                            PointsAddedPerPost = 1,
                            PointsAddedForSolution = 4,
                            PointsDeductedNagativeVote = 2,
                            AdminEmailAddress = "*****@*****.**",
                            NotificationReplyEmail = "*****@*****.**",
                            SMTPEnableSSL = false,
                            Theme = "Metro",
                            NewMemberStartingRole = startingRole,
                            DefaultLanguage = startingLanguage,
                            ActivitiesPerPage = 20,
                            EnableAkisment = false,
                            EnableSocialLogins = false,
                            EnablePolls = true
                        };
                        _settingsService.Add(settings);

                        unitOfWork.Commit();
                    }
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    installerResult.Exception = ex.InnerException;
                    installerResult.Message = "Error creating the initial data >> Settings";
                    installerResult.Successful = false;
                    return installerResult;
                }
            }


            // Now we have saved the above we can create the rest of the data
            using (var unitOfWork = _UnitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    // If the admin user exists then don't do anything else
                    if (_membershipService.GetUser("admin") == null)
                    {
                        // Set up the initial permissions
                        var readOnly = new Permission { Name = "Read Only" };
                        var deletePosts = new Permission { Name = "Delete Posts" };
                        var editPosts = new Permission { Name = "Edit Posts" };
                        var stickyTopics = new Permission { Name = "Sticky Topics" };
                        var lockTopics = new Permission { Name = "Lock Topics" };
                        var voteInPolls = new Permission { Name = "Vote In Polls" };
                        var createPolls = new Permission { Name = "Create Polls" };
                        var createTopics = new Permission { Name = "Create Topics" };
                        var attachFiles = new Permission { Name = "Attach Files" };
                        var denyAccess = new Permission { Name = "Deny Access" };

                        _permissionService.Add(readOnly);
                        _permissionService.Add(deletePosts);
                        _permissionService.Add(editPosts);
                        _permissionService.Add(stickyTopics);
                        _permissionService.Add(lockTopics);
                        _permissionService.Add(voteInPolls);
                        _permissionService.Add(createPolls);
                        _permissionService.Add(createTopics);
                        _permissionService.Add(attachFiles);
                        _permissionService.Add(denyAccess);

                        // create the admin user and put him in the admin role
                        var admin = new MembershipUser
                        {
                            Email = "*****@*****.**",
                            UserName = "******",
                            Password = "******",
                            IsApproved = true,
                            DisableEmailNotifications = false,
                            DisablePosting = false,
                            DisablePrivateMessages = false
                        };
                        _membershipService.CreateUser(admin);

                        // Do a save changes just in case
                        unitOfWork.SaveChanges();

                        // Put the admin in the admin role
                        var adminRole = _roleService.GetRole("Admin");
                        admin.Roles = new List<MembershipRole> { adminRole };

                        unitOfWork.Commit();
                    }
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    installerResult.Exception = ex.InnerException;
                    installerResult.Message = "Error creating the initial data >> Admin user & Permissions";
                    installerResult.Successful = false;
                    return installerResult;
                }
            }

            // Do this so search works and doesn't create a null reference.
            _luceneService.UpdateIndex();

            return installerResult;
        }
Пример #23
0
        /// <summary>
        /// Returns permission set based on category and role
        /// </summary>
        /// <param name="category"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        public PermissionSet GetPermissions(Category category, MembershipRole role)
        {
            // Pass the role in to see select which permissions to apply
            // Going to cache this per request, just to help with performance
            var objectContextKey = string.Concat(HttpContext.Current.GetHashCode().ToString("x"), "-", category.Id, "-", role.Id);
            if (!HttpContext.Current.Items.Contains(objectContextKey))
            {
                switch (role.RoleName)
                {
                    case AppConstants.AdminRoleName:
                        _permissions = GetAdminPermissions(category, role);
                        break;
                    case AppConstants.GuestRoleName:
                        _permissions = GetGuestPermissions(category, role);
                        break;
                    default:
                        _permissions = GetOtherPermissions(category, role);
                        break;
                }

                HttpContext.Current.Items.Add(objectContextKey, _permissions);
            }

            return HttpContext.Current.Items[objectContextKey] as PermissionSet;
        }
Пример #24
0
        public void BeforePostMadeCancel()
        {
            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>();

            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 }
            };

            EventManager.Instance.BeforePostMade += eventsService_BeforePostMadeCancel;
            postService.AddNewPost("A test post", topic, user, out permissionSet);

            membershipUserPointsService.DidNotReceive().Add(Arg.Is<MembershipUserPoints>(x => x.User == user));
            EventManager.Instance.BeforePostMade -= eventsService_BeforePostMadeCancel;
        }
 /// <summary>
 /// Returns a row with the permission and CPFR
 /// </summary>
 /// <param name="role"></param>
 /// <param name="cat"></param>
 /// <returns></returns>
 public Dictionary<Permission, CategoryPermissionForRole> GetCategoryRow(MembershipRole role, Category cat)
 {
     var catRowList = _categoryPermissionForRoleService.GetCategoryRow(role, cat);
     return catRowList.ToDictionary(catRow => catRow.Permission);
 }
Пример #26
0
        /// <summary>
        /// Guest = Not logged in, so only need to check the access permission
        /// </summary>
        /// <param name="category"></param>
        /// <param name="role"></param>
        private PermissionSet GetGuestPermissions(Category category, MembershipRole role)
        {
            // Get all the permissions
                    var permissionList = _permissionRepository.GetAll();

                    // Make a CategoryPermissionForRole for each permission that exists,
                    // but only set the read-only permission to true for this role / category. All others false
                    var permissions = permissionList.Select(permission => new CategoryPermissionForRole
                    {
                        Category = category,
                        IsTicked = permission.Name == AppConstants.PermissionReadOnly,
                        MembershipRole = role,
                        Permission = permission
                    }).ToList();

                    // Deny Access may have been set (or left null) for guest for the category, so need to read for it
                    var denyAccessPermission = role.CategoryPermissionForRole
                                       .FirstOrDefault(x => x.Category == category &&
                                                            x.Permission.Name == AppConstants.PermissionDenyAccess &&
                                                            x.MembershipRole == role);

                    // Set the Deny Access value in the results. If it's null for this role/category, record it as false in the results
                    var categoryPermissionForRole = permissions.FirstOrDefault(x => x.Permission.Name == AppConstants.PermissionDenyAccess);
                    if (categoryPermissionForRole != null)
                    {
                        categoryPermissionForRole.IsTicked = denyAccessPermission != null && denyAccessPermission.IsTicked;
                    }

                    var permissionSet = new PermissionSet(permissions);

            return permissionSet;
        }
Пример #27
0
 /// <summary>
 /// Save a role
 /// </summary>
 /// <param name="role"></param>
 public void Save(MembershipRole role)
 {
     role.RoleName = StringUtils.SafePlainText(role.RoleName);
     _roleRepository.Update(role);
 }
Пример #28
0
 /// <summary>
 /// Create a new role
 /// </summary>
 /// <param name="role"></param>
 public void CreateRole(MembershipRole role)
 {
     role.RoleName = StringUtils.SafePlainText(role.RoleName);
     _roleRepository.Add(role);
 }
Пример #29
0
        public IList<Topic> GetPendingTopics(List<Category> allowedCategories, MembershipRole usersRole)
        {
            var allowedCatIds = allowedCategories.Select(x => x.Id);
            var allPendingTopics = _context.Topic.AsNoTracking().Include(x => x.Category).Where(x => x.Pending == true && allowedCatIds.Contains(x.Category.Id)).ToList();
            if (usersRole != null)
            {
                var pendingTopics = new List<Topic>();
                var permissionSets = new Dictionary<Guid, PermissionSet>();
                foreach (var category in allowedCategories)
                {
                    var permissionSet = _roleService.GetPermissions(category, usersRole);
                    permissionSets.Add(category.Id, permissionSet);
                }

                foreach (var pendingTopic in allPendingTopics)
                {
                    if (permissionSets.ContainsKey(pendingTopic.Category.Id))
                    {
                        var permissions = permissionSets[pendingTopic.Category.Id];
                        if (permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                        {
                            pendingTopics.Add(pendingTopic);
                        }
                    }
                }
                return pendingTopics;
            }
            return allPendingTopics;
        }
Пример #30
0
        /// <summary>
        /// Admin: so no need to check db, admin is all powerful
        /// </summary>
        private PermissionSet GetAdminPermissions(Category category, MembershipRole role)
        {
            // Get all permissions
                    var permissionList = _permissionRepository.GetAll();

                    // Make a new entry in the results against each permission. All true (this is admin) except "Deny Access"
                    // and "Read Only" which should be false
                    var permissionSet = new PermissionSet(permissionList.Select(permission => new CategoryPermissionForRole
                                                                                                            {
                                                                                                                Category = category,
                                                                                                                IsTicked = (permission.Name != AppConstants.PermissionDenyAccess && permission.Name != AppConstants.PermissionReadOnly),
                                                                                                                MembershipRole = role,
                                                                                                                Permission = permission
                                                                                                            }).ToList());

            return permissionSet;
        }