I have a survey's platform with all the score of a list of stores.
I need to make available to each user, the stores based in his location's area (region).
I use Microsoft Identity in my MVC project and I found only two aproaches for this:
1- Build a profile for each region, so I can filter based on the logged user's profile name - dbContext.Where(location == profileName)
2- Extend the ApplicationUser to include the region, so I can filter using dbContext.Where(location == User.Identity.GetLocation())
Or any other option?
I have been able to implement the second option:
Stores Model:
public enum PTLocationDistrict
{
[Display(Name = "Aveiro")]
Aveiro = 1,
[Display(Name = "Beja")]
Beja = 2,
[Display(Name = "Braga")]
Braga = 3
}
[Table("Stores")]
public class Store
{
[Key]
public int Id { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public PTLocationDistrict District { get; set; }
}
Identity ApplicationUser:
public class ApplicationUser : IdentityUser
{
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
userIdentity.AddClaim(new Claim("PTLocationDistrict", this.PTLocationDistrict.ToString()));
return userIdentity;
}
// Additional properties for the Application User
public PTLocationDistrict? PTLocationDistrict { get; set; }
}
Identity Services:
public static PTLocationDistrict? GetPTLocationDistrict(this IIdentity identity)
{
Claim claim = ((ClaimsIdentity)identity).FindFirst("PTLocationDistrict");
PTLocationDistrict value;
if (claim == null)
{
return null;
}
else if (Enum.TryParse(claim.Value, out value))
{
return value;
}
else
{
return null;
}
}
Dashboard Report Count Service:
public int GetCountToday(PTLocationDistrict? ptLocationDistrict)
{
try
{
var today = DateTime.Today;
IQueryable<SurveySession> surveySessions = _dbContext.SurveySessions.AsNoTracking().AsQueryable();
if (ptLocationDistrict != null)
{
surveySessions = surveySessions.Where(ss => ss.Location.District == ptLocationDistrict.Value);
}
int count = surveySessions
.Where(p => p.DateCreated >= today)
.Count();
return count;
}
catch (Exception error)
{
_logger.Error("[Error in SurveyService.GetCountToday" - Error: " + error + "]");
return 0;
}
}
Controller Action:
public virtual ActionResult Index()
{
IndexViewModel model = new IndexViewModel();
PTLocationDistrict? ptLocationDistrict = User.Identity.GetPTLocationDistrict();
// Realizados Hoje
model.SurveyCountToday = _surveyService.GetCountToday(ptLocationDistrict);
}