コード例 #1
0
        /// <summary>
        /// Delete a category
        /// </summary>
        /// <param name="category"></param>
        public void Delete(Category category)
        {
            // Check if anyone else if using this role
            var okToDelete = !category.Topics.Any();

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

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

                var categoryNotificationsToDelete = new List<CategoryNotification>();
                categoryNotificationsToDelete.AddRange(category.CategoryNotifications);
                foreach (var categoryNotification in categoryNotificationsToDelete)
                {
                    _categoryNotificationService.Delete(categoryNotification);
                }

                _categoryRepository.Delete(category);
            }
            else
            {
                var inUseBy = new List<Entity>();
                inUseBy.AddRange(category.Topics);
                throw new InUseUnableToDeleteException(inUseBy);
            }
        }
コード例 #2
0
ファイル: PostServiceTests.cs プロジェクト: kangjh0815/test
        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
 /// <summary>
 /// Return all notifications by a specified category
 /// </summary>
 /// <param name="category"></param>
 /// <returns></returns>
 public IList<CategoryNotification> GetByCategory(Category category)
 {
     return _context.CategoryNotification
         .AsNoTracking()
         .Where(x => x.Category.Id == category.Id)
         .ToList();
 }
コード例 #4
0
 public IList<CategoryPermissionForRole> GetCategoryRow(MembershipRole role, Category cat)
 {
     return _context.CategoryPermissionForRole
         .Where(x => x.Category.Id == cat.Id &&
                     x.MembershipRole.Id == role.Id)
                     .ToList();
 }
コード例 #5
0
 /// <summary>
 /// Gets all categories right the way down
 /// </summary>
 /// <param name="category"></param>
 /// <returns></returns>
 public IList<Category> GetAllDeepSubCategories(Category category)
 {
     var catGuid = category.Id.ToString().ToLower();
     return _context.Category
             .Where(x => x.Path != null && x.Path.ToLower().Contains(catGuid))
             .OrderBy(x => x.SortOrder)
             .ToList();
 }
コード例 #6
0
 public void Update(Category item)
 {
     // Check there's not an object with same identifier already in context
     if (_context.Category.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; 
 }
コード例 #7
0
 /// <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();
 }
コード例 #8
0
 /// <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);
 }
コード例 #9
0
ファイル: CategoryService.cs プロジェクト: huchao007/mvcforum
        public List<Category> GetSubCategories(Category category, List<Category> allCategories, int level = 2)
        {
            var catsToReturn = new List<Category>();
            var cats = allCategories.Where(x => x.ParentCategory != null && x.ParentCategory.Id == category.Id).OrderBy(x =>x.SortOrder);
            foreach (var cat in cats)
            {
                cat.Level = level;
                catsToReturn.Add(cat);
                catsToReturn.AddRange(GetSubCategories(cat, allCategories, level + 1));
            }

            return catsToReturn;
        }
コード例 #10
0
        /// <summary>
        /// Add a new category
        /// </summary>
        /// <param name="category"></param>
        public void Add(Category category)
        {
            // Sanitize
            category = SanitizeCategory(category);

            // Set the create date
            category.DateCreated = DateTime.UtcNow;

            // url slug generator
            category.Slug = ServiceHelpers.GenerateSlug(category.Name, _categoryRepository.GetBySlugLike(ServiceHelpers.CreateUrl(category.Name)), null);

            // Add the category
            _categoryRepository.Add(category);
        }
コード例 #11
0
        public ActionResult CreateCategory(CreateCategoryViewModel categoryViewModel)
        {
            if (ModelState.IsValid)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        var category = new Category
                                           {
                                               Name = categoryViewModel.Name,
                                               Description = categoryViewModel.Description,
                                               IsLocked = categoryViewModel.IsLocked,
                                               SortOrder = categoryViewModel.SortOrder,
                                           };

                        if (categoryViewModel.ParentCategory != null)
                        {
                            category.ParentCategory =
                                _categoryService.Get(categoryViewModel.ParentCategory.Value);
                        }

                        _categoryService.Add(category);

                        // We use temp data because we are doing a redirect
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                                                        {
                                                                            Message = "Category Created",
                                                                            MessageType =
                                                                                GenericMessages.success
                                                                        };
                        unitOfWork.Commit();
                    }
                    catch (Exception)
                    {
                        unitOfWork.Rollback();
                    }
                }
            }

            return RedirectToAction("Index");
        }
