/// <summary> /// Create a new role /// </summary> /// <param name="role"></param> public MembershipRole CreateRole(MembershipRole role) { role.RoleName = StringUtils.SafePlainText(role.RoleName); var membershipRole = GetRole(role.RoleName); return(membershipRole ?? _context.MembershipRole.Add(role)); }
public virtual void AddRole(MembershipRole role) { List <MembershipRole> allRoles = (List <MembershipRole>)GetItem("Roles"); allRoles.Add(role); SetAllRoles(allRoles); }
public IList <CategoryPermissionForRole> GetCategoryRow(MembershipRole role, Category cat) { return(_context.CategoryPermissionForRole .Where(x => x.Category.Id == cat.Id && x.MembershipRole.Id == role.Id) .ToList()); }
public IList <Post> GetPendingPosts(List <Category> allowedCategories, MembershipRole usersRole) { var allowedCatIds = allowedCategories.Select(x => x.Id); var allPendingPosts = _context.Post.AsNoTracking().Include(x => x.Topic.Category).Where(x => x.Pending == true && allowedCatIds.Contains(x.Topic.Category.Id)).ToList(); if (usersRole != null) { var pendingPosts = new List <Post>(); var permissionSets = new Dictionary <Guid, PermissionSet>(); foreach (var category in allowedCategories) { var permissionSet = _roleService.GetPermissions(category, usersRole); permissionSets.Add(category.Id, permissionSet); } foreach (var pendingPost in allPendingPosts) { if (permissionSets.ContainsKey(pendingPost.Topic.Category.Id)) { var permissions = permissionSets[pendingPost.Topic.Category.Id]; if (permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked) { pendingPosts.Add(pendingPost); } } } return(pendingPosts); } return(allPendingPosts); }
/// <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); }
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()); } }
public async Task CreateDefaultSuperAdmin() { try { await _roles.GenerateRolesFromPagesAsync(); var roles = _roleManager.Roles.ToList(); //add memberships Membership MS_Admin = new Membership(); MS_Admin.Name = "SuperAdmin"; await _context.Membership.AddAsync(MS_Admin); await _context.SaveChangesAsync(); Membership MS_User = new Membership(); MS_User.Name = "User"; await _context.Membership.AddAsync(MS_User); await _context.SaveChangesAsync(); //add membership role foreach (var item in roles) { MembershipRole MSRole = new MembershipRole(); MSRole.MembershipId = MS_Admin.MembershipId; MSRole.RoleName = item.Name; await _context.MembershipRole.AddAsync(MSRole); await _context.SaveChangesAsync(); } //add users ApplicationUser superAdmin = new ApplicationUser(); superAdmin.Email = _superAdminDefaultOptions.Email; superAdmin.UserName = superAdmin.Email; superAdmin.EmailConfirmed = true; var result = await _userManager.CreateAsync(superAdmin, _superAdminDefaultOptions.Password); if (result.Succeeded) { //add to user profile UserProfile profile = new UserProfile(); profile.FirstName = "Super"; profile.LastName = "Admin"; profile.Email = superAdmin.Email; profile.ApplicationUserId = superAdmin.Id; profile.MembershipId = MS_Admin.MembershipId; await _context.UserProfile.AddAsync(profile); await _context.SaveChangesAsync(); await _roles.AddToRoles(superAdmin.Id); } } catch (Exception) { throw; } }
protected void btnRemove_Click(object sender, EventArgs e) { HiddenField hdnUserName = null; CheckBox chkSelected = null; MembershipRole role = getCurrentGroup(); string currentRoleName = role.RoleName; foreach (GridViewRow dgItem in gvUsers.Rows) { hdnUserName = (HiddenField)dgItem.FindControl("hdnUserName"); if (!String.IsNullOrEmpty(hdnUserName.Value)) { chkSelected = (CheckBox)dgItem.FindControl("chkSelected"); if (chkSelected.Checked) { Roles.RemoveUserFromRole(hdnUserName.Value, currentRoleName); } } } Response.Redirect(SiteData.CurrentScriptName + "?id=" + groupID.ToString()); }
protected void Page_Load(object sender, EventArgs e) { Master.ActivateTab(AdminBaseMasterPage.SectionID.GroupAdmin); groupID = GetGuidIDFromQuery(); btnApply.Visible = SecurityData.IsAdmin; btnAddUsers.Visible = SecurityData.IsAdmin; btnRemove.Visible = SecurityData.IsAdmin; if (groupID == Guid.Empty) { btnApply.Text = "Add"; } else { pnlUsers.Visible = true; } if (!IsPostBack) { if (groupID != Guid.Empty) { MembershipRole role = getCurrentGroup(); txtRoleName.Text = role.RoleName; txtRoleName.Enabled = CheckValidEditing(role.RoleName); btnApply.Visible = CheckValidEditing(role.RoleName); GetUserList(role.RoleName); } } }
public IList <Topic> GetPendingTopics(List <Group> allowedGroups, MembershipRole usersRole) { var allowedCatIds = allowedGroups.Select(x => x.Id); var allPendingTopics = _context.Topic.AsNoTracking().Include(x => x.Group).Where(x => x.Pending == true && allowedCatIds.Contains(x.Group.Id)).ToList(); if (usersRole != null) { var pendingTopics = new List <Topic>(); var permissionSets = new Dictionary <Guid, PermissionSet>(); foreach (var Group in allowedGroups) { var permissionSet = _roleService.GetPermissions(Group, usersRole); permissionSets.Add(Group.Id, permissionSet); } foreach (var pendingTopic in allPendingTopics) { if (permissionSets.ContainsKey(pendingTopic.Group.Id)) { var permissions = permissionSets[pendingTopic.Group.Id]; if (permissions[ForumConfiguration.Instance.PermissionEditPosts].IsTicked) { pendingTopics.Add(pendingTopic); } } } return(pendingTopics); } return(allPendingTopics); }
private void PrepareRoleViewModel(MemberShipRoleViewModel model, MembershipRole entity) { model.isAdmin = (WorkContext.CurrentMembershipUser.MembershipRoles.Any(x => x.Id == new Guid("7a2f0eca-4daf-4aa5-8c1d-9cffd6aad69f"))); if (model.isAdmin) { IList <SelectListItem> selList = new List <SelectListItem>(); var companyList = _companyService.GetAll(); if (entity == null) { foreach (var item in companyList) { selList.Add(new SelectListItem { Text = item.CompanyName, Value = item.Id.ToString(), Selected = (item.Id == WorkContext.CurrentMembershipUser.Company.Id) }); } } else { foreach (var item in companyList) { selList.Add(new SelectListItem { Text = item.CompanyName, Value = item.Id.ToString(), Selected = (item.Id == entity.Company.Id) }); } } model.Companys = selList; } }
public static List <TopicViewModel> CreateTopicViewModels(List <Topic> topics, IRoleService roleService, MembershipRole usersRole, MembershipUser loggedOnUser, List <Category> allowedCategories, Settings settings, IPostService postService, ITopicNotificationService topicNotificationService, IPollAnswerService pollAnswerService, IVoteService voteService, IFavouriteService favouriteService) { // Get all topic Ids var topicIds = topics.Select(x => x.Id).ToList(); // Gets posts for topics var posts = postService.GetPostsByTopics(topicIds, allowedCategories); var groupedPosts = posts.ToLookup(x => x.Topic.Id); // Get all permissions var permissions = GetPermissionsForTopics(topics, roleService, usersRole); // Create the view models var viewModels = new List <TopicViewModel>(); foreach (var topic in topics) { var id = topic.Id; var permission = permissions[topic.Category]; var topicPosts = groupedPosts.Contains(id) ? groupedPosts[id].ToList() : new List <Post>(); viewModels.Add(CreateTopicViewModel(topic, permission, topicPosts, null, null, null, null, loggedOnUser, settings, topicNotificationService, pollAnswerService, voteService, favouriteService)); } return(viewModels); }
// TODO - This query could be a performance problem /// <summary> /// Gets a paged list of badges /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="usersRole"></param> /// <returns></returns> public async Task <PaginatedList <ActivityBase> > GetPagedGroupedActivities(int pageIndex, int pageSize, MembershipRole usersRole) { // Read the database for all activities and convert each to a more specialised activity type var allowedCategories = _categoryService.GetAllowedCategories(usersRole); var allowedCatIds = allowedCategories.Select(x => x.Id); var query = from activity in _context.Activity where (activity.Type != ActivityType.TopicCreated.ToString() || _context.Topic .Where(p => allowedCatIds.Contains(p.Category.Id)).Select(q => q.Id.ToString()) .Contains(activity.Data)) && (activity.Type != ActivityType.PostCreated.ToString() || _context.Post .Where(p => allowedCatIds.Contains(p.Topic.Category.Id)).Select(q => q.Id.ToString()) .Contains(activity.Data)) select activity; var results = query.OrderByDescending(x => x.Timestamp); var activities = await PaginatedList <Activity> .CreateAsync(results, pageIndex, pageSize); // Convert var specificActivities = ConvertToSpecificActivities(activities, pageIndex, pageSize); return(specificActivities); }
public IList <Topic> GetPendingTopics(List <Category> allowedCategories, MembershipRole usersRole) { var cacheKey = string.Concat(CacheKeys.Topic.StartsWith, "GetPendingTopics-", allowedCategories.GetHashCode(), "-", usersRole.Id); return(_cacheService.CachePerRequest(cacheKey, () => { 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; })); }
/// <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); }
/// <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); }
public static List <TopicViewModel> CreateTopicViewModels(List <Topic> topics, IRoleService roleService, MembershipRole usersRole, MembershipUser loggedOnUser, Settings settings) { // Get all topic Ids var topicIds = topics.Select(x => x.Id).ToList(); // Gets posts for topics var postService = ServiceFactory.Get <IPostService>(); var posts = postService.GetPostsByTopics(topicIds); var groupedPosts = posts.ToLookup(x => x.Topic.Id); // Get all permissions var permissions = GetPermissionsForTopics(topics, roleService, usersRole); // Create the view models var viewModels = new List <TopicViewModel>(); foreach (var topic in topics) { var id = topic.Id; var permission = permissions[topic.Category]; var topicPosts = (groupedPosts.Contains(id) ? groupedPosts[id].ToList() : new List <Post>()); viewModels.Add(CreateTopicViewModel(topic, permission, topicPosts, null, null, null, null, loggedOnUser, settings)); } return(viewModels); }
public void Init() { AutoMappingRegistrar.Configure(); _membershipServiceSub = Substitute.For <IMembershipService>(); //.Do(x => { return MembershipCreateStatus.ProviderError; }); var role = new MembershipRole { Id = Guid.NewGuid(), RoleName = "authors", }; var user = new MembershipUser { UserId = Guid.NewGuid(), UserName = "******", Comment = "test user", CreateDate = DateTime.Now, Email = "*****@*****.**", FailedPasswordAnswerAttempt = 0, FailedPasswordAttemptCount = 0, IsApproved = true, IsLockedOut = false, LastLockoutDate = DateTime.Now, LastLoginDate = DateTime.Now, LastPasswordChangedDate = DateTime.Now, Password = "******", PasswordQuestion = "question", PasswordAnswer = "answer", Roles = new List <MembershipRole> { role }, Stories = new List <NewsItem>() }; var newsItem = new NewsItem { Id = Guid.NewGuid(), Title = "test title", Body = "body", Authors = new List <MembershipUser> { user } }; role.Users = new List <MembershipUser> { user }; user.Stories = new List <NewsItem> { newsItem }; _membershipServiceSub.GetAll().Returns(new List <MembershipUser> { user }); }
public Dictionary<Permission, GlobalPermissionForRole> GetAll(MembershipRole role) { var cacheKey = string.Concat(CacheKeys.GlobalPermissionForRole.StartsWith, "GetAll-", role.Id); return _cacheService.CachePerRequest(cacheKey, () => { var catRowList = _context.GlobalPermissionForRole.Include(x => x.MembershipRole).Where(x => x.MembershipRole.Id == role.Id).ToList(); return catRowList.ToDictionary(catRow => catRow.Permission); }); }
/// <summary> /// Return allowed Groups based on the users role /// </summary> /// <param name="role"></param> /// <returns></returns> public List <Group> GetAllowedGroups(MembershipRole role, Guid?membershipId) { if (role.RoleName == Constants.AdminRoleName) { return(GetAllowedGroups(role, ForumConfiguration.Instance.PermissionDenyAccess, membershipId)); } return(_context.GroupUser.Where(x => x.User.Id == membershipId && (x.Approved && !x.Banned && !x.Locked && !x.Rejected)).Select(x => x.Group).ToList()); }
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 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; }
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; }
public static MembershipRole RoleViewModelToRole(RoleViewModel roleViewModel) { var viewModel = new MembershipRole { RoleName = roleViewModel.RoleName }; return(viewModel); }
public ActionResult RolePermission(Guid id) { var model = new RolePermissionViewModel(); MembershipRole role = _membershipService.GetRole(id); model.MembershipRole = role; GenerateRolePermissions(model); return(View(model)); }
public static List <TopicViewModel> CreateTopicViewModels(List <Topic> topics, IRoleService roleService, MembershipRole usersRole, MembershipUser loggedOnUser, List <Group> allowedGroups, Settings settings, IPostService postService, INotificationService topicNotificationService, IPollService pollService, IVoteService voteService, IFavouriteService favouriteService) { // Get all topic Ids var topicIds = topics.Select(x => x.Id).ToList(); // Gets posts for topics var posts = postService.GetPostsByTopics(topicIds, allowedGroups); var groupedPosts = posts.ToLookup(x => x.Topic.Id); // Get all permissions var permissions = GetPermissionsForTopics(topics, roleService, usersRole); // Get all votes var votesGrouped = voteService.GetVotesByTopicsGroupedIntoPosts(topicIds); // Favourites grouped var favouritesGrouped = favouriteService.GetByTopicsGroupedIntoPosts(topicIds); // Create the view models var viewModels = new List <TopicViewModel>(); foreach (var topic in topics) { var id = topic.Id; var permission = permissions[topic.Group]; var topicPosts = groupedPosts.Contains(id) ? groupedPosts[id].ToList() : new List <Post>(); var votes = new Dictionary <Guid, List <Vote> >(); if (votesGrouped.ContainsKey(id)) { votes = votesGrouped[id]; } var favourites = new Dictionary <Guid, List <Favourite> >(); if (favouritesGrouped.ContainsKey(id)) { favourites = favouritesGrouped[id]; } var postIds = topicPosts.Select(x => x.Id).ToList(); viewModels.Add(CreateTopicViewModel(topic, permission, topicPosts, postIds, null, null, null, null, loggedOnUser, settings, topicNotificationService, pollService, votes, favourites)); } return(viewModels); }
public static RoleViewModel RoleToRoleViewModel(MembershipRole role) { var viewModel = new RoleViewModel { Id = role.Id, RoleName = role.RoleName }; return(viewModel); }
public Dictionary <Permission, GlobalPermissionForRole> GetAll(MembershipRole role) { var cacheKey = string.Concat(CacheKeys.GlobalPermissionForRole.StartsWith, "GetAll-", role.Id); return(_cacheService.CachePerRequest(cacheKey, () => { var catRowList = _context.GlobalPermissionForRole.Include(x => x.MembershipRole).Where(x => x.MembershipRole.Id == role.Id).ToList(); return catRowList.ToDictionary(catRow => catRow.Permission); })); }
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(); }
/// <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)); }
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(); }
public void Init() { AutoMappingRegistrar.Configure(); _membershipServiceSub = Substitute.For<IMembershipService>(); //.Do(x => { return MembershipCreateStatus.ProviderError; }); var role = new MembershipRole { Id = Guid.NewGuid(), RoleName = "authors", }; var user = new MembershipUser { UserId = Guid.NewGuid(), UserName = "******", Comment = "test user", CreateDate = DateTime.Now, Email = "*****@*****.**", FailedPasswordAnswerAttempt = 0, FailedPasswordAttemptCount = 0, IsApproved = true, IsLockedOut = false, LastLockoutDate = DateTime.Now, LastLoginDate = DateTime.Now, LastPasswordChangedDate = DateTime.Now, Password = "******", PasswordQuestion = "question", PasswordAnswer = "answer", Roles = new List<MembershipRole> {role}, Stories = new List<NewsItem>() }; var newsItem = new NewsItem { Id = Guid.NewGuid(), Title = "test title", Body = "body", Authors = new List<MembershipUser> { user } }; role.Users = new List<MembershipUser> {user}; user.Stories = new List<NewsItem> {newsItem}; _membershipServiceSub.GetAll().Returns(new List<MembershipUser>{user}); }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary != null) { var membershipRole = new MembershipRole(); membershipRole.Id = dictionary.GetValue<int>("id"); membershipRole.Inherited = dictionary.GetValue<bool>("inherited"); membershipRole.Name = dictionary.GetValue<string>("name"); return membershipRole; } return null; }
/// <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 = _categoryPermissionForRoleService.GetByRole(role.Id); foreach (var categoryPermissionForRole in rolesToDelete) { _categoryPermissionForRoleService.Delete(categoryPermissionForRole); } _context.MembershipRole.Remove(role); } else { var inUseBy = new List<Entity>(); inUseBy.AddRange(role.Users); throw new InUseUnableToDeleteException(inUseBy); } }
/// <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); }
/// <summary> /// Create a new role /// </summary> /// <param name="role"></param> public MembershipRole CreateRole(MembershipRole role) { role.RoleName = StringUtils.SafePlainText(role.RoleName); var membershipRole = GetRole(role.RoleName); return membershipRole ?? _context.MembershipRole.Add(role); }
/// <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 = _permissionService.GetAll().ToList(); // 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 // 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.PermissionDenyAccess && permission.Name != SiteConstants.Instance.PermissionReadOnly), MembershipRole = role, Permission = permission }); } } // Sort the global permissions out - As it's a admin we set everything to true! var globalPermissions = permissionList .Where(x => x.IsGlobal) .Select(permission => new GlobalPermissionForRole { IsTicked = true, MembershipRole = role, Permission = permission }); // Create the permission set return new PermissionSet(categoryPermissions, globalPermissions); }
/// <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); }
private List<Category> GetAllowedCategoriesCode(MembershipRole role, string actionType) { var cacheKey = string.Concat(CacheKeys.Category.StartsWith, "GetAllowedCategoriesCode-", role.Id, "-", actionType); return _cacheService.CachePerRequest(cacheKey, () => { var filteredCats = new List<Category>(); var allCats = GetAll(); foreach (var category in allCats) { var permissionSet = _roleService.GetPermissions(category, role); if (!permissionSet[actionType].IsTicked) { // Only add it category is NOT locked filteredCats.Add(category); } } return filteredCats; }); }
/// <summary> /// Returns permission set based on category and role /// </summary> /// <param name="category">Category could be null when requesting global permissions</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 // We pass in an empty guid if the category is null var categoryId = Guid.Empty; if (category != null) { categoryId = category.Id; } var cacheKey = string.Concat(CacheKeys.Role.StartsWith, "GetPermissions-", categoryId, "-", role.Id); return _cacheService.CachePerRequest(cacheKey, () => { PermissionSet permissions; 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; } return permissions; }); }
/// <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 cacheKey = string.Concat(CacheKeys.CategoryPermissionForRole.StartsWith, "GetCategoryRow-", role.Id, "-", cat.Id); return _cacheService.CachePerRequest(cacheKey, () => { var catRowList = _context.CategoryPermissionForRole .Include(x => x.MembershipRole) .Include(x => x.Category) .Include(x => x.Permission) .AsNoTracking() .Where(x => x.Category.Id == cat.Id && x.MembershipRole.Id == role.Id) .ToList(); return catRowList.ToDictionary(catRow => catRow.Permission); }); }
private MembershipRole ToOrmRole(DalMembershipRole dalRole) { if (dalRole == null) return null; var role = new MembershipRole(); UpdateInfo(role, dalRole); return role; }
public IList<Topic> GetPendingTopics(List<Category> allowedCategories, MembershipRole usersRole) { var cacheKey = string.Concat(CacheKeys.Topic.StartsWith, "GetPendingTopics-", allowedCategories.GetHashCode(), "-", usersRole.Id); return _cacheService.CachePerRequest(cacheKey, () => { 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; }); }
private void UpdateInfo(MembershipRole role, DalMembershipRole dalRole) { if (role == null || dalRole == null) throw new ArgumentNullException(); role.Id = dalRole.Id; role.RoleName = dalRole.RoleName; }
public List<Category> GetAllowedCategories(MembershipRole role, string actionType) { return GetAllowedCategoriesCode(role, actionType); }
/// <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, SiteConstants.Instance.PermissionDenyAccess); }
public IList<Post> GetPendingPosts(List<Category> allowedCategories, MembershipRole usersRole) { var allowedCatIds = allowedCategories.Select(x => x.Id); var allPendingPosts = _context.Post.AsNoTracking().Include(x => x.Topic.Category).Where(x => x.Pending == true && allowedCatIds.Contains(x.Topic.Category.Id)).ToList(); if (usersRole != null) { var pendingPosts = new List<Post>(); var permissionSets = new Dictionary<Guid, PermissionSet>(); foreach (var category in allowedCategories) { var permissionSet = _roleService.GetPermissions(category, usersRole); permissionSets.Add(category.Id, permissionSet); } foreach (var pendingPost in allPendingPosts) { if (permissionSets.ContainsKey(pendingPost.Topic.Category.Id)) { var permissions = permissionSets[pendingPost.Topic.Category.Id]; if (permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked) { pendingPosts.Add(pendingPost); } } } return pendingPosts; } return allPendingPosts; }