I'm looking for the best or a good way to handle items visibility per user. Actually I've the following entities...
public class Post
{
public Guid Id {get;set;}
public string Content {get; set;}
public Guid VisibilityId {get; set;}
public Visibility Visibility {get; set;}
}
public class Visibility
{
public Guid Id {get; set;}
public string Name {get; set;}
}
public class AllowedList
{
public Guid PostId {get; set;}
public Guid UserId {get; set;}
}
I added the following lookups for the Visibility Entity
Public, OnlyMe, Custom
I want to display post items for user in cases
- "public" in that case all users allowed to show that Post.
- "Custom" in that case the user if exist on the AllowedList then they can show it.
- "OnlyMe" in that case the created user only can show that Post.
so based on that acceptance criteria, I created the following code.
/*
1. PublicId => 1,
2. OnlyMeId => 2,
3. CustomId => 3
*/
public IQueryable<Post> GetPosts(ApplicationContext context ,ICurrentUser user)
{
var userId = user.Id;
var posts = context.Posts.Where(p => p.VisibilityId == 1 || (p.VisibilityId == 2 && p.CreatedBy == userId) || context.AllowedList.Any(a => a.PostId == p.Id && a.UserId == userId));
return posts; // return as IQueryble of Posts
}
That's my Solution but I don't think that is the correct or good one for that case.
CodePudding user response:
I think that a Boolean IsPublic should be enough to formulate all cases, since the creator should always be allowed to see the post. OnlyMe would correspond to Public == false with an empty allowed list. If Public is true, it doesn't matter whether there are entries in the allowed list or not.
public bool IsPublic { get; set; }
var posts = context.Posts
.Where(p => p.IsPublic ||
p.CreatedBy == userId ||
context.AllowedList.Any(a => a.PostId == p.Id && a.UserId == userId));