コード例 #12
0
        private void NotifyNewTopics(Category cat, IUnitOfWork unitOfWork)
        {
            // Get all notifications for this category
            var notifications = _categoryNotificationService.GetByCategory(cat).Select(x => x.User.Id).ToList();

            if (notifications.Any())
            {
                // remove the current user from the notification, don't want to notify yourself that you
                // have just made a topic!
                notifications.Remove(LoggedOnUser.Id);

                if (notifications.Count > 0)
                {
                    // Now get all the users that need notifying
                    var usersToNotify = MembershipService.GetUsersById(notifications);

                    // Create the email
                    var sb = new StringBuilder();
                    sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("Topic.Notification.NewTopics"), cat.Name));
                    sb.AppendFormat("<p>{0}</p>", string.Concat(SettingsService.GetSettings().ForumUrl, cat.NiceUrl));

                    // create the emails and only send them to people who have not had notifications disabled
                    var emails = usersToNotify.Where(x => x.DisableEmailNotifications != true).Select(user => new Email
                    {
                        Body = _emailService.EmailTemplate(user.UserName, sb.ToString()),
                        EmailTo = user.Email,
                        NameTo = user.UserName,
                        Subject = string.Concat(LocalizationService.GetResourceString("Topic.Notification.Subject"), SettingsService.GetSettings().ForumName)
                    }).ToList();

                    // and now pass the emails in to be sent
                    _emailService.SendMail(emails);

                    try
                    {
                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                    }
                }
            }
        }
コード例 #13
0
 public PartialViewResult GetCategoryBreadcrumb(Category category)
 {
     using (UnitOfWorkManager.NewUnitOfWork())
     {
         var viewModel = new BreadcrumbViewModel
         {
             Categories = _categoryService.GetCategoryParents(category).ToList(),
             Category = category
         };
         return PartialView("GetCategoryBreadcrumb", viewModel);
     }
 }
コード例 #14
0
ファイル: CategoryService.cs プロジェクト: huchao007/mvcforum
 public List<Category> GetCategoryParents(Category category, List<Category> allowedCategories)
 {
     var cats = _categoryRepository.GetCategoryParents(category);
     var allowedCatIds = new List<Guid>();
     if (allowedCategories != null && allowedCategories.Any())
     {
         allowedCatIds.AddRange(allowedCategories.Select(x => x.Id));
     }
     return cats.Where(x => allowedCatIds.Contains(x.Id)).ToList();
 }
コード例 #15
0
        public PartialViewResult GetCategoryBreadcrumb(Category category)
        {
            var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

            using (UnitOfWorkManager.NewUnitOfWork())
            {
                var viewModel = new BreadcrumbViewModel
                {
                    Categories = _categoryService.GetCategoryParents(category,allowedCategories),
                    Category = category
                };
                return PartialView("GetCategoryBreadcrumb", viewModel);
            }
        }
コード例 #16
0
ファイル: RoleService.cs プロジェクト: ivanchen52/mvcforum
        /// <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 = _permissionService.GetAll().ToList();

            var categoryPermissions = new List<CategoryPermissionForRole>();
            if (category != null)
            {
                // Get the known permissions for this role and category
                var categoryRow = _categoryPermissionForRoleService.GetCategoryRow(role, category);
                var categoryRowPermissions = categoryRow.ToDictionary(catRow => catRow.Key.Id);

                // 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
                foreach (var permission in permissionList.Where(x => !x.IsGlobal))
                {
                    categoryPermissions.Add(categoryRowPermissions.ContainsKey(permission.Id)
                                        ? categoryRowPermissions[permission.Id].Value
                                        : new CategoryPermissionForRole { Category = category, MembershipRole = role, IsTicked = false, Permission = permission });
                }
            }

            // Sort the global permissions out - As it's a guest we set everything to false
            var globalPermissions = new List<GlobalPermissionForRole>();

            // Get the known global permissions for this role
            var globalRow = _globalPermissionForRoleService.GetAll(role);
            var globalRowPermissions = globalRow.ToDictionary(row => row.Key.Id);

            // Load up the results with the permisions for this role. A null entry for a permissions results in a new
            // record with a false value
            foreach (var permission in permissionList.Where(x => x.IsGlobal))
            {
                globalPermissions.Add(globalRowPermissions.ContainsKey(permission.Id)
                                    ? globalRowPermissions[permission.Id].Value
                                    : new GlobalPermissionForRole { MembershipRole = role, IsTicked = false, Permission = permission });
            }

            return new PermissionSet(categoryPermissions, globalPermissions);
        }
コード例 #17
0
        /// <summary>
        /// Save / Update a category
        /// </summary>
        /// <param name="category"></param>
        public void Save(Category category)
        {
            // Sanitize
            category = SanitizeCategory(category);

            _categoryRepository.Update(category);
        }
