Beispiel #1
0
        public string GetMapStr(PermissionMap pt)
        {
            string str = "";
            var    ps  = plts.Where(b => b.PID == pt.ID).OrderBy(b => b.SortID);

            if (ps != null)
            {
                str = "<ul>";
                foreach (var item in ps)
                {
                    str += "<li><label><input type='checkbox' name='p" + item.ID + "' pid='p" + item.PID + "' />" + item.Name + "</label>";
                    var childStr = GetMapStr(item);
                    if (!string.IsNullOrEmpty(childStr))
                    {
                        str += "<ul>" + childStr + "</ul></li>";
                    }
                    else
                    {
                        str += "</li>";
                    }
                }
                str += "</ul>";
            }
            return(str);
        }
Beispiel #2
0
    protected void btnGrantAccess_Click(object sender, EventArgs e)
    {
        List <PermissionMap> permissionList = new List <PermissionMap>();

        foreach (GridViewRow item in grdVwPermission.Rows)
        {
            PermissionMap pm = new PermissionMap();
            pm.Permission = ((Label)item.FindControl("lblPermission")).Text;
            pm.Allow      = ((CheckBox)item.FindControl("chkGrantPermission")).Checked;
            pm.Deny       = ((CheckBox)item.FindControl("chkRevokePermission")).Checked;
            permissionList.Add(pm);
        }

        bool result = false;

        using (ResourceDataAccess dataAccess = new ResourceDataAccess(Utility.CreateContext()))
        {
            result = dataAccess.SetPermissionToResource(ResourceId, permissionList,
                                                        UserOrGroupId,
                                                        userToken);
        }

        if (PermissionGranted != null)
        {
            PermissionGranted(sender, new GrantEventArgs(result));
        }
    }
    static void Main(string[] args)
    {
        var permissionMap = new PermissionMap(new[] { "Read", "Write" });

        permissionMap.AddUser("Bill");
        permissionMap.AddUser("Jane");
        permissionMap["Bill", "Read"]  = Permission.Allow;
        permissionMap["Jane", "Write"] = Permission.Allow;
        foreach (DataColumn column in permissionMap.Columns)
        {
            Console.Write(column.ColumnName);
            Console.Write(",");
        }
        Console.WriteLine();
        foreach (DataRow row in permissionMap.Rows)
        {
            foreach (DataColumn column in permissionMap.Columns)
            {
                Console.Write(row[column]);
                Console.Write(",");
            }
            Console.WriteLine();
        }
        Console.ReadKey();
    }
Beispiel #4
0
 public FileSystemRoot(string path, Site site)
 {
     Path    = path;
     Readers = new PermissionMap(Permission.Read, new[] { "Administrators", "Editors", "Writers" }, new[] { "admin" });
     Writers = new PermissionMap(Permission.Write, new[] { "Administrators", "Editors", "Writers" }, new[] { "admin" });
     Site    = site;
 }
Beispiel #5
0
    protected void btnGrantAccess_Click(object sender, EventArgs e)
    {
        bool result = false;
        List <PermissionMap> permissionList = new List <PermissionMap>();

        foreach (GridViewRow item in grdGlobalPermission.Rows)
        {
            PermissionMap pm = new PermissionMap();
            pm.Permission = ((Label)item.FindControl("lblPermission")).Text;
            pm.Allow      = ((CheckBox)item.FindControl("chkGrantPermission")).Checked;
            pm.Deny       = ((CheckBox)item.FindControl("chkRevokePermission")).Checked;
            permissionList.Add(pm);
        }
        using (ResourceDataAccess dataAccess = new ResourceDataAccess(Utility.CreateContext()))
        {
            result = dataAccess.SetCreatePremissions(permissionList[0], Id.ToString(), userToken);
        }

        if (result)
        {
            Utility.ShowMessage(lblErrorGlobalPermission, Resources.Resources.PermissionGranted, false);
        }
        else
        {
            Utility.ShowMessage(lblErrorGlobalPermission, Resources.Resources.FailToGrantPermission, false);
        }
        lblErrorGlobalPermission.Visible = true;
    }
