Panich Maxim
Panich Maxim

Reputation: 1115

Authorized users access, ASP.NET MVC

I have rows with different guids in my database table:

public class News
{
    public int NewsId { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public int guid { get; set; }
}

And I want to create groups of users, that will be able to view news with a certain guid. I am using ASP.NET MVC template with users authentication, but I can't understand how should I approach my goal? I can register users, I read about roles and filters, but it didn't help.

[Authorize]
public ActionResult GetNews()
{
 // GET USER GUID AND RETRIEVE NEWS WITH THIS GUID??
}

Should I somehow search how to retrieve user's id in controller method, than make query to database and get users group to filter news list or there is solution more easy?

Also, in Django I was able to control users from prebuild admin panel, has ASP.NET MVC similar thing, or I should make my own controller for this? I need somehow add users to groups/(give them roles) if I want to filtering content for different users.

Upvotes: 0

Views: 734

Answers (2)

user3313994
user3313994

Reputation:

Use User property of ur controller.

Upvotes: 1

IndieTech Solutions
IndieTech Solutions

Reputation: 2539

There couple of ways to achieve that, here's my version. the GetNews() method should only be responsible of getting the new news and return an Actionresult . the logic of checking the user ID or anything else should not be managed inside this method SOLID

As for controlling who should have access to the GetNews() , you can benefit from the authentication logic already implemented in your app. the attribute [Authorize] will only give access to authenticated users to use your method. try to add a role based logic as well, by extending the functionality . something like [Authorize(Roles = "NewsMembers")]

BONUS

sample code to add a role :

 private void AddRole(String roleName)
        {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            var role = new IdentityRole();
            role.Name = roleName;
            roleManager.Create(role);
        }

Sample code to add role to a user

public void addRoleToUser(string UserId,string roleName)
        {
            var context = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);
            userManager.AddToRole(UserId,roleName);
            userManager.Dispose();
            userStore.Dispose();
        }

Upvotes: 0

Related Questions