Reputation: 1414
have scoured by couldn't find anything relevant.
I have to this point built a cool web app in MVC using C#. I created a User model as
public class User
{
// Must be named EntityNameId, must have primary key!
public int UserId { get; set; }
[DisplayName("First Name")]
public string firstName { get; set; }
[DisplayName("Last Name")]
public string lastName { get; set; }
[DisplayName("Cell Number")]
public string cellNumber { get; set; }
}
And as such have designed a profile/dashboard for each user
/User/Profile/1
Accessed by their id. Ive also got other sections such as a menu to edit items /Item/Index/1 which shows all items for that user etc. My code works etc to filter and populate those pages just for the user. To this point however I have not implemented any authentication. I would like to use the built in authentication tools through ApplicationServices and have done before with roles:
<Authorize(Roles:="Manager,Administrator")>
However I would like to limit pages to specific users who are logged in? I.e. /User/Profile/1 should only be accessible by that user etc. Rather than the roles they serve.
Does any one know how this could be done? I know this would likely mean tying the account controllers and user controllers together, not quite sure how to do this so that everything works the same? As app is basically finished, quite simple tho, but just requires authentication.
Upvotes: 2
Views: 108
Reputation: 39807
A secondary option would be to not even pass the user Id into the controller/action method, just grab the logged in user's Id and get the information from there.
[Authorize]
public ActionResult Profile()
{
return View(profileService.GetUserProfile(CurrentUser.Id));
}
Upvotes: 1
Reputation: 56429
Just do a simple check at the top of the action method, if it's not the current user, perform the redirect.
public ActionResult Profile(int id)
{
if (CurrentUser.Id != id)
{
return RedirectToAction("Index");
}
return View();
}
If you use it a lot, you could refactor it out into a method.
Upvotes: 2