public ApplicationUser FindByName(string userName, bool withUserRoles = false) { var applicationUser = _applicationUserService.FindByName(userName); if (applicationUser == null) { return(null); } var applicationUserRoles = _applicationUserRoleService.GetAllUserRolesbyApplicationUserID(applicationUser.Id); // this builds the context for the user: which companies/divisions/departments he has access to //var contextOptions = GetUserContext(applicationUserRoles); //contextOptions.DefaultCompanyID = applicationUser.CompanyId.ToString(); //contextOptions.DefaultDepartmentID = applicationUser.DepartmentId.ToString(); //contextOptions.DefaultDivisionID = applicationUser.DivisionId.ToString(); if (applicationUser.Company != null) { applicationUser.Company.Logo = null; } //applicationUser.ContextOptions = contextOptions; var permissions = new List <PermissionShort>(); foreach (var applicationUserRole in applicationUserRoles) { foreach (var rolePermission in applicationUserRole.ApplicationRole.RolePermissions) { if (permissions.All(p => !(p.PermissionController + " / " + p.PermissionAction).Equals(rolePermission.Permission.PermissionName))) { permissions.Add(new PermissionShort() { PermissionController = rolePermission.Permission.PermissionController, PermissionAction = rolePermission.Permission.PermissionAction }); } } } applicationUser.Permissions = permissions; if (withUserRoles) { applicationUser.ApplicationUserRoleModels = applicationUser.ApplicationUserRoles.Select(aur => new ApplicationUserRoleModel() { UserRoleID = aur.UserRoleID, RoleID = aur.RoleID, CompanyId = aur.CompanyId ?? Guid.Empty, DivisionId = aur.DivisionId ?? Guid.Empty, DepartmentId = aur.DepartmentId ?? Guid.Empty, UserID = aur.UserID }).ToList(); } return(applicationUser); }