1134 lines
52 KiB
C#
1134 lines
52 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data.Entity;
|
|
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 System.Data.Entity.Validation;
|
|
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;
|
|
|
|
namespace EnVisage.Controllers
|
|
{
|
|
[Authorize]
|
|
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
|
|
public class UserController : BaseController
|
|
{
|
|
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 UserController()
|
|
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
|
|
{
|
|
}
|
|
|
|
public UserController(UserManager<ApplicationUser> userManager)
|
|
{
|
|
ApplicationDbContext cnt = new ApplicationDbContext();
|
|
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
var userValidator = um.UserValidator as UserValidator<ApplicationUser>;
|
|
userValidator.AllowOnlyAlphanumericUserNames = true;
|
|
}
|
|
|
|
// GET: /User/
|
|
[AreaSecurityAttribute(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 = from c in DbContext.AspNetUsers select new { Id = c.Id, UserName = c.UserName, LastName = c.LastName, Name = c.FirstName + " " + c.LastName, Email = c.Email, RolesArr = c.AspNetRoles.ToList() };
|
|
|
|
//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":
|
|
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;
|
|
case "UserName":
|
|
if (sortedColumn.Direction == SortingDirection.Ascending)
|
|
query = query.OrderBy(c => c.UserName);
|
|
else
|
|
query = query.OrderByDescending(c => c.UserName);
|
|
break;
|
|
case "LastName":
|
|
if (sortedColumn.Direction == SortingDirection.Ascending)
|
|
query = query.OrderBy(c => c.LastName);
|
|
else
|
|
query = query.OrderByDescending(c => c.LastName);
|
|
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,UserName=x.UserName, 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)]
|
|
//env-648
|
|
//public ActionResult Create([Bind(Include = "UserName,Email")] AspNetUser user, string[] roleitems)
|
|
public ActionResult Create([Bind(Include = "UserName,Email")] UserModel user, string[] roleitems)
|
|
{
|
|
if (ModelState.IsValid)
|
|
{
|
|
ApplicationDbContext cnt = new ApplicationDbContext();
|
|
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
userManager.Create(new ApplicationUser()
|
|
{
|
|
UserName = user.UserName,
|
|
Email = user.Email,
|
|
Phone = string.Empty,
|
|
Type = (int)UserType.Pending,
|
|
PreferredResourceAllocation = user.PreferredResourceAllocation
|
|
}, AppSettingsManager.DefaultPassword);
|
|
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);
|
|
//}
|
|
|
|
UserModel aspnetuser = new UserModel();
|
|
if (!string.IsNullOrEmpty(id))
|
|
{
|
|
aspnetuser = new UserModel(DbContext.AspNetUsers.Find(id));
|
|
if (aspnetuser.Id == Guid.Empty)
|
|
{
|
|
return HttpNotFound();
|
|
}
|
|
}
|
|
|
|
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]
|
|
[AreaSecurityAttribute(area = Areas.Users, level = AccessLevel.Write)]
|
|
//env-648
|
|
//public ActionResult Edit([Bind(Include = "Id,UserName,FirstName,LastName,Email,Phone,PreferredResourceAllocation,Discriminator")] AspNetUser aspnetuser, string[] projectlistread, string[] projectlistwrite, string[] areasread, string[] areaswrite,
|
|
public ActionResult Edit(EditPermissionModel edituser)
|
|
{
|
|
|
|
ProjectTreeModel projecttree = edituser.projecttree;
|
|
UserModel aspnetuser = edituser.aspnetuser;
|
|
|
|
if (ModelState.IsValid)
|
|
{
|
|
// var isNewUser = string.IsNullOrEmpty(aspnetuser.Id);
|
|
var isNewUser = (aspnetuser.Id == Guid.Empty);
|
|
if (!isNewUser && ContentLocker.IsLock("User", aspnetuser.Id.ToString(), 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>();
|
|
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 = Guid.Empty;
|
|
if (isNewUser)
|
|
{
|
|
short userType=(int)UserType.Pending;
|
|
var cnt = new ApplicationDbContext();
|
|
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(cnt));
|
|
try
|
|
{
|
|
|
|
userManager.Create(new ApplicationUser()
|
|
{
|
|
UserName = aspnetuser.UserName,
|
|
FirstName = aspnetuser.FirstName,
|
|
LastName = aspnetuser.LastName,
|
|
Email = aspnetuser.Email,
|
|
Phone = aspnetuser.Phone, // string.Empty,
|
|
Type = userType,
|
|
PreferredResourceAllocation = aspnetuser.PreferredResourceAllocation
|
|
}, AppSettingsManager.DefaultPassword);
|
|
|
|
cnt.SaveChanges();
|
|
}
|
|
catch (Exception createNewUseEx)
|
|
{
|
|
ModelState.AddModelError("", "Error creating user. Please review your entries");
|
|
LogException(createNewUseEx);
|
|
SetErrorScript();
|
|
HttpContext.Response.StatusCode = 500;
|
|
HttpContext.Response.Clear();
|
|
return View(aspnetuser);
|
|
}
|
|
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 = (from pr in context.AspNetRoles
|
|
where pr.Id == roleitem
|
|
select pr).FirstOrDefault();
|
|
if (!userManager.IsInRole(userId.ToString(), role.Name))
|
|
userManager.AddToRole(userId.ToString(), role.Name);
|
|
}
|
|
}
|
|
|
|
new UsersCache().Invalidate();
|
|
|
|
MailManager.SendInvitationMessage(aspnetuser.Email, aspnetuser.UserName, userId.ToString());
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
ModelState.AddModelError("", "Error creating user. Please review your entries");
|
|
LogException(ex);
|
|
SetErrorScript();
|
|
HttpContext.Response.StatusCode = 500;
|
|
HttpContext.Response.Clear();
|
|
return View(aspnetuser);
|
|
}
|
|
|
|
}
|
|
else
|
|
{
|
|
//userId = new Guid(aspnetuser.Id);
|
|
userId = aspnetuser.Id;
|
|
|
|
}
|
|
#endregion
|
|
|
|
#region Save Projects
|
|
|
|
//EnVisageEntities context = new EnVisageEntities();
|
|
var projectAccessCache = new ProjectAccessCache();
|
|
var projects = (from pr in context.Projects
|
|
where !pr.HasChildren
|
|
orderby pr.Name
|
|
select pr).ToList();
|
|
if (projects.Count > 0)
|
|
{
|
|
var projectIds = projects.Select(t => t.Id);
|
|
var permissions = (from pr in context.ProjectAccesses
|
|
where pr.PrincipalId == userId
|
|
select pr)
|
|
.ToDictionary(userProjectAccess => new Tuple<Guid, Guid>(userProjectAccess.PrincipalId, userProjectAccess.ProjectId));
|
|
var rolePermissions = (from pr in context.ProjectAccesses
|
|
where roleIds.Contains(pr.PrincipalId.ToString())
|
|
select pr).ToArray();
|
|
foreach (var roleAccess in rolePermissions)
|
|
{
|
|
permissions.Add(new Tuple<Guid, Guid>(roleAccess.PrincipalId, roleAccess.ProjectId), roleAccess);
|
|
}
|
|
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 ||
|
|
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 (isInheritedRead)
|
|
{
|
|
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.FirstName = aspnetuser.FirstName;
|
|
u.LastName = aspnetuser.LastName;
|
|
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;
|
|
ModelState.AddModelError("", mess);
|
|
}
|
|
}
|
|
|
|
}
|
|
else
|
|
{
|
|
ModelState.AddModelError("", ex.Message);
|
|
}
|
|
LogException(ex);
|
|
SetErrorScript();
|
|
HttpContext.Response.StatusCode = 500;
|
|
HttpContext.Response.Clear();
|
|
return View(aspnetuser);
|
|
}
|
|
|
|
}
|
|
#endregion
|
|
}
|
|
|
|
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index");
|
|
return Json(new { Url = redirectUrl });
|
|
|
|
// 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);
|
|
}
|
|
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.ToString(), User.Identity.Name);
|
|
return RedirectToAction("Index");
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult SavePreferences(string url, string section, string data)
|
|
{
|
|
string userIdAsText = User.Identity.GetID();
|
|
string userName = User.Identity.Name;
|
|
|
|
try
|
|
{
|
|
// Validate user
|
|
var user = DbContext.AspNetUsers.FirstOrDefault(t => t.Id == userIdAsText);
|
|
Guid userId = new Guid(userIdAsText);
|
|
|
|
if (user == null)
|
|
throw new Exception(String.Format("Unknown user id ({0})", userIdAsText));
|
|
|
|
UserPreference pagePrefs = DbContext.UserPreferences.FirstOrDefault(x => userId.Equals(x.UserId) &&
|
|
x.Url.Equals(url, StringComparison.InvariantCultureIgnoreCase) &&
|
|
x.Section.Equals(section, StringComparison.InvariantCultureIgnoreCase));
|
|
|
|
if (pagePrefs == null)
|
|
{
|
|
pagePrefs = new UserPreference()
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
UserId = userId,
|
|
Url = url,
|
|
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]
|
|
public ActionResult GetPreferences(string url, string section)
|
|
{
|
|
string userIdAsText = User.Identity.GetID();
|
|
|
|
try
|
|
{
|
|
// Validate user
|
|
var user = DbContext.AspNetUsers.FirstOrDefault(t => t.Id == userIdAsText);
|
|
Guid userId = new Guid(userIdAsText);
|
|
|
|
if (user == null)
|
|
throw new Exception(String.Format("Unknown user id ({0})", userIdAsText));
|
|
|
|
string prefData = String.Empty;
|
|
|
|
var prefRecords = DbContext.UserPreferences.Where(x => x.UserId.Equals(userId) &&
|
|
x.Url.Equals(url, StringComparison.InvariantCultureIgnoreCase) &&
|
|
x.Section.Equals(section, StringComparison.InvariantCultureIgnoreCase));
|
|
|
|
if (prefRecords.Count() > 0)
|
|
prefData = prefRecords.First().Data;
|
|
|
|
var pagePreferences = new
|
|
{
|
|
Status = "OK",
|
|
Data = prefData
|
|
};
|
|
|
|
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 { 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;
|
|
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)
|
|
{
|
|
|
|
bool result = false;
|
|
if (UserName == null)
|
|
{
|
|
result = false;
|
|
}
|
|
else
|
|
{
|
|
result = CheckDbForUniqueness(UserName,Id);
|
|
}
|
|
|
|
return Json(result);
|
|
|
|
}
|
|
private bool CheckDbForUniqueness(string UserName,Guid Id)
|
|
{
|
|
var query = from c in DbContext.AspNetUsers
|
|
select new
|
|
{
|
|
UserName = c.UserName,
|
|
Id = c.Id
|
|
};
|
|
if (Guid.Empty == Id)
|
|
query = query.Where(c => c.UserName.ToLower() == (UserName.ToLower()));
|
|
else
|
|
query = query.Where(c => (c.UserName.ToLower() == UserName.ToLower() && c.Id != Id.ToString()));
|
|
|
|
return !(query.Count() > 0);
|
|
}
|
|
#endregion
|
|
//env-648 end
|
|
}
|
|
}
|