コード例 #18
0
        private void NotifyNewTopics(Category cat, Topic topic, IUnitOfWork unitOfWork)
        {
            var settings = SettingsService.GetSettings();

            // Get all notifications for this category and for the tags on the topic
            var notifications = _categoryNotificationService.GetByCategory(cat).Select(x => x.User.Id).ToList();

            // Merge and remove duplicate ids
            if (topic.Tags != null && topic.Tags.Any())
            {
                var tagNotifications = _tagNotificationService.GetByTag(topic.Tags.ToList()).Select(x => x.User.Id).ToList();
                notifications = notifications.Union(tagNotifications).ToList();
            }

            if (notifications.Any())
            {
                // remove the current user from the notification, don't want to notify yourself that you 
                // have just made a topic!
                notifications.Remove(LoggedOnReadOnlyUser.Id);

                if (notifications.Count > 0)
                {
                    // Now get all the users that need notifying
                    var usersToNotify = MembershipService.GetUsersById(notifications);

                    // Create the email
                    var sb = new StringBuilder();
                    sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("Topic.Notification.NewTopics"), cat.Name));
                    sb.AppendFormat("<p>{0}</p>", topic.Name);
                    sb.Append(AppHelpers.ConvertPostContent(topic.LastPost.PostContent));
                    sb.AppendFormat("<p><a href=\"{0}\">{0}</a></p>", string.Concat(settings.ForumUrl.TrimEnd('/'), cat.NiceUrl));

                    // create the emails and only send them to people who have not had notifications disabled
                    var emails = usersToNotify.Where(x => x.DisableEmailNotifications != true).Select(user => new Email
                    {
                        Body = _emailService.EmailTemplate(user.UserName, sb.ToString()),
                        EmailTo = user.Email,
                        NameTo = user.UserName,
                        Subject = string.Concat(LocalizationService.GetResourceString("Topic.Notification.Subject"), settings.ForumName)
                    }).ToList();

                    // and now pass the emails in to be sent
                    _emailService.SendMail(emails);

                    try
                    {
                        unitOfWork.Commit();
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                    }
                }
            }
        }
コード例 #19
0
 public IList<CategoryNotification> GetByUserAndCategory(MembershipUser user, Category category)
 {
     return _context.CategoryNotification
         .Where(x => x.Category.Id == category.Id && x.User.Id == user.Id)
         .ToList();
 }
コード例 #20
0
 /// <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);
 }
コード例 #21
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;
        }
コード例 #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
 public IList<Category> GetCategoryParents(Category category)
 {
     return _categoryRepository.GetCategoryParents(category);
 }
コード例 #24
0
ファイル: RoleService.cs プロジェクト: kangjh0815/test
        /// <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;
        }
コード例 #25
0
 /// <summary>
 /// Sanitizes a category
 /// </summary>
 /// <param name="category"></param>
 /// <returns></returns>
 public Category SanitizeCategory(Category category)
 {
     // Sanitize any strings in a category
     category.Description = StringUtils.GetSafeHtml(category.Description);
     category.Name = StringUtils.SafePlainText(category.Name);
     return category;
 }
コード例 #26
0
ファイル: RoleService.cs プロジェクト: kangjh0815/test
        /// <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;
        }
コード例 #27
0
        /// <summary>
        /// Keep slug in line with name
        /// </summary>
        /// <param name="category"></param>
        public void UpdateSlugFromName(Category category)
        {
            // Sanitize
            category = SanitizeCategory(category);

            category.Slug = ServiceHelpers.GenerateSlug(category.Name, _categoryRepository.GetBySlugLike(category.Slug), category.Slug);
        }
コード例 #28
0
ファイル: RoleService.cs プロジェクト: ivanchen52/mvcforum
        /// <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 = _permissionService.GetAll().ToList();

            // Make a CategoryPermissionForRole for each permission that exists,
            // but only set the read-only permission to true for this role / category. All others false

            // Category could be null if only requesting global permissions
            // Just return a new list
            var categoryPermissions = new List<CategoryPermissionForRole>();
            if (category != null)
            {
                foreach (var permission in permissionList.Where(x => !x.IsGlobal))
                {
                    categoryPermissions.Add(new CategoryPermissionForRole
                    {
                        Category = category,
                        IsTicked = permission.Name == SiteConstants.Instance.PermissionReadOnly,
                        MembershipRole = role,
                        Permission = permission
                    });
                }

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

                // 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 = categoryPermissions.FirstOrDefault(x => x.Permission.Name == SiteConstants.Instance.PermissionDenyAccess);
                if (categoryPermissionForRole != null)
                {
                    categoryPermissionForRole.IsTicked = denyAccessPermission != null && denyAccessPermission.IsTicked;
                }
            }

            // Sort the global permissions out - As it's a guest we set everything to false
            var globalPermissions = new List<GlobalPermissionForRole>();
            foreach (var permission in permissionList.Where(x => x.IsGlobal))
            {
                globalPermissions.Add(new GlobalPermissionForRole
                {
                    IsTicked = false,
                    MembershipRole = role,
                    Permission = permission
                });
            }

            return new PermissionSet(categoryPermissions, globalPermissions);
        }
コード例 #29
0
ファイル: RoleService.cs プロジェクト: kangjh0815/test
        /// <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;
        }
コード例 #30
0
ファイル: RoleService.cs プロジェクト: kangjh0815/test
        /// <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;
        }