Beispiel #6
0
        protected override void Render(HtmlTextWriter writer)
        {
            if (RequiredPermission == Permission.None)
            {
                RequiredPermission = Page.GetType().GetCustomAttributes(typeof(IPermittable), true).OfType <IPermittable>()
                                     .Select(p => PermissionMap.GetMaximumPermission(p.RequiredPermission))
                                     .OrderByDescending(rp => rp)
                                     .FirstOrDefault();
            }

            var item = new SelectionUtility(this, Page.GetEngine()).SelectedItem;

            if (!Page.GetEngine().SecurityManager.IsAuthorized(Page.User, item, RequiredPermission))
            {
                var message = "User: "******"(" + GetUserRoles(Page.User.Identity.Name) + ")" +
                              "  Item:" + item.GetType().Name + "_" + item.ID + "_" + item.State + "_" + item.Title +
                              ",  RequiredPremission:" + RequiredPermission + ", AlteredPermissions:" +
                              item.AlteredPermissions + " , Write_Roles: (" + GetRolesForPermission(item, Permission.Write) + ")" +
                              " , Publish_Roles: (" + GetRolesForPermission(item, Permission.Publish) + ")" +
                              " , Admin_Roles: (" + GetRolesForPermission(item, Permission.Administer) + ")" +
                              GetAdditionalInfo(item, Page.User);
                Page.GetEngine().Resolve <IErrorNotifier>().Notify(new UnauthorizedAccessException(message));
                cv.IsValid = false;
                cv.RenderControl(writer);
            }
            else
            {
                base.Render(writer);
            }
        }
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     AccountMap.Map(modelBuilder.Entity <Account>());
     PermissionMap.Map(modelBuilder.Entity <Permission>());
     ObjectiveMap.Map(modelBuilder.Entity <Objective>());
     StatusMap.Map(modelBuilder.Entity <Status>());
 }
Beispiel #8
0
        public bool MapPermission(List <RolesPermissionViewModel> request, string roleId)
        {
            var oldPermissionMaps = _permissionMapRepository.GetAllActive().Where(x => x.RoleId == roleId).ToList();

            _permissionMapRepository.RemoveAll(oldPermissionMaps);
//            _permissionMapRepository.Commit();
            var newPermissionMaps = new List <PermissionMap>();

            foreach (var mapItem in request)
            {
                if (mapItem.HasPermission == true)
                {
                    PermissionMap newPermissionMap = new PermissionMap();
                    newPermissionMap.RoleId       = roleId;
                    newPermissionMap.PermissionId = mapItem.Id;

                    var user = GetUserFromToken();
                    newPermissionMap.Id             = Guid.NewGuid().ToString();
                    newPermissionMap.Created        = DateTime.Now;
                    newPermissionMap.Modified       = DateTime.Now;
                    newPermissionMap.CreatedBy      = user.Id;
                    newPermissionMap.ModifiedBy     = user.Id;
                    newPermissionMap.CreatedCompany = user.Company.Id;
                    newPermissionMap.Active         = true;
                    newPermissionMap.DeletedBy      = null;
                    newPermissionMap.DeletionTime   = null;

                    newPermissionMaps.Add(newPermissionMap);
                }
            }

            _permissionMapRepository.Add(newPermissionMaps);

            return(_permissionMapRepository.Commit());
        }
Beispiel #9
0
        public PermissionMap ToPermissionMap(Permission permission, string[] defaultRoles, string[] defaultUsers)
        {
            PermissionMap map = Dynamic ? new DynamicPermissionMap() : new PermissionMap();

            map.Permissions = permission;
            map.Roles       = ToArray(Roles, defaultRoles);
            map.Users       = ToArray(Users, defaultUsers);
            return(map);
        }
Beispiel #10
0
        public void CanMapFullPermission(Permission expectedPermission)
        {
            var map = new PermissionMap {
                Permissions = Permission.Full, Roles = new[] { "rolename" }
            };

            Assert.That(map.MapsTo(expectedPermission), Is.True);
            Assert.That(map.Authorizes(user, item, expectedPermission), Is.True);
        }
