How to hide a Model property for certain users?

I am building an API that will serve users with different administration levels (roles)

I have the following model (redacted for brevity)

public class Job
{
    public Guid JobId { get; set; }
    public string Name{ get; set; }
    public string CommentsAdmins { get; set; }
}

When an admin user calls the API controller, I want the API to return the entire model above. But when a regular user calls the API, I want the model to return the same model, minus CommentsAdmins

public class Job
{
    public Guid JobId { get; set; }
    public string Name{ get; set; }
}

I'm not comfortable to use a nullable string? because I believe that's a dirty way to do it. Also I don't want the field to be visible in my mobile app code, which may be publicly visible if somebody tries to decompile the mobile app binaries.

Additionally, creating multiple models for multiple user levels doesn't feel intuitive as well.

What's the best way to go about this?

1 answer

  • answered 2022-05-05 05:52 A Farmanbar

    Just in case, try below approach

    public class Job: baseClass
    {
        private bool isAdmin;
        public job(bool isAdmin) this.isAdmin = isAdmin;
        public Guid JobId { get; set; }
        public string Name { get; set; }
        public override CommentsAdmins get 
                                       { return isAdmin? base.CommentsAdmins: null ;}
                                       set 
                                       {base.CommentsAdmins = value};
    }
    
    public class baseClass
    {
        public virtual string CommentsAdmins { get; set; }
    }
    

    I haven't tried it, but I think it shall work.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum