1189 lines
55 KiB
C#
1189 lines
55 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data.Entity.Infrastructure;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Transactions;
|
|
using System.Web.Mvc;
|
|
using EnVisage.Code.BLL;
|
|
using jQuery.DataTables.Mvc;
|
|
using System.Collections.ObjectModel;
|
|
using Microsoft.AspNet.Identity;
|
|
using Microsoft.AspNet.Identity.EntityFramework;
|
|
using EnVisage.Models;
|
|
using EnVisage.App_Start;
|
|
using EnVisage.Code;
|
|
using System.Text;
|
|
using EnVisage.Code.Cache;
|
|
using EnVisage.Models.Cache;
|
|
using EntityState = System.Data.Entity.EntityState;
|
|
using System.Web.UI;
|
|
using EnVisage.Code.Validation;
|
|
using Kendo.Mvc.Extensions;
|
|
using Resources;
|
|
using EnVisage.Code.Extensions;
|
|
using Prevu.Core.Main;
|
|
|
|
namespace EnVisage.Controllers
|
|
{
|
|
[Authorize]
|
|
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
|
|
public class UserController : BaseController
|
|
{
|
|
#region Properties
|
|
|
|
private IUserManager UserManager { get; }
|
|
|
|
#endregion
|
|
|
|
public class ListUsers
|
|
{
|
|
public string Id { get; set; }
|
|
public string UserName { get; set; }
|
|
public string Name { get; set; }
|
|
public string Email { get; set; }
|
|
public string Roles { get; set; }
|
|
public string WorkFlowRoles { get; set; }
|
|
}
|
|
|
|
public UserController(IUserManager userManager)
|
|
{
|
|
UserManager = userManager;
|
|
|
|
var cnt = new ApplicationDbContext();
|
|
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
var userValidator = um.UserValidator as UserValidator<ApplicationUser, string>;
|
|
if (userValidator != null) userValidator.AllowOnlyAlphanumericUserNames = true;
|
|
}
|
|
|
|
// GET: /User/
|
|
[AreaSecurity(area = Areas.Users, level = AccessLevel.Read)]
|
|
public ActionResult Index()
|
|
{
|
|
if (!SecurityManager.CheckSecurityObjectPermission(Areas.Users, AccessLevel.Read))
|
|
return Redirect("/");
|
|
return View(DbContext.AspNetUsers.ToList());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns JSON user list with filters and sort for jQuery DataTables
|
|
/// </summary>
|
|
[HttpPost]
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Read)]
|
|
public JsonResult Index(JQueryDataTablesModel jQueryDataTablesModel)
|
|
{
|
|
int totalRecordCount;
|
|
int searchRecordCount;
|
|
|
|
var users = GetUsers(startIndex: jQueryDataTablesModel.iDisplayStart,
|
|
pageSize: jQueryDataTablesModel.iDisplayLength, sortedColumns: jQueryDataTablesModel.GetSortedColumns(),
|
|
totalRecordCount: out totalRecordCount, searchRecordCount: out searchRecordCount, searchString: jQueryDataTablesModel.sSearch);
|
|
|
|
return this.DataTablesJson(items: users,
|
|
totalRecords: totalRecordCount,
|
|
totalDisplayRecords: searchRecordCount,
|
|
sEcho: jQueryDataTablesModel.sEcho);
|
|
|
|
}
|
|
|
|
private IList<ListUsers> GetUsers(int startIndex,
|
|
int pageSize,
|
|
ReadOnlyCollection<SortedColumn> sortedColumns,
|
|
out int totalRecordCount,
|
|
out int searchRecordCount,
|
|
string searchString)
|
|
{
|
|
var query = DbContext.AspNetUsers.Select(c=>
|
|
new
|
|
{
|
|
c.Discriminator,
|
|
c.Id,
|
|
c.UserName,
|
|
c.LastName,
|
|
Name = c.FirstName + " " + c.LastName,
|
|
c.Email,
|
|
RolesArr = c.AspNetRoles.ToList(),
|
|
WorkFlowRolesArr = c.User2WorkFlowRole.ToList()
|
|
});
|
|
// do not display API users, consider to user ClaimsType.Roles to separate different types of users
|
|
query =query.Where(x => x.Discriminator == "ApplicationUser" || string.IsNullOrEmpty (x.Discriminator));
|
|
|
|
//filter
|
|
if (!string.IsNullOrWhiteSpace(searchString))
|
|
{
|
|
query = query.Where(c => c.Name.ToLower().Contains(searchString.ToLower()) || c.UserName.ToLower().Contains(searchString.ToLower()) || c.Email.ToLower().Contains(searchString.ToLower()));
|
|
}
|
|
|
|
//sort
|
|
foreach (var sortedColumn in sortedColumns)
|
|
{
|
|
switch (sortedColumn.PropertyName)
|
|
{
|
|
case "Id":
|
|
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Id) : query.OrderByDescending(c => c.Id);
|
|
break;
|
|
case "Email":
|
|
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Email) : query.OrderByDescending(c => c.Email);
|
|
break;
|
|
case "UserName":
|
|
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.UserName) : query.OrderByDescending(c => c.UserName);
|
|
break;
|
|
case "LastName":
|
|
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.LastName) : query.OrderByDescending(c => c.LastName);
|
|
break;
|
|
default:
|
|
query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Name) : query.OrderByDescending(c => c.Name);
|
|
break;
|
|
}
|
|
}
|
|
|
|
totalRecordCount = DbContext.AspNetUsers.Count();
|
|
var list = query.Skip(startIndex).Take(pageSize).AsEnumerable()
|
|
.Select(x => new ListUsers
|
|
{
|
|
Id = x.Id,
|
|
UserName = x.UserName,
|
|
Name = x.Name,
|
|
Email = x.Email,
|
|
Roles = String.Join(", ", x.RolesArr.Select(r => r.Name)),
|
|
WorkFlowRoles = String.Join(", ", x.WorkFlowRolesArr.Select(r => r.WorkFlowRole.RoleName))
|
|
})
|
|
.ToList();
|
|
searchRecordCount = query.Count();
|
|
return list;
|
|
}
|
|
|
|
// GET: /User/Edit/5
|
|
[AreaSecurity(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult Edit(string id)
|
|
{
|
|
Models.UserModel aspnetuser = new Models.UserModel();
|
|
if (!string.IsNullOrEmpty(id))
|
|
{
|
|
aspnetuser = new Models.UserModel(DbContext.AspNetUsers.Find(id));
|
|
if (aspnetuser.Id == Guid.Empty)
|
|
{
|
|
return HttpNotFound();
|
|
}
|
|
|
|
// Load user attached companies
|
|
var userid = aspnetuser.Id.ToString();
|
|
aspnetuser.CompaniesWatcher = DbContext.User2Company.Where(x => x.UserId.Equals(aspnetuser.Id) && (x.RelationType == CollaborationRole.Watcher)).Select(x => x.CompanyId).ToList();
|
|
aspnetuser.CompaniesContributor = DbContext.User2Company.Where(x => x.UserId.Equals(aspnetuser.Id) && (x.RelationType == CollaborationRole.Contributor)).Select(x => x.CompanyId).ToList();
|
|
aspnetuser.WorkFlowRoles = DbContext.User2WorkFlowRole.Where(x => x.UserId == userid).Select(x => x.RoleId).ToList();
|
|
}
|
|
|
|
return View(aspnetuser);
|
|
}
|
|
[HttpPost]
|
|
public ActionResult Test()
|
|
{
|
|
return Json(new object());
|
|
}
|
|
// POST: /User/Edit/5
|
|
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
|
|
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
|
|
[HttpPost]
|
|
[ValidateAntiForgeryToken]
|
|
[ValidateAjax]
|
|
[AreaSecurity(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult Edit(EditPermissionModel edituser)
|
|
{
|
|
edituser.TrimStringProperties();
|
|
var projecttree = edituser.projecttree;
|
|
var aspnetuser = edituser.aspnetuser;
|
|
|
|
var isNewUser = (aspnetuser.Id == Guid.Empty);
|
|
if (!isNewUser && ContentLocker.IsLock("User", aspnetuser.Id.ToString(), User.Identity.GetUserName()))
|
|
{
|
|
ModelState.AddModelError(string.Empty, Messages.User_UpdatedByAnotherUser);
|
|
return new FailedJsonResult(ModelState);
|
|
//return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
|
|
}
|
|
try
|
|
{
|
|
var areasReadInherited = new List<Areas>();
|
|
var areasWriteInherited = new List<Areas>();
|
|
var projectListReadInherited = new List<Guid>();
|
|
var projectListWriteInherited = new List<Guid>();
|
|
projecttree.Overriden.Where(x => "areasread".Equals(x.Split('|')[0])).ToList().ForEach(x => areasReadInherited.Add((Areas) Enum.Parse(typeof(Areas), x.Split('|')[1])));
|
|
projecttree.Overriden.Where(x => "areaswrite".Equals(x.Split('|')[0])).ToList().ForEach(x => areasWriteInherited.Add((Areas) Enum.Parse(typeof(Areas), x.Split('|')[1])));
|
|
projecttree.Overriden.Where(x => "projectlistread".Equals(x.Split('|')[0])).ToList().ForEach(x => projectListReadInherited.Add(Guid.Parse(x.Split('|')[1])));
|
|
projecttree.Overriden.Where(x => "projectlistwrite".Equals(x.Split('|')[0])).ToList().ForEach(x => projectListWriteInherited.Add(Guid.Parse(x.Split('|')[1])));
|
|
var roleIds = (projecttree.RoleItems ?? new List<string>()).Select(t => new Guid(t).ToString()).ToList<string>();
|
|
|
|
if (projecttree.ProjectList == null) projecttree.ProjectList = new List<ProjectPermission>();
|
|
if (projecttree.AreaList == null) projecttree.AreaList = new List<AreaPermission>();
|
|
if (projecttree.RoleItems == null) projecttree.RoleItems = new List<string>();
|
|
if (projecttree.Overriden == null) projecttree.Overriden = new List<string>();
|
|
|
|
var context = new EnVisageEntities();
|
|
|
|
#region Create new user
|
|
Guid userId;
|
|
if (isNewUser)
|
|
{
|
|
short userType = (int) UserType.Pending;
|
|
if (this.HttpContext.User.Identity.isSSO())
|
|
userType = (int) UserType.Active;
|
|
|
|
var cnt = new ApplicationDbContext();
|
|
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
var userValidator = userManager.UserValidator as UserValidator<ApplicationUser, string>;
|
|
if (userValidator != null)
|
|
userValidator.AllowOnlyAlphanumericUserNames = false;
|
|
try
|
|
{
|
|
|
|
userManager.Create(new ApplicationUser
|
|
{
|
|
UserName = aspnetuser.UserName,
|
|
FirstName = aspnetuser.FirstName,
|
|
LastName = aspnetuser.LastName,
|
|
Email = aspnetuser.Email,
|
|
PhoneNumber = aspnetuser.Phone, // string.Empty,
|
|
Type = userType,
|
|
PreferredResourceAllocation = aspnetuser.PreferredResourceAllocation,
|
|
PreferredTotalsDisplaying = aspnetuser.PreferredTotalsDisplaying,
|
|
ShowAutomaticViews = aspnetuser.ShowAutomaticViews,
|
|
OverUnderCoefficient = aspnetuser.OverUnderCoefficient
|
|
}, AppSettingsManager.DefaultPassword);
|
|
|
|
cnt.SaveChanges();
|
|
}
|
|
catch (Exception createNewUseEx)
|
|
{
|
|
ModelState.AddModelError("", Messages.User_Create_Error_ReviewYourEntries);
|
|
LogException(createNewUseEx);
|
|
|
|
return new FailedJsonResult(ModelState);
|
|
}
|
|
try
|
|
{
|
|
userId = new Guid(userManager.FindByName(aspnetuser.UserName).Id);
|
|
|
|
aspnetuser.Id = userId;// userId.ToString();
|
|
|
|
if (projecttree.RoleItems != null)
|
|
{
|
|
foreach (var roleitem in projecttree.RoleItems)
|
|
{
|
|
var role = context.AspNetRoles.FirstOrDefault(pr => pr.Id == roleitem);
|
|
if (!userManager.IsInRole(userId.ToString(), role.Name))
|
|
userManager.AddToRole(userId.ToString(), role.Name);
|
|
}
|
|
}
|
|
|
|
new UsersCache().Invalidate();
|
|
|
|
MailManager.SendInvitationMessage(aspnetuser.Email, aspnetuser.UserName, userId.ToString(), this.HttpContext.User.Identity.isSSO());
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
ModelState.AddModelError("", Messages.User_Create_Error_ReviewYourEntries);
|
|
LogException(ex);
|
|
|
|
return new FailedJsonResult(ModelState);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
userId = aspnetuser.Id;
|
|
}
|
|
#endregion
|
|
|
|
#region Save Projects
|
|
|
|
//EnVisageEntities context = new EnVisageEntities();
|
|
var projectAccessCache = new ProjectAccessCache();
|
|
var projects = context.Projects.Where(pr => !pr.HasChildren).OrderBy(pr => pr.Name).ToList();
|
|
if (projects.Count > 0)
|
|
{
|
|
var permissions = context.ProjectAccesses.Where(pr => pr.PrincipalId == userId)
|
|
.ToDictionary(userProjectAccess => new Tuple<Guid, Guid>(userProjectAccess.PrincipalId, userProjectAccess.ProjectId));
|
|
var rolePermissions = context.ProjectAccesses.Where(pr => roleIds.Contains(pr.PrincipalId.ToString())).ToArray();
|
|
permissions.AddRange(rolePermissions.ToDictionary(p => new Tuple<Guid, Guid>(p.PrincipalId, p.ProjectId), p=>p));
|
|
|
|
foreach (var project in projects)
|
|
{
|
|
var userProjectAccess = permissions.ContainsKey(new Tuple<Guid, Guid>(userId, project.Id))
|
|
? permissions.FirstOrDefault(t => t.Key.Item1 == userId && t.Key.Item2 == project.Id).Value
|
|
: null;
|
|
var roleProjectAcesses = rolePermissions.Where(t => t.ProjectId == project.Id).ToArray();
|
|
var isInheritedRead = projectListReadInherited.Contains(project.Id);
|
|
var isInheritedWrite = projectListWriteInherited.Contains(project.Id);
|
|
var UIProjectList = from m in projecttree.ProjectList
|
|
where m.id == project.Id.ToString()
|
|
select m;
|
|
var UIProject = UIProjectList.FirstOrDefault();
|
|
|
|
var newRead = Permission.Deny;
|
|
if (isInheritedRead)
|
|
{
|
|
if (UIProject == null)
|
|
newRead = Permission.Inherited;
|
|
else if (!UIProject.p.read)
|
|
newRead = Permission.Deny;
|
|
else
|
|
newRead = Permission.Inherited;
|
|
}
|
|
else
|
|
{
|
|
if (UIProject == null)
|
|
newRead = Permission.Deny;
|
|
else if (UIProject.p.read)
|
|
newRead = Permission.Allow;
|
|
}
|
|
|
|
|
|
//var newRead = isInheritedRead ? Permission.Inherited
|
|
// :(UIProject != null && UIProject.p.read
|
|
// ? Permission.Allow
|
|
// : Permission.Deny);
|
|
var newWrite = Permission.Deny;
|
|
if (isInheritedWrite)
|
|
{
|
|
if (UIProject == null)
|
|
newWrite = Permission.Inherited;
|
|
else if (!UIProject.p.write)
|
|
newWrite = Permission.Deny;
|
|
else
|
|
newWrite = Permission.Inherited;
|
|
}
|
|
else
|
|
{
|
|
if (UIProject == null)
|
|
newWrite = Permission.Deny;
|
|
else if (UIProject.p.write)
|
|
newWrite = Permission.Allow;
|
|
}
|
|
//var newWrite = (isInheritedRead && ((UIProject != null && UIProject.p.write) ? Permission.Inherited
|
|
// : (UIProject != null && UIProject.p.write
|
|
// ? Permission.Allow
|
|
// : Permission.Deny);
|
|
|
|
// build new values
|
|
//var newRead = isInheritedRead ? Permission.Inherited
|
|
// : projecttree.ProjectListRead.Contains(project.Id.ToString())
|
|
// ? Permission.Allow
|
|
// : Permission.Deny;
|
|
//var newWrite = isInheritedWrite ? Permission.Inherited
|
|
// : projecttree.ProjectListWrite.Contains(project.Id.ToString())
|
|
// ? Permission.Allow
|
|
// : Permission.Deny;
|
|
// if read option has been inherited then we should set inherited value
|
|
var roleRead = roleProjectAcesses.Any(t => t.Read == (int) Permission.Allow) ? Permission.Allow : Permission.Deny;
|
|
if (newRead == Permission.Inherited)
|
|
newRead = roleRead;
|
|
// if write option has been inherited then we should set inherited value
|
|
var roleWrite = roleProjectAcesses.Any(t => t.Write == (int) Permission.Allow) ? Permission.Allow : Permission.Deny;
|
|
if (newWrite == Permission.Inherited)
|
|
newWrite = roleWrite;
|
|
var readIsChanged = roleRead != newRead;
|
|
var writeIsChanged = roleWrite != newWrite;
|
|
//check if the permission set is inherited, if so
|
|
//make sure we capture the change on a user level.
|
|
//if isInheritedread means one of the user roles
|
|
//has permission to do the read
|
|
if (isInheritedRead && newRead == Permission.Deny && roleProjectAcesses.Length > 0)
|
|
{
|
|
readIsChanged = true;
|
|
isInheritedRead = false;
|
|
}
|
|
if (isInheritedWrite && newWrite == Permission.Deny && roleProjectAcesses.Length > 0)
|
|
{
|
|
writeIsChanged = true;
|
|
isInheritedWrite = false;
|
|
}
|
|
if (userProjectAccess == null)
|
|
{
|
|
if ((!isInheritedRead || !isInheritedWrite) && (readIsChanged || writeIsChanged))
|
|
{
|
|
if (!permissions.ContainsKey(new Tuple<Guid, Guid>(userId, project.Id)))
|
|
{
|
|
var newpa = new ProjectAccess
|
|
{
|
|
PrincipalId = userId,
|
|
ProjectId = project.Id,
|
|
Read = (int) newRead,
|
|
Write = (int) newWrite
|
|
};
|
|
context.ProjectAccesses.Add(newpa);
|
|
permissions.Add(new Tuple<Guid, Guid>(userId, project.Id), newpa);
|
|
}
|
|
if (project.ParentProjectId.HasValue)
|
|
{
|
|
if (!permissions.ContainsKey(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value)))
|
|
{
|
|
var parentPA = new ProjectAccess
|
|
{
|
|
PrincipalId = userId,
|
|
ProjectId = project.ParentProjectId.Value,
|
|
Read = (int) 1,
|
|
Write = (int) 1
|
|
};
|
|
context.ProjectAccesses.Add(parentPA);
|
|
permissions.Add(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value), parentPA);
|
|
}
|
|
else
|
|
{
|
|
var parentPA = permissions.ContainsKey(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value))
|
|
? permissions.FirstOrDefault(t => t.Key.Item1 == userId && t.Key.Item2 == project.ParentProjectId.Value).Value
|
|
: null;
|
|
if (parentPA != null && context.Entry(parentPA).State == EntityState.Unchanged || context.Entry(parentPA).State == EntityState.Modified)
|
|
{
|
|
parentPA.Read = 1;
|
|
parentPA.Write = 1;
|
|
context.Entry(parentPA).State = EntityState.Modified;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if ((!isInheritedRead || !isInheritedWrite) && (readIsChanged || writeIsChanged))
|
|
{
|
|
userProjectAccess.Read = (int) newRead;
|
|
userProjectAccess.Write = (int) newWrite;
|
|
if (project.ParentProjectId.HasValue)
|
|
{
|
|
if (!permissions.ContainsKey(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value)))
|
|
{
|
|
var parentPA = new ProjectAccess
|
|
{
|
|
PrincipalId = userId,
|
|
ProjectId = project.ParentProjectId.Value,
|
|
Read = 1,
|
|
Write = 1
|
|
};
|
|
context.ProjectAccesses.Add(parentPA);
|
|
permissions.Add(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value), parentPA);
|
|
}
|
|
else
|
|
{
|
|
var parentPA = permissions.ContainsKey(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value))
|
|
? permissions.FirstOrDefault(t => t.Key.Item1 == userId && t.Key.Item2 == project.ParentProjectId.Value).Value
|
|
: null;
|
|
if (parentPA != null && context.Entry(parentPA).State == EntityState.Unchanged || context.Entry(parentPA).State == EntityState.Modified)
|
|
{
|
|
parentPA.Read = 1;
|
|
parentPA.Write = 1;
|
|
context.Entry(parentPA).State = EntityState.Modified;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (context.Entry(userProjectAccess).State == EntityState.Unchanged ||
|
|
context.Entry(userProjectAccess).State == EntityState.Modified)
|
|
{
|
|
context.ProjectAccesses.Remove(userProjectAccess);
|
|
permissions.Remove(new Tuple<Guid, Guid>(userId, project.Id));
|
|
}
|
|
if (project.ParentProjectId.HasValue)
|
|
{
|
|
var projectParts =
|
|
projects.Where(t => t.ParentProjectId == project.ParentProjectId.Value).Select(t => t.Id).ToArray();
|
|
var otherPartsAccess = permissions.Where(t => projectParts.Contains(t.Key.Item2) && t.Key.Item2 != project.ParentProjectId.Value);
|
|
if (!otherPartsAccess.Any())
|
|
{
|
|
var parentPA = permissions.ContainsKey(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value))
|
|
? permissions.FirstOrDefault(t => t.Key.Item1 == userId && t.Key.Item2 == project.ParentProjectId.Value).Value
|
|
: null;
|
|
if ((parentPA != null && context.Entry(parentPA).State == EntityState.Unchanged )||
|
|
(parentPA != null && context.Entry(parentPA).State == EntityState.Modified))
|
|
{
|
|
context.ProjectAccesses.Remove(parentPA);
|
|
permissions.Remove(new Tuple<Guid, Guid>(userId, project.ParentProjectId.Value));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
context.SaveChanges();
|
|
projectAccessCache.Invalidate();
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Save Areas
|
|
|
|
var securityAreasCache = new SecurityAreasCache();
|
|
var areas = Enum.GetValues(typeof(Areas)).Cast<Areas>().ToArray();
|
|
if (areas.Length > 0)
|
|
{
|
|
var areaStrings = areas.Select(t => t.ToString());
|
|
var userPermissions = (from pr in context.Securities
|
|
where pr.PrincipalId == userId && areaStrings.Contains(pr.SecurityObject)
|
|
select pr).ToArray();
|
|
var rolePermissions = (from pr in context.Securities
|
|
where roleIds.Contains(pr.PrincipalId.ToString())
|
|
select pr).ToArray();
|
|
foreach (var area in areas)
|
|
{
|
|
var areaStr = area.ToString();
|
|
var isInheritedRead = areasReadInherited.Contains(area);
|
|
var isInheritedWrite = areasWriteInherited.Contains(area);
|
|
var userPermission = userPermissions.FirstOrDefault(t => t.SecurityObject == areaStr);
|
|
var roleAreaPermissions = rolePermissions.Where(t => t.SecurityObject == areaStr).ToArray();
|
|
// build new values
|
|
var UIAreaList = from m in projecttree.AreaList
|
|
where m.id == area.ToString()
|
|
select m;
|
|
|
|
var UIArea = UIAreaList.FirstOrDefault();
|
|
var newRead = Permission.Deny;
|
|
if (isInheritedRead)
|
|
{
|
|
if (UIArea == null)
|
|
newRead = Permission.Inherited;
|
|
else if (!UIArea.p.read)
|
|
newRead = Permission.Deny;
|
|
else
|
|
newRead = Permission.Inherited;
|
|
}
|
|
else
|
|
{
|
|
if (UIArea == null)
|
|
newRead = Permission.Deny;
|
|
else if (UIArea.p.read)
|
|
newRead = Permission.Allow;
|
|
}
|
|
|
|
|
|
//var newRead = isInheritedRead ? Permission.Inherited
|
|
// : (UIArea != null && UIArea.p.read
|
|
//? Permission.Allow
|
|
//: Permission.Deny);
|
|
var newWrite = Permission.Deny;
|
|
if (isInheritedWrite)
|
|
{
|
|
if (UIArea == null)
|
|
newWrite = Permission.Inherited;
|
|
else if (!UIArea.p.write)
|
|
newWrite = Permission.Deny;
|
|
else
|
|
newWrite = Permission.Inherited;
|
|
}
|
|
else
|
|
{
|
|
if (UIArea == null)
|
|
newWrite = Permission.Deny;
|
|
else if (UIArea.p.write)
|
|
newWrite = Permission.Allow;
|
|
}
|
|
// var newWrite = isInheritedRead ? Permission.Inherited
|
|
// : (UIArea != null && UIArea.p.write
|
|
//? Permission.Allow
|
|
//: Permission.Deny);
|
|
//var newRead = isInheritedRead ? Permission.Inherite
|
|
// : (projecttree.AreasRead != null && projecttree.AreasRead.Contains(area.ToString())
|
|
// ? Permission.Allow
|
|
// : Permission.Deny);
|
|
//var newWrite = isInheritedWrite ? Permission.Inherited
|
|
// : (projecttree.AreasWrite != null && projecttree.AreasWrite.Contains(area.ToString())
|
|
// ? Permission.Allow
|
|
// : Permission.Deny);
|
|
// if read option has been inherited then we should set inherited value
|
|
var roleRead = roleAreaPermissions.Any(t => t.Read == (int) Permission.Allow) ? Permission.Allow : Permission.Deny;
|
|
if (newRead == Permission.Inherited)
|
|
newRead = roleRead;
|
|
// if write option has been inherited then we should set inherited value
|
|
var roleWrite = roleAreaPermissions.Any(t => t.Write == (int) Permission.Allow) ? Permission.Allow : Permission.Deny;
|
|
if (newWrite == Permission.Inherited)
|
|
newWrite = roleWrite;
|
|
var readIsChanged = roleRead != newRead;
|
|
var writeIsChanged = roleWrite != newWrite;
|
|
|
|
//check if the permission set is inherited, if so
|
|
//make sure we capture the change on a user level.
|
|
//if isInheritedread means one of the user roles
|
|
//has permission to do the read
|
|
if (isInheritedRead && newRead == Permission.Deny && roleAreaPermissions.Length > 0)
|
|
{
|
|
readIsChanged = true;
|
|
isInheritedRead = false;
|
|
}
|
|
if (isInheritedWrite && newWrite == Permission.Deny && roleAreaPermissions.Length > 0)
|
|
{
|
|
writeIsChanged = true;
|
|
isInheritedWrite = false;
|
|
}
|
|
|
|
// if there is no user permission in DB
|
|
if (userPermission == null)
|
|
{
|
|
// if any of read/write permission has been overriden on the form
|
|
if ((!isInheritedRead || !isInheritedWrite) && (readIsChanged || writeIsChanged))
|
|
{
|
|
var newpa = new Security
|
|
{
|
|
PrincipalId = userId,
|
|
SecurityObject = area.ToString(),
|
|
Read = (int) newRead,
|
|
Write = (int) newWrite
|
|
};
|
|
context.Securities.Add(newpa);
|
|
}
|
|
}
|
|
else // if there is a user permission in DB
|
|
{
|
|
// if any of read/write permission has been overriden on the form
|
|
if ((!isInheritedRead || !isInheritedWrite) && (readIsChanged || writeIsChanged))
|
|
{
|
|
userPermission.Read = (int) newRead;
|
|
userPermission.Write = (int) newWrite;
|
|
}
|
|
else
|
|
{
|
|
// if new values equal to old values then remove user record as we should inherit permissions from role this way
|
|
context.Securities.Remove(userPermission);
|
|
}
|
|
}
|
|
}
|
|
context.SaveChanges();
|
|
securityAreasCache.Invalidate();
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Update existing user
|
|
if (!isNewUser)
|
|
{
|
|
var cnt = new ApplicationDbContext();
|
|
|
|
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
|
|
foreach (var userrole in userManager.GetRoles(aspnetuser.Id.ToString()))
|
|
{
|
|
var role = (from pr in context.AspNetRoles
|
|
where pr.Name == userrole
|
|
select pr).FirstOrDefault();
|
|
if (projecttree.RoleItems == null || !projecttree.RoleItems.Contains(role.Id.ToString()))
|
|
userManager.RemoveFromRole(aspnetuser.Id.ToString(), userrole);
|
|
}
|
|
if (projecttree.RoleItems != null)
|
|
{
|
|
foreach (var roleitem in projecttree.RoleItems)
|
|
{
|
|
var role = (from pr in context.AspNetRoles
|
|
where pr.Id == roleitem
|
|
select pr).FirstOrDefault();
|
|
if (!userManager.IsInRole(aspnetuser.Id.ToString(), role.Name))
|
|
userManager.AddToRole(aspnetuser.Id.ToString(), role.Name);
|
|
}
|
|
}
|
|
ApplicationUser u = userManager.FindById(aspnetuser.Id.ToString());
|
|
u.UserName = aspnetuser.UserName;
|
|
u.FirstName = aspnetuser.FirstName;
|
|
u.LastName = aspnetuser.LastName;
|
|
u.Email = aspnetuser.Email;
|
|
u.PhoneNumber = aspnetuser.Phone;
|
|
u.PreferredResourceAllocation = aspnetuser.PreferredResourceAllocation;
|
|
u.PreferredTotalsDisplaying = aspnetuser.PreferredTotalsDisplaying;
|
|
u.ShowAutomaticViews = aspnetuser.ShowAutomaticViews;
|
|
u.OverUnderCoefficient = aspnetuser.OverUnderCoefficient;
|
|
userManager.Update(u);
|
|
|
|
cnt.SaveChanges();
|
|
}
|
|
#endregion
|
|
|
|
#region Save user Companies
|
|
|
|
var recsToRemove = context.User2Company.Where(x => x.UserId.Equals(userId)).ToList();
|
|
var companiesChanged = recsToRemove.Count > 0;
|
|
context.User2Company.RemoveRange(recsToRemove);
|
|
|
|
var contrs = FilterCompanyList(context, aspnetuser.CompaniesContributor, null);
|
|
|
|
if ((contrs != null) && (contrs.Count > 0))
|
|
{
|
|
companiesChanged = SaveUserCompanies(userId, contrs, CollaborationRole.Contributor, context) || companiesChanged;
|
|
}
|
|
|
|
var watchersFiltered = FilterCompanyList(context, aspnetuser.CompaniesWatcher, contrs);
|
|
|
|
if ((watchersFiltered != null) && (watchersFiltered.Count > 0))
|
|
{
|
|
companiesChanged = SaveUserCompanies(userId, watchersFiltered, CollaborationRole.Watcher, context) || companiesChanged;
|
|
}
|
|
|
|
if (companiesChanged)
|
|
{
|
|
context.SaveChanges();
|
|
}
|
|
|
|
#endregion
|
|
#region WorkFlowRoles
|
|
|
|
var user2wfroles = context.User2WorkFlowRole.Where(x => x.UserId ==userId.ToString()).ToList();
|
|
var wfRolesChanged = user2wfroles.Count > 0;
|
|
var wfRecsChanged = false;
|
|
foreach (var u2WfRec in user2wfroles)
|
|
{
|
|
if (!edituser.aspnetuser.WorkFlowRoles.Contains(u2WfRec.RoleId))
|
|
{
|
|
context.User2WorkFlowRole.Remove(u2WfRec);
|
|
context.Entry(u2WfRec).State = EntityState.Deleted;
|
|
wfRecsChanged = true;
|
|
}
|
|
}
|
|
foreach (var wfRoleId in edituser.aspnetuser.WorkFlowRoles)
|
|
{
|
|
var oldRec = user2wfroles.Where(x => x.RoleId == wfRoleId).FirstOrDefault();
|
|
if (oldRec == null)
|
|
{
|
|
var efRec = new User2WorkFlowRole()
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
RoleId = wfRoleId,
|
|
UserId = userId.ToString()
|
|
};
|
|
context.User2WorkFlowRole.Add(efRec);
|
|
context.Entry(efRec).State = EntityState.Added;
|
|
wfRecsChanged = true;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
if (wfRecsChanged)
|
|
{
|
|
context.SaveChanges();
|
|
}
|
|
#endregion
|
|
new UsersCache().Invalidate();
|
|
ContentLocker.RemoveLock("User", aspnetuser.Id.ToString(), User.Identity.GetUserName());
|
|
return new SuccessJsonResult();
|
|
//return new HttpStatusCodeResult(HttpStatusCode.OK);
|
|
}
|
|
catch (BLLException blEx) // handle any system specific error
|
|
{
|
|
// display error message if required
|
|
if (blEx.DisplayError)
|
|
ModelState.AddModelError(string.Empty, blEx.Message);
|
|
else // if display not requried then display modal form with general error message
|
|
{
|
|
LogException(blEx);
|
|
ModelState.AddModelError(string.Empty, Messages.Accoun_SaveUser_Error);
|
|
}
|
|
}
|
|
catch (Exception exception) // handle any unexpected error
|
|
{
|
|
LogException(exception);
|
|
ModelState.AddModelError(string.Empty, Messages.Accoun_SaveUser_Error);
|
|
}
|
|
|
|
return new FailedJsonResult(ModelState);
|
|
}
|
|
|
|
[HttpPost]
|
|
//[ValidateAntiForgeryToken]
|
|
[AreaSecurity(area = Areas.Users, level = AccessLevel.Write)]
|
|
public JsonResult GetRolePermissions(Guid[] roleId)
|
|
{
|
|
if (roleId == null)
|
|
{
|
|
return Json("[[],[]]");
|
|
}
|
|
|
|
StringBuilder sb = new StringBuilder();
|
|
StringBuilder sb1 = new StringBuilder();
|
|
sb.Append("[");
|
|
sb1.Append("[");
|
|
//if (roleId.HasValue && !Guid.Empty.Equals(roleId.Value))
|
|
{
|
|
//var list = roleId.Select(x => Guid.Parse(x));
|
|
EnVisageEntities context = new EnVisageEntities();
|
|
SecurityAreasCache securityAreasCache = new SecurityAreasCache();
|
|
var accessForRoles = (from pr in securityAreasCache.Value
|
|
where roleId.Contains(pr.PrincipalId)
|
|
select pr).ToList();
|
|
|
|
var projects = (from pr in context.Projects
|
|
select pr).ToList();
|
|
|
|
var accessForProjects = (from pr in new ProjectAccessCache().Value
|
|
where roleId.Contains(pr.PrincipalId)
|
|
select pr).ToList();
|
|
|
|
|
|
foreach (var area in Enum.GetValues(typeof(Areas)))
|
|
{
|
|
List<UserAreaAccess> items = accessForRoles.Where(x => x.SecurityObject.Equals(area.ToString())).ToList();
|
|
if (!items.Any())
|
|
continue;
|
|
//area, area_read, area_write, area_read_disabled, area_write_disabled
|
|
sb.AppendFormat("[\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\"],",
|
|
area, items.Exists(x => x.Read == 1), items.Exists(x => x.Write == 1), items.Exists(x => x.Read != 2), items.Exists(x => x.Write != 2));
|
|
}
|
|
|
|
foreach (var project in projects)
|
|
{
|
|
var items = accessForProjects.Where(x => x.ProjectId.Equals(project.Id)).ToList();
|
|
if (!items.Any())
|
|
continue;
|
|
//projectId, project_read, project_write, project_read_disabled, project_write_disabled
|
|
sb1.AppendFormat("[\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\"],",
|
|
project.Id, items.Exists(x => x.Read == 1), items.Exists(x => x.Write == 1), items.Exists(x => x.Read != 2), items.Exists(x => x.Write != 2));
|
|
|
|
|
|
}
|
|
}
|
|
return Json("[" + sb.ToString().TrimEnd(',') + "]," + sb1.ToString().TrimEnd(',') + "]]");
|
|
}
|
|
|
|
// GET: /User/Delete/5
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult Delete(string id)
|
|
{
|
|
if (id == null)
|
|
{
|
|
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
|
|
}
|
|
AspNetUser aspnetuser = DbContext.AspNetUsers.Find(id);
|
|
if (aspnetuser == null)
|
|
{
|
|
return HttpNotFound();
|
|
}
|
|
return View(aspnetuser);
|
|
}
|
|
|
|
// POST: /User/Delete/5
|
|
[HttpPost, ActionName("Delete")]
|
|
[ValidateAntiForgeryToken]
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult DeleteConfirmed(string id)
|
|
{
|
|
if (ContentLocker.IsLock("User", id, User.Identity.GetUserName()))
|
|
{
|
|
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
|
|
}
|
|
using (var transactionScope = new TransactionScope())
|
|
{
|
|
AspNetUser aspnetuser = DbContext.AspNetUsers.AsNoTracking().FirstOrDefault(t => t.Id == id);
|
|
(DbContext as IObjectContextAdapter).ObjectContext.ExecuteStoreCommand(
|
|
string.Format("exec sp_DeleteUser '{0}'", aspnetuser.Id));
|
|
transactionScope.Complete();
|
|
}
|
|
new UsersCache().Invalidate();
|
|
|
|
ContentLocker.RemoveLock("User", id, User.Identity.GetUserName());
|
|
return RedirectToAction("Index");
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult SavePreferences(string url, string section, string data)
|
|
{
|
|
string userIdAsText = User.Identity.GetID();
|
|
var pageUrl = url.TrimEnd('/');
|
|
|
|
try
|
|
{
|
|
// Validate user
|
|
var user = DbContext.AspNetUsers.FirstOrDefault(t => t.Id == userIdAsText);
|
|
Guid userId = new Guid(userIdAsText);
|
|
|
|
if (user == null)
|
|
throw new Exception($"Unknown user id ({userIdAsText})");
|
|
|
|
UserPreference pagePrefs = DbContext.UserPreferences.FirstOrDefault(x => userId.Equals(x.UserId) &&
|
|
x.Url.Equals(pageUrl, StringComparison.InvariantCultureIgnoreCase) &&
|
|
x.Section.Equals(section, StringComparison.InvariantCultureIgnoreCase));
|
|
|
|
if (pagePrefs == null)
|
|
{
|
|
pagePrefs = new UserPreference
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
UserId = userId,
|
|
Url = pageUrl,
|
|
Section = section
|
|
};
|
|
|
|
DbContext.UserPreferences.Add(pagePrefs);
|
|
}
|
|
|
|
pagePrefs.Data = data;
|
|
DbContext.SaveChanges();
|
|
|
|
return new HttpStatusCodeResult(HttpStatusCode.OK);
|
|
}
|
|
catch (BLLException blEx)
|
|
{
|
|
if (blEx.DisplayError)
|
|
SetErrorScript(message: blEx.Message);
|
|
else
|
|
{
|
|
LogException(blEx);
|
|
SetErrorScript();
|
|
}
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
LogException(exception);
|
|
SetErrorScript();
|
|
}
|
|
|
|
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
|
|
}
|
|
|
|
[HttpPost]
|
|
[Obsolete("Use GetPagePreferences method to load all sections for the page instead of separate ajax call for each section")]
|
|
public ActionResult GetPreferences(string url, string section)
|
|
{
|
|
try
|
|
{
|
|
var userId = SecurityManager.GetUserPrincipal();
|
|
var pagePreferences = new
|
|
{
|
|
Status = "OK",
|
|
Data = UserManager.GetPagePreferences(url, section, userId)
|
|
};
|
|
|
|
return Json(pagePreferences, JsonRequestBehavior.AllowGet);
|
|
}
|
|
catch (BLLException blEx)
|
|
{
|
|
if (blEx.DisplayError)
|
|
SetErrorScript(message: blEx.Message);
|
|
else
|
|
{
|
|
LogException(blEx);
|
|
SetErrorScript();
|
|
}
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
LogException(exception);
|
|
SetErrorScript();
|
|
}
|
|
|
|
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult GetPagePreferences(string url)
|
|
{
|
|
try
|
|
{
|
|
var userId = SecurityManager.GetUserPrincipal();
|
|
var preferences = UserManager.GetPagePreferences(url, userId);
|
|
var pagePreferences = new
|
|
{
|
|
Status = "OK",
|
|
Data = preferences
|
|
};
|
|
|
|
return Json(pagePreferences, JsonRequestBehavior.AllowGet);
|
|
}
|
|
catch (BLLException blEx)
|
|
{
|
|
if (blEx.DisplayError)
|
|
SetErrorScript(message: blEx.Message);
|
|
else
|
|
{
|
|
LogException(blEx);
|
|
SetErrorScript();
|
|
}
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
LogException(exception);
|
|
SetErrorScript();
|
|
}
|
|
|
|
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
|
|
}
|
|
|
|
protected class ListItem
|
|
{
|
|
public Guid Id { get; set; }
|
|
public string Name { get; set; }
|
|
}
|
|
|
|
protected class ProjectListItem : ListItem
|
|
{
|
|
public bool Read { get; set; }
|
|
public bool ReadInherited { get; set; }
|
|
public bool RoleRead { get; set; }
|
|
public bool Write { get; set; }
|
|
public bool WriteInherited { get; set; }
|
|
public bool RoleWrite { get; set; }
|
|
}
|
|
|
|
protected class ClientListItem : ListItem
|
|
{
|
|
public List<ProjectListItem> Projects { get; set; }
|
|
}
|
|
|
|
protected class CompanyListItem : ListItem
|
|
{
|
|
public List<ClientListItem> Clients { get; set; }
|
|
}
|
|
|
|
[HttpPost]
|
|
public JsonResult GetProjectAccessTree(Guid? userId)
|
|
{
|
|
var result = new List<CompanyListItem>();
|
|
var user = userId.HasValue ? DbContext.AspNetUsers.FirstOrDefault(x => x.Id == userId.ToString()) : null;
|
|
var companies = DbContext.Companies.Select(x => new { x.Id, x.Name, Clients = x.Company2Client }).ToList();
|
|
var mainProjects = DbContext.Projects.Where(t => t.HasChildren)
|
|
.Select(t => new { t.Id, t.Name })
|
|
.ToDictionary(key => key.Id, elem => elem.Name);
|
|
var paCache = new ProjectAccessCache();
|
|
foreach (var company in companies)
|
|
{
|
|
var clientsList = new List<ClientListItem>();
|
|
foreach (var client in company.Clients.Select(x => x.Client).Distinct())
|
|
{
|
|
if (result.Any(x => x.Clients.Any(c => c.Id == client.Id)))
|
|
continue;
|
|
|
|
var projList = new List<ProjectListItem>();
|
|
foreach (var project in client.Projects.OrderBy(p => p.ParentProjectId).ThenBy(p => p.Name))
|
|
{
|
|
if (project.HasChildren) // do not display main project, but only his parts
|
|
continue;
|
|
ProjectListItem newItem = new ProjectListItem {Id = project.Id};
|
|
//if (project.Name == "Workflow and Queue Updates")
|
|
// new object();
|
|
newItem.Name = !project.ParentProjectId.HasValue || !mainProjects.ContainsKey(project.ParentProjectId.Value)
|
|
? project.Name
|
|
: string.Format("{1}: {0}", mainProjects[project.ParentProjectId.Value], project.Name);
|
|
|
|
bool explicitPermissionFound = false;
|
|
if (user != null)
|
|
{
|
|
var perm = paCache.Value.FirstOrDefault(x => x.PrincipalId == userId && x.ProjectId == project.Id);
|
|
if (perm != null)
|
|
{
|
|
newItem.Read = perm.Read > 0;
|
|
newItem.Write = perm.Write > 0;
|
|
explicitPermissionFound = true;
|
|
}
|
|
var rolePerm = new List<ProjectAccess>();
|
|
foreach (var role in user.AspNetRoles)
|
|
rolePerm.AddRange(project.ProjectAccesses.Where(x => x.PrincipalId == new Guid(role.Id)));
|
|
|
|
newItem.RoleRead = rolePerm.Any(x => x.Read == (int) Permission.Allow);
|
|
newItem.RoleWrite = rolePerm.Any(x => x.Write == (int) Permission.Allow);
|
|
}
|
|
|
|
if (!explicitPermissionFound)
|
|
{
|
|
newItem.Read = newItem.RoleRead;
|
|
newItem.Write = newItem.RoleWrite;
|
|
}
|
|
|
|
newItem.ReadInherited = !explicitPermissionFound;
|
|
newItem.WriteInherited = !explicitPermissionFound;
|
|
|
|
projList.Add(newItem);
|
|
}
|
|
|
|
clientsList.Add(new ClientListItem
|
|
{
|
|
Id = client.Id,
|
|
Name = client.Name,
|
|
Projects = projList
|
|
});
|
|
}
|
|
|
|
result.Add(new CompanyListItem
|
|
{
|
|
Id = company.Id,
|
|
Name = company.Name,
|
|
Clients = clientsList
|
|
});
|
|
}
|
|
|
|
return Json(result);
|
|
}
|
|
//env-648 start
|
|
#region CustomValidation
|
|
[HttpPost]
|
|
public JsonResult IsUnique(string userName, Guid id)
|
|
{
|
|
var result = userName != null && CheckDbForUniqueness(userName, id);
|
|
|
|
return Json(result);
|
|
}
|
|
private bool CheckDbForUniqueness(string userName, Guid id)
|
|
{
|
|
var query = DbContext.AspNetUsers.Select(c => new
|
|
{
|
|
c.UserName,
|
|
c.Id
|
|
});
|
|
query = Guid.Empty == id ?
|
|
query.Where(c => c.UserName.ToLower() == userName.ToLower()) :
|
|
query.Where(c => c.UserName.ToLower() == userName.ToLower() && c.Id != id.ToString());
|
|
|
|
return !query.Any();
|
|
}
|
|
#endregion
|
|
//env-648 end
|
|
|
|
private List<Guid> FilterCompanyList(EnVisageEntities context, List<Guid> srcCompanies, List<Guid> excludeCompanies)
|
|
{
|
|
if ((srcCompanies == null) || (srcCompanies.Count < 1))
|
|
return srcCompanies;
|
|
|
|
var result = new List<Guid>(srcCompanies);
|
|
|
|
// Get all available companies and convert to simple tree
|
|
CompanyManager mngr = new CompanyManager(context);
|
|
var allCompanies = mngr.GetCompanies();
|
|
var allCompaniesTree = new Dictionary<Guid, List<Guid>>();
|
|
|
|
foreach (var prntCompany in allCompanies.Keys)
|
|
{
|
|
var childCompanies = allCompanies[prntCompany];
|
|
|
|
if (childCompanies != null && childCompanies.Count > 0)
|
|
{
|
|
allCompaniesTree.Add(prntCompany.Key, childCompanies.Select(x => x.Id).ToList());
|
|
}
|
|
}
|
|
|
|
foreach (var prntCompany in allCompaniesTree.Keys)
|
|
{
|
|
// If parent company selected, remove all child companies from the result list
|
|
if (result.Contains(prntCompany))
|
|
result.RemoveAll(x => allCompaniesTree[prntCompany].Contains(x));
|
|
}
|
|
|
|
if ((excludeCompanies != null) && (excludeCompanies.Count > 0))
|
|
// Apply additional exclude list
|
|
result = result.Except(excludeCompanies).ToList();
|
|
|
|
return result;
|
|
}
|
|
|
|
private bool SaveUserCompanies(Guid userId, List<Guid> companies, CollaborationRole role, EnVisageEntities context)
|
|
{
|
|
if (companies == null || companies.Count < 1)
|
|
return false;
|
|
|
|
foreach (var companyId in companies)
|
|
{
|
|
User2Company newRec = new User2Company
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
UserId = userId,
|
|
CompanyId = companyId,
|
|
RelationType = role
|
|
};
|
|
context.User2Company.Add(newRec);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
}
|