Beispiel #11
0
        public void CanMapReadPermission(Permission expectedPermission, bool expectedResult)
        {
            var map = new PermissionMap {
                Permissions = Permission.Read, Roles = new[] { "rolename" }
            };

            Assert.That(map.MapsTo(expectedPermission), Is.EqualTo(expectedResult));
            Assert.That(map.Authorizes(user, item, expectedPermission), Is.EqualTo(expectedResult));
        }
Beispiel #12
0
 private static void Apply(PermissionMap map, Directory dir)
 {
     if (map.IsAltered)
     {
         DynamicPermissionMap.SetRoles(dir, map.Permissions, map.Roles);
     }
     else
     {
         DynamicPermissionMap.SetAllRoles(dir, map.Permissions);
     }
 }
Beispiel #13
0
        public void CanClone()
        {
            PermissionMap original = new PermissionMap(Permission.ReadWrite, new string[] { "role1" }, new string[] { "user1" });
            PermissionMap cloned   = original.Clone();

            Assert.That(original.Permissions, Is.EqualTo(cloned.Permissions));
            Assert.That(original.Users.Length, Is.EqualTo(cloned.Users.Length));
            Assert.That(original.Roles.Length, Is.EqualTo(cloned.Roles.Length));
            Assert.That(original.Users[0], Is.EqualTo(cloned.Users[0]));
            Assert.That(original.Roles[0], Is.EqualTo(cloned.Roles[0]));
        }
Beispiel #14
0
        public ActionResult Detail(int id)
        {
            try
            {
                PermissionMapRepository ml = new PermissionMapRepository();

                PermissionMap obj = ml.GetPermissionMap(id);

                return(View(obj));
            }
            catch (Exception ex)
            {
                return(Content(ContentIcon.Error + "|" + ErrorWirter(RouteData, ex.Message)));
            }
        }
Beispiel #15
0
        public ActionResult Edit(int id)
        {
            try
            {
                PermissionMapRepository ml = new PermissionMapRepository();

                PermissionMap obj = ml.GetPermissionMap(id);

                ViewData["ForeachMenuByOption"]       = ForeachMenuByOption(obj.MID, 0);
                ViewData["ForeachPermissionByOption"] = ForeachPermissionByOption(obj.PID, 0, 1);

                return(View(obj));
            }
            catch (Exception ex)
            {
                return(Content(ContentIcon.Error + "|" + ErrorWirter(RouteData, ex.Message)));
            }
        }
Beispiel #16
0
        protected override void Render(HtmlTextWriter writer)
        {
            if (RequiredPermission == Permission.None)
            {
                RequiredPermission = Page.GetType().GetCustomAttributes(typeof(IPermittable), true).OfType <IPermittable>()
                                     .Select(p => PermissionMap.GetMaximumPermission(p.RequiredPermission))
                                     .OrderByDescending(rp => rp)
                                     .FirstOrDefault();
            }

            var item = new SelectionUtility(this, Page.GetEngine()).SelectedItem;

            if (!Page.GetEngine().SecurityManager.IsAuthorized(Page.User, item, RequiredPermission))
            {
                cv.IsValid = false;
                cv.RenderControl(writer);
            }
            else
            {
                base.Render(writer);
            }
        }
Beispiel #17
0
        public ActionResult Create(FormCollection formCollection)
        {
            try
            {
                PermissionMapRepository ml = new PermissionMapRepository();

                PermissionMap obj = new PermissionMap()
                {
                    CreateDate = DateTime.Now, CreateUserID = ID, IsDeleted = false
                };

                UpdateModel(obj);

                bool result = ml.Insert(obj) > 0 ? true : false;

                return(result ? Content(ContentIcon.Succeed + "|操作成功|/Admin/PermissionMap/Index") : Content(ContentIcon.Error + "|操作失败"));
            }
            catch (Exception ex)
            {
                return(Content(ContentIcon.Error + "|" + ErrorWirter(RouteData, ex.Message)));
            }
        }
