The default Identity comes with some user attributes. and this table is fully extensible with custom attributes.
I have added a custom attribute "OrganisationId" to specify that each user must be a part of an organisation.
public class ApplicationUser
: IdentityUser<int, ApplicationUserLogin,
ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public int OrganisationId { get; set; }
public Organisation Organisation { get; set; }
public UserProfile UserProfile { get; set; }
}
So now in most of my controllers I need to gain access to user organisation or user organisation id to filter the content.
For example: Organisations can have multiple addresses and users can view the list of addresses in their own organisations.
[ChildActionOnly]
// GET: Addresses
public ActionResult Index()
{
var userId = User.Identity.GetUserId<int>();
var userOrganisationId = _organisationService.GetOrganisationByUserId(userId).Id;
var addresses = _addressService.GetAddresses(userOrganisationId);
var viewModel = Mapper.Map<IEnumerable<Address>, IEnumerable<AddressViewModel>>(addresses);
return PartialView("_Index", viewModel);
}
But I can see that to gain access only the user organisation I need to inject ApplicationUserManager or OrganisationService in my controller.
In the above you see that I have injected organisationService then create a method to find the user organisation.
I just think this seems to be very repetitive task.
Would that be any other better way to access the user extended properties without injecting any services?
For example User object already accessible in controller.
something like:
var organisationId = User.GetCustomProperty(u => u.OrganisationId);
Or maybe using custom action filters?
What would be the best way to avoid this sort of repetitive checking?
Thanks,