0

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,

akd
  • 6,538
  • 16
  • 70
  • 112
  • if you are looking for a way to access `OrganisationId` from an extention method, you can check [this](http://stackoverflow.com/questions/38846816/how-to-get-custom-property-value-of-the-applicationuser-in-the-asp-net-mvc-5-vie/38847016#38847016) – tmg Nov 23 '16 at 12:56
  • 1
    yes it worked. I had to customize the code to convert from string to int but I got it working. This was what I was looking for. thanks. – akd Nov 23 '16 at 13:16
  • I am glad it worked. In case you need to check if user has access to some action according to his `OrganisationId`, then you should use custom filters. – tmg Nov 23 '16 at 13:20

1 Answers1

0

The Simplest Way that i have found is the below two lines of code hope this will help you.

 public class ApplicationUser : IdentityUser
    {

        [Required]
        public string Name { get; set; }

 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
}

  public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

<ul class="nav navbar-nav navbar-left">
            <li>
                @{
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var currentUser = manager.FindById(User.Identity.GetUserId());
                }
                @Html.ActionLink(currentUser.Name + " " + "Welcome", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li>
                <a href="javascript:document.getElementById('logoutForm').submit()">LogOff </a>
            </li>
        </ul>
Mohammad
  • 71
  • 1
  • 10