Beispiel #18
0
        public ActionResult Index(int?pageIndex, int?pageSize, PermissionMap entity)
        {
            try
            {
                PermissionMapRepository ml = new PermissionMapRepository();
                entity.IsDeleted = false;
                PagedList <PermissionMap> page = ml.Search(entity).GetPagedList(pageIndex ?? PageIndex, pageSize ?? PageSize, Order, By);
                if (page != null && page.TotalItemCount > 0)
                {
                    foreach (var item in page)
                    {
                        if (item.Menu.ID == 0)
                        {
                            PermissionDataRepository pl = new PermissionDataRepository();
                            var plts = pl.Search().Where(b => b.PID == item.ID).ToList();
                            if (plts != null)
                            {
                                pl.Deletes(plts);
                            }
                            ml.Delete(item);
                        }
                    }
                    page = ml.Search(entity).GetPagedList(pageIndex ?? PageIndex, pageSize ?? PageSize, Order, By);
                }
                IList <PermissionMap> objs = page;

                if (Request.IsAjaxRequest())
                {
                    return(PartialView("_Index", objs));
                }

                return(View(objs));
            }
            catch (Exception ex)
            {
                return(Content(ContentIcon.Error + "|" + ErrorWirter(RouteData, ex.Message)));
            }
        }
Beispiel #19
0
        public ActionResult Edit(int id, FormCollection formCollection)
        {
            try
            {
                PermissionMapRepository ml = new PermissionMapRepository();

                PermissionMap obj = ml.GetPermissionMap(id);

                UpdateModel(obj);

                obj.LastUpdateDate = DateTime.Now;

                obj.LastUpdateUserID = ID;

                bool result = ml.Update(obj) > 0 ? true : false;

                return(result ? Content(ContentIcon.Succeed + "|操作成功") : Content(ContentIcon.Error + "|操作失败"));
            }
            catch (Exception ex)
            {
                return(Content(ContentIcon.Error + "|" + ErrorWirter(RouteData, ex.Message)));
            }
        }
        public ActionResult AccessFor(string uap)
        {
            var Data         = Newtonsoft.Json.JsonConvert.DeserializeObject <List <PermissionMap> >(uap);
            var permissionId = Data.FirstOrDefault().PermissionId;

            var defaultUserExist = _context.PermissionMaps.Where(x => x.PermissionId == permissionId).Any(x => x.ApplicationUserId == DefaultUserId);

            foreach (var data in Data)
            {
                if (defaultUserExist)
                {
                    ViewBag.Message = "Please Select a User First.";
                    return(RedirectToAction("AccessFor"));
                }
                PermissionMap current_uap = _context.PermissionMaps.Find(data.PermissionId);
                current_uap.IsPermitted = bool.Parse(data.IsPermitted.ToString());
            }

            _context.SaveChanges();

            //return Json(a);
            return(RedirectToAction("Index"));
        }
        public void CreateUserParmission(string Id)
        {
            var userRoles = Context.UserRoles.ToList();

            //var mapData = Context.PermissionMaps.Where(x => x.ApplicationUserId == Id).Include(x => x.UserRole).ToList();
            foreach (var item in userRoles)
            {
                var mapData = Context.PermissionMaps.Where(x => x.ApplicationUserId == Id).FirstOrDefault(x => x.RoleId == item.RoleId);

                if (mapData != null)
                {
                    continue;
                }

                PermissionMap permissionMap = new PermissionMap()
                {
                    RoleId            = item.RoleId,
                    ApplicationUserId = Id,
                    IsPermitted       = false
                };
                Context.PermissionMaps.Add(permissionMap);
                Context.SaveChanges();
            }
        }
