public static async Task<OperationResult> AddUserToRole(string adminId, string uid, int rid)
 {
     OperationResult OpResult = new OperationResult();
     var maxp = await MemberAdminContext.GetMaxPriority(adminId);
     RoleServiceProxy rsvc = new RoleServiceProxy();
     UserServiceProxy usvc = new UserServiceProxy();
     var cntx = Cntx;
     var u = await usvc.LoadEntityByKeyAsync(cntx, uid);
     if (u == null)
     {
         OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
         return OpResult;
     }
     var uroles = await usvc.MaterializeAllRolesAsync(cntx, u);
     if (DBAutoCleanupRoles)
     {
         // prevent polution
         List<Role> higherroles = new List<Role>();
         foreach (var ur in uroles)
         {
             var pr = ur;
             if (pr.ID == rid)
                 higherroles.Add(ur);
             while (pr.ParentID != null)
             {
                 pr.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, pr);
                 pr = pr.UpperRef;
                 if (pr.ID == rid)
                 {
                     higherroles.Add(ur);
                     break;
                 }
             }
         }
         if (higherroles.Count > 0)
         {
             string rolesstr = "";
             foreach (var hr in higherroles)
                 rolesstr += (rolesstr == "" ? "" : ", ") + hr.DistinctString;
             string errorfmt = ResourceUtils.GetString("43558b5deaec392b9461d28d4e753687", "Operation denied: the user already has this or more specific roles: '{0}'! Try to remove them before adding present one.");
             OpResult.Result = new { ok = false, msg = string.Format(errorfmt, rolesstr) };
             return OpResult;
         }
     }
     var r = await rsvc.LoadEntityByKeyAsync(cntx, rid);
     if (r == null)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("db2a3d7bc44d36a9ebeaa0d562c4cd21", "The role is not found.") };
         return OpResult;
     }
     else if (r.RolePriority > maxp.Major)
     {
         OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("67729f0f407d1ea57f28b43235b3e5f6", "Adding more priviledged role is not authorized.") };
         return OpResult;
     }
     List<SimpleMessage> notices = new List<SimpleMessage>();
     var uir = new UsersInRole();
     List<Role> removed = new List<Role>();
     if (DBAutoCleanupRoles)
     {
         // clean up: find more general roles to remove.
         var p = r;
         while (p.ParentID != null)
         {
             p.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, p);
             p = p.UpperRef;
             foreach (var ur in uroles)
             {
                 if (ur.ID == p.ID)
                 {
                     if (!(from d in removed where d.ID == p.ID select d).Any())
                         removed.Add(p);
                 }
             }
         }
     }
     uir.IsPersisted = false;
     uir.UserID = u.ID;
     uir.RoleID = rid;
     uir.SubPriority = 0;
     uir.AssignDate = DateTime.UtcNow;
     uir.LastModified = uir.AssignDate;
     uir.AdminID = adminId;
     UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
     await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });
     UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
     var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);
     notices.Add(new SimpleMessage
                 {
                     TypeId = 1,
                     Title = string.Format(ResourceUtils.GetString("38015f8af3e032dfd803758dd2bde917", "New role: [{0}] is added.", memb.AcceptLanguages), r.DistinctString),
                     Data = "{ id=\"" + r.ID + "\", type=\"role\", name=\"" + r.DistinctString + "\" }"
                 });
     var _r = new { id = rid, uid = u.ID, name = r.RoleName, path = r.DistinctString, level = uir.SubPriority, op = true };
     List<dynamic> _removed = new List<dynamic>();
     if (removed.Count > 0)
     {
         List<UsersInRole> l = new List<UsersInRole>();
         foreach (var rmv in removed)
         {
             var x = uirsvc.LoadEntityByKey(Cntx, rmv.ID, u.ID);
             l.Add(x);
             _removed.Add(new { id = rmv.ID, name = rmv.RoleName, path = rmv.DistinctString, op = maxp.Major >= rmv.RolePriority });
         }
         await uirsvc.DeleteEntitiesAsync(Cntx, new UsersInRoleSet(), l.ToArray());
         foreach (var _rrmv in removed)
             notices.Add(new SimpleMessage
             {
                 TypeId = 1,
                 Title = string.Format(ResourceUtils.GetString("9708d527fbbf0d9752fc2c741615fb58", "Your role: [{0}] is removed.", memb.AcceptLanguages), _rrmv.DistinctString),
                 Data = "{ id=\"" + _rrmv.ID + "\", type=\"role\", name=\"" + _rrmv.DistinctString + "\" }"
             });
     }
     await AddUserRoleHistory(uir, UserRoleOperations.Added);
     OpResult.Result = new { ok = true, msg = "", added = _r, removed = _removed.ToArray() };
     OpResult.notices = notices.ToArray();
     return OpResult;
 }
