845 lines
37 KiB
C#
845 lines
37 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Data.Entity;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Web;
|
|
using System.Web.Mvc;
|
|
using System.Web.Script.Serialization;
|
|
using System.Xml.Serialization;
|
|
using EnVisage;
|
|
using EnVisage.Code.BLL;
|
|
using jQuery.DataTables.Mvc;
|
|
using System.Collections.ObjectModel;
|
|
using System.Data.Entity.Validation;
|
|
using Microsoft.AspNet.Identity;
|
|
using Microsoft.AspNet.Identity.EntityFramework;
|
|
using EnVisage.Models;
|
|
using EnVisage.App_Start;
|
|
using EnVisage.Code.HtmlHelpers;
|
|
using EnVisage.Code;
|
|
using System.Text;
|
|
using EnVisage.Code.Cache;
|
|
using EnVisage.Models.Cache;
|
|
using EntityState = System.Data.Entity.EntityState;
|
|
|
|
namespace EnVisage.Controllers
|
|
{
|
|
[Authorize]
|
|
public class UserController : BaseController
|
|
{
|
|
public class ListUsers
|
|
{
|
|
public string Id { get; set; }
|
|
public string Name { get; set; }
|
|
public string Email { get; set; }
|
|
public string Roles { get; set; }
|
|
}
|
|
|
|
|
|
// GET: /User/
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Read)]
|
|
public ActionResult Index()
|
|
{
|
|
if (!HtmlHelpers.CheckSecurityObjectPermission(null, 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 = from c in DbContext.AspNetUsers select new { Id = c.Id, Name = c.UserName, Email = c.Email, RolesArr = c.AspNetRoles.ToList() };
|
|
|
|
//filter
|
|
if (!string.IsNullOrWhiteSpace(searchString))
|
|
{
|
|
query = query.Where(c => c.Name.ToLower().Contains(searchString.ToLower()));
|
|
}
|
|
|
|
//sort
|
|
foreach (var sortedColumn in sortedColumns)
|
|
{
|
|
switch (sortedColumn.PropertyName)
|
|
{
|
|
case "Id":
|
|
if (sortedColumn.Direction == SortingDirection.Ascending)
|
|
query = query.OrderBy(c => c.Id);
|
|
else
|
|
query = query.OrderByDescending(c => c.Id);
|
|
break;
|
|
case "Email":
|
|
if (sortedColumn.Direction == SortingDirection.Ascending)
|
|
query = query.OrderBy(c => c.Email);
|
|
else
|
|
query = query.OrderByDescending(c => c.Email);
|
|
break;
|
|
default:
|
|
if (sortedColumn.Direction == SortingDirection.Ascending)
|
|
query = query.OrderBy(c => c.Name);
|
|
else
|
|
query = 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, Name = x.Name, Email = x.Email, Roles = String.Join(", ", x.RolesArr.Select(r => r.Name)) })
|
|
.ToList();
|
|
searchRecordCount = query.Count();
|
|
return list;
|
|
}
|
|
|
|
|
|
// GET: /User/Create
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult Create()
|
|
{
|
|
var user = new AspNetUser();
|
|
return View(user);
|
|
}
|
|
|
|
// POST: /User/Create
|
|
// 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]
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult Create([Bind(Include = "UserName,Email")] AspNetUser user, string[] roleitems)
|
|
{
|
|
if (ModelState.IsValid)
|
|
{
|
|
ApplicationDbContext cnt = new ApplicationDbContext();
|
|
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
var password = System.Configuration.ConfigurationManager.AppSettings["DefaultPassword"];
|
|
userManager.Create(new ApplicationUser()
|
|
{
|
|
UserName = user.UserName,
|
|
Email = user.Email,
|
|
Phone = string.Empty,
|
|
Type = (int)UserType.Pending,
|
|
PagePreferences = user.PagePreferences,
|
|
PreferredResourceAllocation = user.PreferredResourceAllocation
|
|
}, password);
|
|
cnt.SaveChanges();
|
|
|
|
try
|
|
{
|
|
var userId = userManager.FindByName(user.UserName).Id;
|
|
|
|
if (roleitems != null)
|
|
{
|
|
EnVisageEntities context = new EnVisageEntities();
|
|
|
|
foreach (var roleitem in roleitems)
|
|
{
|
|
var role = (from pr in context.AspNetRoles
|
|
where pr.Id == roleitem
|
|
select pr).FirstOrDefault();
|
|
if (!userManager.IsInRole(userId, role.Name))
|
|
userManager.AddToRole(userId, role.Name);
|
|
}
|
|
}
|
|
|
|
new UsersCache().Invalidate();
|
|
|
|
MailManager.SendInvitationMessage(user.Email, user.UserName, userId);
|
|
}
|
|
catch(Exception ex)
|
|
{
|
|
ModelState.AddModelError("", ex);
|
|
}
|
|
return RedirectToAction("Index");
|
|
}
|
|
|
|
return View(user);
|
|
}
|
|
|
|
// GET: /User/Edit/5
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult Edit(string id)
|
|
{
|
|
//if (id == null)
|
|
//{
|
|
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
|
|
//}
|
|
AspNetUser aspnetuser = null;
|
|
if (string.IsNullOrEmpty(id))
|
|
{
|
|
aspnetuser = new AspNetUser();
|
|
}
|
|
else
|
|
{
|
|
aspnetuser = DbContext.AspNetUsers.Find(id);
|
|
if (aspnetuser == null)
|
|
{
|
|
return HttpNotFound();
|
|
}
|
|
}
|
|
return View(aspnetuser);
|
|
}
|
|
|
|
// 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]
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Write)]
|
|
public ActionResult Edit([Bind(Include = "Id,UserName,Email,Phone,PreferredResourceAllocation,Discriminator")] AspNetUser aspnetuser, string[] projectlistread, string[] projectlistwrite, string[] areasread, string[] areaswrite,
|
|
string[] roleitems, string[] overriden)
|
|
{
|
|
if (ModelState.IsValid)
|
|
{
|
|
var isNewUser = string.IsNullOrEmpty(aspnetuser.Id);
|
|
if (!isNewUser && ContentLocker.IsLock("User", aspnetuser.Id, User.Identity.Name))
|
|
{
|
|
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
|
|
}
|
|
|
|
var areasReadInherited = new List<Areas>();
|
|
var areasWriteInherited = new List<Areas>();
|
|
var projectListReadInherited = new List<Guid>();
|
|
var projectListWriteInherited = new List<Guid>();
|
|
overriden.Where(x => "areasread".Equals(x.Split('|')[0])).ToList().ForEach(x => areasReadInherited.Add((Areas)Enum.Parse(typeof(Areas), x.Split('|')[1])));
|
|
overriden.Where(x => "areaswrite".Equals(x.Split('|')[0])).ToList().ForEach(x => areasWriteInherited.Add((Areas)Enum.Parse(typeof(Areas), x.Split('|')[1])));
|
|
overriden.Where(x => "projectlistread".Equals(x.Split('|')[0])).ToList().ForEach(x => projectListReadInherited.Add(Guid.Parse(x.Split('|')[1])));
|
|
overriden.Where(x => "projectlistwrite".Equals(x.Split('|')[0])).ToList().ForEach(x => projectListWriteInherited.Add(Guid.Parse(x.Split('|')[1])));
|
|
var roleIds = (roleitems ?? new string[0]).Select(t => new Guid(t)).ToArray();
|
|
|
|
if (projectlistread == null) projectlistread = new[] { "0" };
|
|
if (projectlistwrite == null) projectlistwrite = new[] { "0" };
|
|
|
|
var context = new EnVisageEntities();
|
|
|
|
#region Create new user
|
|
if (isNewUser)
|
|
{
|
|
var cnt = new ApplicationDbContext();
|
|
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
var password = System.Configuration.ConfigurationManager.AppSettings["DefaultPassword"];
|
|
userManager.Create(new ApplicationUser()
|
|
{
|
|
UserName = aspnetuser.UserName,
|
|
Email = aspnetuser.Email,
|
|
Phone = aspnetuser.Phone, // string.Empty,
|
|
Type = (int)UserType.Pending,
|
|
PreferredResourceAllocation = aspnetuser.PreferredResourceAllocation,
|
|
PagePreferences = string.Empty
|
|
}, password);
|
|
|
|
cnt.SaveChanges();
|
|
|
|
try
|
|
{
|
|
var userId = userManager.FindByName(aspnetuser.UserName).Id;
|
|
|
|
aspnetuser.Id = userId;
|
|
|
|
if (roleitems != null)
|
|
{
|
|
foreach (var roleitem in roleitems)
|
|
{
|
|
var role = (from pr in context.AspNetRoles
|
|
where pr.Id == roleitem
|
|
select pr).FirstOrDefault();
|
|
if (!userManager.IsInRole(userId, role.Name))
|
|
userManager.AddToRole(userId, role.Name);
|
|
}
|
|
}
|
|
|
|
new UsersCache().Invalidate();
|
|
|
|
MailManager.SendInvitationMessage(aspnetuser.Email, aspnetuser.UserName, userId);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
ModelState.AddModelError("", ex);
|
|
}
|
|
|
|
}
|
|
#endregion
|
|
|
|
#region Save Projects
|
|
|
|
//EnVisageEntities context = new EnVisageEntities();
|
|
var projectAccessCache = new ProjectAccessCache();
|
|
var projects = (from pr in context.Projects
|
|
orderby pr.Name
|
|
select pr).ToList();
|
|
if (projects.Count > 0)
|
|
{
|
|
var projectIds = projects.Select(t => t.Id);
|
|
var userProjectAccesses = (from pr in context.ProjectAccesses
|
|
where
|
|
pr.PrincipalId == new Guid(aspnetuser.Id) &&
|
|
projectIds.Contains(pr.ProjectId)
|
|
select pr).ToList();
|
|
var rolePermissions = (from pr in context.ProjectAccesses
|
|
where roleIds.Contains(pr.PrincipalId)
|
|
select pr).ToArray();
|
|
Dictionary<Guid, ProjectAccess> addedParentPermissions = new Dictionary<Guid, ProjectAccess>();
|
|
foreach (var project in projects)
|
|
{
|
|
var userProjectAccess = userProjectAccesses.FirstOrDefault(t=>t.ProjectId == project.Id);
|
|
var roleProjectAcesses = rolePermissions.Where(t => t.ProjectId == project.Id).ToArray();
|
|
var isInheritedRead = projectListReadInherited.Contains(project.Id);
|
|
var isInheritedWrite = projectListWriteInherited.Contains(project.Id);
|
|
|
|
// build new values
|
|
var newRead = isInheritedRead ? Permission.Inherited
|
|
: projectlistread.Contains(project.Id.ToString())
|
|
? Permission.Allow
|
|
: Permission.Deny;
|
|
var newWrite = isInheritedWrite ? Permission.Inherited
|
|
: 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;
|
|
|
|
if (userProjectAccess == null)
|
|
{
|
|
if ((!isInheritedRead || !isInheritedWrite) && (readIsChanged || writeIsChanged))
|
|
{
|
|
var newpa = new ProjectAccess
|
|
{
|
|
PrincipalId = new Guid(aspnetuser.Id),
|
|
ProjectId = project.Id,
|
|
Read = (int)newRead,
|
|
Write = (int)newWrite
|
|
};
|
|
context.ProjectAccesses.Add(newpa);
|
|
if (project.ParentProjectId.HasValue)
|
|
{
|
|
if (!userProjectAccesses.Any(t => t.ProjectId == project.ParentProjectId.Value) && !addedParentPermissions.ContainsKey(project.ParentProjectId.Value))
|
|
{
|
|
var parentPA = new ProjectAccess
|
|
{
|
|
PrincipalId = new Guid(aspnetuser.Id),
|
|
ProjectId = project.ParentProjectId.Value,
|
|
Read = (int) newRead,
|
|
Write = (int) newWrite
|
|
};
|
|
context.ProjectAccesses.Add(parentPA);
|
|
addedParentPermissions.Add(project.ParentProjectId.Value, parentPA);
|
|
}
|
|
else
|
|
{
|
|
var parentPA = userProjectAccesses.FirstOrDefault(t => t.ProjectId == project.ParentProjectId.Value);
|
|
if (parentPA != null)
|
|
{
|
|
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 (!userProjectAccesses.Any(t => t.ProjectId == project.ParentProjectId.Value) && !addedParentPermissions.ContainsKey(project.ParentProjectId.Value))
|
|
{
|
|
var parentPA = new ProjectAccess
|
|
{
|
|
PrincipalId = new Guid(aspnetuser.Id),
|
|
ProjectId = project.ParentProjectId.Value,
|
|
Read = 1,
|
|
Write = 1
|
|
};
|
|
context.ProjectAccesses.Add(parentPA);
|
|
addedParentPermissions.Add(project.ParentProjectId.Value, parentPA);
|
|
}
|
|
else
|
|
{
|
|
var parentPA = userProjectAccesses.FirstOrDefault(t => t.ProjectId == project.ParentProjectId.Value);
|
|
if (parentPA != null)
|
|
{
|
|
parentPA.Read = 1;
|
|
parentPA.Write = 1;
|
|
context.Entry(parentPA).State = EntityState.Modified;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
context.ProjectAccesses.Remove(userProjectAccess);
|
|
if (project.ParentProjectId.HasValue)
|
|
{
|
|
var projectParts =
|
|
projects.Where(t => t.ParentProjectId == project.ParentProjectId.Value).Select(t=>t.Id).ToArray();
|
|
var otherPartsAccess = userProjectAccesses.Where(t => projectParts.Contains(t.ProjectId) && t.ProjectId != project.ParentProjectId.Value);
|
|
if (!otherPartsAccess.Any())
|
|
{
|
|
var parentPA = userProjectAccesses.FirstOrDefault(t => t.ProjectId == project.ParentProjectId.Value);
|
|
if (parentPA != null)
|
|
context.ProjectAccesses.Remove(userProjectAccess);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
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 == new Guid(aspnetuser.Id) && areaStrings.Contains(pr.SecurityObject)
|
|
select pr).ToArray();
|
|
var rolePermissions = (from pr in context.Securities
|
|
where roleIds.Contains(pr.PrincipalId)
|
|
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 newRead = isInheritedRead ? Permission.Inherited
|
|
: (areasread != null && areasread.Contains(area.ToString())
|
|
? Permission.Allow
|
|
: Permission.Deny);
|
|
var newWrite = isInheritedWrite ? Permission.Inherited
|
|
: (areaswrite != null && 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;
|
|
// 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 = new Guid(aspnetuser.Id),
|
|
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))
|
|
{
|
|
var role = (from pr in context.AspNetRoles
|
|
where pr.Name == userrole
|
|
select pr).FirstOrDefault();
|
|
if (!roleitems.Contains(role.Id))
|
|
userManager.RemoveFromRole(aspnetuser.Id, userrole);
|
|
}
|
|
if (roleitems != null)
|
|
{
|
|
foreach (var roleitem in roleitems)
|
|
{
|
|
var role = (from pr in context.AspNetRoles
|
|
where pr.Id == roleitem
|
|
select pr).FirstOrDefault();
|
|
if (!userManager.IsInRole(aspnetuser.Id, role.Name))
|
|
userManager.AddToRole(aspnetuser.Id, role.Name);
|
|
}
|
|
}
|
|
ApplicationUser u = userManager.FindById(aspnetuser.Id);
|
|
u.Email = aspnetuser.Email;
|
|
u.Phone = aspnetuser.Phone;
|
|
u.PreferredResourceAllocation = aspnetuser.PreferredResourceAllocation;
|
|
userManager.Update(u);
|
|
|
|
try
|
|
{
|
|
cnt.SaveChanges();
|
|
|
|
new UsersCache().Invalidate();
|
|
|
|
ContentLocker.RemoveLock("User", aspnetuser.Id.ToString(), User.Identity.Name);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
var dbEntityValidationException = ex as DbEntityValidationException;
|
|
if (dbEntityValidationException != null)
|
|
{
|
|
foreach (var validationErrors in dbEntityValidationException.EntityValidationErrors)
|
|
{
|
|
foreach (var validationError in validationErrors.ValidationErrors)
|
|
{
|
|
var mess = validationError.PropertyName + validationError.ErrorMessage;
|
|
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
#endregion
|
|
}
|
|
|
|
return RedirectToAction("Index");
|
|
}
|
|
|
|
[HttpPost]
|
|
//[ValidateAntiForgeryToken]
|
|
[AreaSecurityAttribute(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.Count() == 0)
|
|
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.Count() == 0)
|
|
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.ToString(), User.Identity.Name))
|
|
{
|
|
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
|
|
}
|
|
|
|
foreach (var source in DbContext.PasswordResetRequests.Where(t=>t.UserId == id))
|
|
{
|
|
DbContext.PasswordResetRequests.Remove(source);
|
|
}
|
|
AspNetUser aspnetuser = DbContext.AspNetUsers.Find(id);
|
|
DbContext.AspNetUsers.Remove(aspnetuser);
|
|
DbContext.SaveChanges();
|
|
|
|
new UsersCache().Invalidate();
|
|
|
|
ContentLocker.RemoveLock("User", id.ToString(), User.Identity.Name);
|
|
return RedirectToAction("Index");
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult GetPagePreferences(string key)
|
|
{
|
|
var userId = User.Identity.GetUserId();
|
|
try
|
|
{
|
|
var user = new UsersCache().Value.FirstOrDefault(x => x.Id == new Guid(userId));
|
|
if (user != null)
|
|
{
|
|
var pagePreferences = new
|
|
{
|
|
Status = "OK",
|
|
Data = PagePreferencesList.GetPage(user.PagePreferences, key)
|
|
};
|
|
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();
|
|
}
|
|
ContentLocker.RemoveLock("User", userId, User.Identity.Name);
|
|
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
|
|
}
|
|
[HttpPost]
|
|
public ActionResult SavePagePreferences(string pageKey, string data)
|
|
{
|
|
var userId = User.Identity.GetUserId();
|
|
if (ContentLocker.IsLock("User", userId, User.Identity.Name))
|
|
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
|
|
ContentLocker.AddLock("User", userId, User.Identity.Name);
|
|
try
|
|
{
|
|
var user = DbContext.AspNetUsers.FirstOrDefault(t => t.Id == userId);
|
|
if (user != null)
|
|
{
|
|
user.PagePreferences = PagePreferencesList.SetPagePreferences(user.PagePreferences, pageKey, data);
|
|
DbContext.Entry(user).State = EntityState.Modified;
|
|
DbContext.SaveChanges();
|
|
ContentLocker.RemoveLock("User", userId, User.Identity.Name);
|
|
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();
|
|
}
|
|
ContentLocker.RemoveLock("User", userId, User.Identity.Name);
|
|
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 = DbContext.AspNetUsers.FirstOrDefault(x => x.Id == userId.ToString());
|
|
var companies = DbContext.Companies.Select(x => new { Id = x.Id, Name = 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();
|
|
newItem.Id = project.Id;
|
|
newItem.Name = !project.ParentProjectId.HasValue || !mainProjects.ContainsKey(project.ParentProjectId.Value)
|
|
? project.Name
|
|
: string.Format("{0}: {1}", 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);
|
|
}
|
|
}
|
|
}
|