Beispiel #22
0
 /// <summary>Gets the permissions for the logged in user towards an item.</summary>
 /// <param name="item">The item for which permissions should be retrieved.</param>
 /// <returns>A permission flag.</returns>
 public virtual Permission GetMaximumPermission(ContentItem item)
 {
     return(PermissionMap.GetMaximumPermission(Security.GetPermissions(WebContext.User, item)));
 }
        /// <summary>
        /// 自动生成菜单及权限结构
        /// </summary>
        /// <param name="title"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private static void AutoGenerateMenuAndMap(string title, string url)
        {
            DBContext db = new DBContext();

            //分析当前地址
            url = url.Substring(0, url.LastIndexOf("/") + 1) + "Index";
            int menuID = 0;

            //寻找菜单
            try
            {
                menuID = db.FromSql("SELECT * FROM [Menu] AS m WHERE [Url] LIKE '" + url.ToLower() + "'").ToFirst <Menu>().ID;
                if (menuID < 1)
                {
                    throw new Exception("菜单中不存在则新建");
                }
            }
            catch
            {
                try
                {
                    //若当前数据库中不存在该菜单,则自动创建一个菜单
                    var mt = new Menu()
                    {
                        Name             = title,
                        ParentID         = 0,
                        Icon             = "icos-list-images",
                        Url              = url,
                        Sort             = 0,
                        Level            = 1,
                        IsDeleted        = false,
                        LastUpdateDate   = DateTime.Now,
                        CreateDate       = DateTime.Now,
                        CreateUserID     = CurrentMember.ID,
                        LastUpdateUserID = CurrentMember.ID
                    };
                    MenuRepository ml = new MenuRepository();
                    menuID = ml.Insert(mt);
                }
                catch { }
            }
            //权限结构
            var  pmt    = new PermissionMap();
            bool hasMap = false;

            try
            {
                pmt = db.FromSql("SELECT * FROM [PermissionMap] AS pm WHERE [MID]=" + menuID + " AND [Name]='" + title + "'").ToFirst <PermissionMap>();
                if (pmt != null && pmt.ID > 0)
                {
                    hasMap = true;
                }
            }
            catch { }
            if (hasMap == false)
            {
                //自动产生权限结构
                pmt = new PermissionMap()
                {
                    SortID           = GetSort(title),
                    MID              = menuID,
                    Name             = title,
                    Description      = title,
                    IsBasic          = 0,
                    CreateUserID     = CurrentMember.ID,
                    CreateDate       = DateTime.Now,
                    LastUpdateDate   = DateTime.Now,
                    LastUpdateUserID = CurrentMember.ID,
                    IsDeleted        = false
                };
                var pml = new PermissionMapRepository();
                pml.Insert(pmt);
            }
        }
 /// <summary>
 /// 验证当前地址权限
 /// </summary>
 /// <param name="privilegeValue">/admin/article/index</param>
 /// <returns></returns>
 public static bool IsPast(string title, string url)
 {
     if (site.IsValidePermission == true)
     {
         //
         //开发者开发时使用此代码,后继发布后因性能优化需要屏蔽下行代码
         //
         AutoGenerateMenuAndMap(title, url);
         //
         PermissionHelper permission = new PermissionHelper();
         try
         {
             if (CurrentMember.ID > 0 && CurrentMember.RoleID == 1)
             {
                 return(true);
             }
             //菜单查询
             int menuID = 0;
             try
             {
                 var menuUrl = url.Substring(0, url.LastIndexOf("/") + 1) + "Index";
                 if (permission.Menus != null)
                 {
                     foreach (var item in permission.Menus)
                     {
                         if (!string.IsNullOrEmpty(item.Url) && item.Url.ToUpper() == menuUrl.ToUpper())
                         {
                             menuID = item.ID;
                         }
                     }
                 }
             }
             catch
             {
                 menuID = 0;
             }
             if (menuID == 0)
             {
                 return(true);
             }
             //查询权限配置表,若有明确记录不允许访问,则返回false
             var pmt = new PermissionMap();
             try
             {
                 pmt = permission.PermissionMaps.Where(b => b.MID == menuID && b.Name == title).First();
             }
             catch { return(true); }
             var plts = permission.PermissionDatas.Where(b => b.RID == CurrentMember.RoleID && b.PID == pmt.ID);
             if (plts != null)
             {
                 foreach (var item in plts)
                 {
                     if (item.HasPermission == false)
                     {
                         return(false);
                     }
                 }
             }
         }
         catch { }
     }
     return(true);
 }