Exemple #2
0
        public static async Task <OperationResult> AddUserToRole(string adminId, string uid, int rid)
        {
            OperationResult OpResult = new OperationResult();
            var             maxp     = await MemberAdminContext.GetMaxPriority(adminId);

            RoleServiceProxy rsvc = new RoleServiceProxy();
            UserServiceProxy usvc = new UserServiceProxy();
            var cntx = Cntx;
            var u    = await usvc.LoadEntityByKeyAsync(cntx, uid);

            if (u == null)
            {
                OpResult.Result = new { ok = false, msg = string.Format(ResourceUtils.GetString("b66098049404e4de1356242e8aa6444a", "User \"{0}\" is not found."), uid) };
                return(OpResult);
            }
            var uroles = await usvc.MaterializeAllRolesAsync(cntx, u);

            if (DBAutoCleanupRoles)
            {
                // prevent polution
                List <Role> higherroles = new List <Role>();
                foreach (var ur in uroles)
                {
                    var pr = ur;
                    if (pr.ID == rid)
                    {
                        higherroles.Add(ur);
                    }
                    while (pr.ParentID != null)
                    {
                        pr.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, pr);

                        pr = pr.UpperRef;
                        if (pr.ID == rid)
                        {
                            higherroles.Add(ur);
                            break;
                        }
                    }
                }
                if (higherroles.Count > 0)
                {
                    string rolesstr = "";
                    foreach (var hr in higherroles)
                    {
                        rolesstr += (rolesstr == "" ? "" : ", ") + hr.DistinctString;
                    }
                    string errorfmt = ResourceUtils.GetString("43558b5deaec392b9461d28d4e753687", "Operation denied: the user already has this or more specific roles: '{0}'! Try to remove them before adding present one.");
                    OpResult.Result = new { ok = false, msg = string.Format(errorfmt, rolesstr) };
                    return(OpResult);
                }
            }
            var r = await rsvc.LoadEntityByKeyAsync(cntx, rid);

            if (r == null)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("db2a3d7bc44d36a9ebeaa0d562c4cd21", "The role is not found.") };
                return(OpResult);
            }
            else if (r.RolePriority > maxp.Major)
            {
                OpResult.Result = new { ok = false, msg = ResourceUtils.GetString("67729f0f407d1ea57f28b43235b3e5f6", "Adding more priviledged role is not authorized.") };
                return(OpResult);
            }
            List <SimpleMessage> notices = new List <SimpleMessage>();
            var         uir     = new UsersInRole();
            List <Role> removed = new List <Role>();

            if (DBAutoCleanupRoles)
            {
                // clean up: find more general roles to remove.
                var p = r;
                while (p.ParentID != null)
                {
                    p.UpperRef = await rsvc.MaterializeUpperRefAsync(cntx, p);

                    p = p.UpperRef;
                    foreach (var ur in uroles)
                    {
                        if (ur.ID == p.ID)
                        {
                            if (!(from d in removed where d.ID == p.ID select d).Any())
                            {
                                removed.Add(p);
                            }
                        }
                    }
                }
            }
            uir.IsPersisted  = false;
            uir.UserID       = u.ID;
            uir.RoleID       = rid;
            uir.SubPriority  = 0;
            uir.AssignDate   = DateTime.UtcNow;
            uir.LastModified = uir.AssignDate;
            uir.AdminID      = adminId;
            UsersInRoleServiceProxy uirsvc = new UsersInRoleServiceProxy();
            await uirsvc.AddOrUpdateEntitiesAsync(cntx, new UsersInRoleSet(), new UsersInRole[] { uir });

            UserAppMemberServiceProxy mbsvc = new UserAppMemberServiceProxy();
            var memb = await mbsvc.LoadEntityByKeyAsync(cntx, AppId, uid);

            notices.Add(new SimpleMessage
            {
                TypeId = 1,
                Title  = string.Format(ResourceUtils.GetString("38015f8af3e032dfd803758dd2bde917", "New role: [{0}] is added.", memb.AcceptLanguages), r.DistinctString),
                Data   = "{ id=\"" + r.ID + "\", type=\"role\", name=\"" + r.DistinctString + "\" }"
            });
            var            _r       = new { id = rid, uid = u.ID, name = r.RoleName, path = r.DistinctString, level = uir.SubPriority, op = true };
            List <dynamic> _removed = new List <dynamic>();

            if (removed.Count > 0)
            {
                List <UsersInRole> l = new List <UsersInRole>();
                foreach (var rmv in removed)
                {
                    var x = uirsvc.LoadEntityByKey(Cntx, rmv.ID, u.ID);
                    l.Add(x);
                    _removed.Add(new { id = rmv.ID, name = rmv.RoleName, path = rmv.DistinctString, op = maxp.Major >= rmv.RolePriority });
                }
                await uirsvc.DeleteEntitiesAsync(Cntx, new UsersInRoleSet(), l.ToArray());

                foreach (var _rrmv in removed)
                {
                    notices.Add(new SimpleMessage
                    {
                        TypeId = 1,
                        Title  = string.Format(ResourceUtils.GetString("9708d527fbbf0d9752fc2c741615fb58", "Your role: [{0}] is removed.", memb.AcceptLanguages), _rrmv.DistinctString),
                        Data   = "{ id=\"" + _rrmv.ID + "\", type=\"role\", name=\"" + _rrmv.DistinctString + "\" }"
                    });
                }
            }
            await AddUserRoleHistory(uir, UserRoleOperations.Added);

            OpResult.Result  = new { ok = true, msg = "", added = _r, removed = _removed.ToArray() };
            OpResult.notices = notices.ToArray();
            return(OpResult);
        }