public RolePermissionDto MapWithPermission(RolePermission entity)
 {
     return new RolePermissionDto
                {
                    Permission = new PermissionDtoMapper().Map(entity.Permission)
                };
 }
 public void CreateRolePermissions(Role role, IList<Permission> rList)
 {
     foreach (Permission permission in rList)
     {
         RolePermission rolePermission = new RolePermission();
         rolePermission.Role = role;
         rolePermission.Permission = permission;
         entityDao.CreateRolePermission(rolePermission);
     }
 }
Ejemplo n.º 3
0
        public async Task <ActionResult> proc()
        {
            var json  = new StreamReader(Request.Body).ReadToEnd();
            var items = JsonConvert.DeserializeObject <List <JGN_RolePermissions> >(json);

            if (items.Count > 0)
            {
                var roleid = items[0].roleid;
                RolePermission.DeleteRole(_context, (short)roleid);
                foreach (var permission in items)
                {
                    await RolePermission.Add(_context, permission);
                }
            }
            return(Ok(new { status = "success", message = SiteConfig.generalLocalizer["_records_processed"].Value }));
        }
Ejemplo n.º 4
0
        public ActionResult AddAminUserAllPermissions()
        {
            //List<RolePersmissions> rp=new List<RolePersmissions>();
            foreach (var item in db.Permissions.ToList())
            {
                var role = new RolePermission
                {
                    Id           = 1,
                    PermissionId = item.Id
                };
                db.RolePermissions.Add(role);
            }
            db.SaveChanges();

            return(View());
        }
Ejemplo n.º 5
0
        public Either <Error, Success> AllowRolePermissions(DtoLinkRolePermissions link)
        {
            var result = _appContext.Roles.FindEither(link.RoleId).Bind(
                role =>
            {
                link.PermissionIds.Select(permission => _appContext.Permissions.Find <Permission>(permission)).Select(
                    permission =>
                {
                    RolePermission.Create(permission, role).Bind <EntityEntry <RolePermission> >(x => _appContext.RolePermissions.Add(x));
                    return(Right <Error, Permission>(permission));
                });
                var t = _appContext.TrySaveChanges().Bind <Success>(_ => Success.ItsSuccess);
                return(t);
            });

            return(result);
        }
Ejemplo n.º 6
0
        public async Task <ActionResult> Create([Bind(Include = "PermissionId,RoleId")] RolePermission rolePermission)
        {
            if (ModelState.IsValid && rolePermission.PermissionId != 0)
            {
                db.RolePermission.Add(rolePermission);
                await db.SaveChangesAsync();

                return(RedirectToAction("Edit", "Roles", new { id = rolePermission.RoleId }));
            }
            ViewBag.Id     = rolePermission.RoleId;
            ViewBag.RoleId = new SelectList(db.Roles.Where(x => x.Id == rolePermission.RoleId), "Id", "Name");
            var rolePermissions = db.RolePermission.Where(x => x.RoleId == rolePermission.RoleId).Select(r => r.PermissionId).ToList();

            ViewBag.PermissionId = new SelectList(db.Permissions.Where(x => x.Enabled).Where(r => !rolePermissions.Contains(r.Id)), "Id", "Name", rolePermission.PermissionId);

            return(View(rolePermission));
        }
        public IActionResult Modify(string roleId, string permissionId, [FromBody] RolePermission o)
        {
#if DEBUG
            DataConnection.TurnTraceSwitchOn();
            DataConnection.WriteTraceLine = (msg, context) => Debug.WriteLine(msg, context);
#endif
            if (ModelState.IsValid)
            {
                using (var db = new peppaDB())
                {
                    o.modified_by = CurrentAccountId;
                    var count = db.Update <RolePermission>(o);
                    return(Ok(count));
                }
            }
            return(BadRequest());
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> AddRolePermission([FromBody] RolePermission rolePermission)
        {
            NewResponseModel newRolePermissionResponseModel = new NewResponseModel();

            try
            {
                await _db.AddRolePermission(rolePermission);

                newRolePermissionResponseModel.Message = "Success !!!";
                return(Ok(newRolePermissionResponseModel));
            }
            catch (Exception ex)
            {
                newRolePermissionResponseModel.Message = ex.Message;
                return(BadRequest(newRolePermissionResponseModel));
            }
        }
Ejemplo n.º 9
0
        public async Task UpdateAsync(RolePermission rolePermission, CancellationToken cancellationToken)
        {
            if (rolePermission == null)
            {
                throw new ArgumentNullException(nameof(rolePermission));
            }

            Context.Attach(rolePermission);
            Context.Update(rolePermission);

            try
            {
                await Context.SaveChangesAsync(cancellationToken);
            }

            catch (DbUpdateConcurrencyException) { }
        }
Ejemplo n.º 10
0
        public HttpResponseMessage Post(IEnumerable <RolePermission> entity)
        {
            using (var session = NHibernateHelper.CreateSessionFactory())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var queryString = Request
                                      .GetQueryNameValuePairs()
                                      .ToDictionary(x => x.Key, x => x.Value);

                    var roleId = Convert.ToInt32(queryString["roleId"]);

                    var existingData = session.CreateCriteria(typeof(RolePermission)).List <RolePermission>();
                    var filteredData = existingData.Where(x => x.Role.Id.Equals(roleId));

                    foreach (var n in filteredData)
                    {
                        RolePermission n1       = n;
                        var            contains = entity.Where(x => x.Permission.Id == n1.Permission.Id);
                        if (!contains.Any())
                        {
                            session.Delete(n1);
                        }
                    }

                    if (entity != null)
                    {
                        foreach (var n in entity)
                        {
                            RolePermission n1       = n;
                            var            contains = filteredData.Where(x => x.Permission.Id == n1.Permission.Id);
                            if (!contains.Any())
                            {
                                session.SaveOrUpdate(n1);
                            }
                        }
                    }

                    transaction.Commit();


                    // return as HttpResponseMessage
                    return(WebApiHelper.ObjectToHttpResponseMessage(entity));
                }
            }
        }
Ejemplo n.º 11
0
        public async Task <RolePermissionModel> AddRolePermissionAsync(RolePermissionModel model)
        {
            long id = model.RolePermissionId;

            using (var dataService = DataServiceFactory.CreateDataService())
            {
                var rolePermission = new RolePermission();
                if (rolePermission != null)
                {
                    UpdateRolePermissionFromModel(rolePermission, model);
                    await dataService.AddRolePermissionAsync(rolePermission);

                    model.Merge(await GetRolePermissionAsync(dataService, rolePermission.RolePermissionId));
                }
                return(model);
            }
        }
Ejemplo n.º 12
0
        public async Task <ActionResult> Edit(string id)
        {
            ViewData["ActionType"] = "Update";
            AddJS("Role", "/admin/js/Role/RoleManage.js");
            if (!string.IsNullOrEmpty(id))
            {
                RolePermission     rolePermission = new RolePermission();
                RoleManager        roleManager    = new RoleManager();
                PermissionManager  permission     = new PermissionManager();
                IList <PageAction> pageActions    = await permission.GetAllPageAction();

                string apiURL   = APIURL.IdentityBaseUri + IdentityAPI.Role.GetByID;
                var    userRole = new {
                    id = id
                };
                RoleViewModel role = await roleManager.GetRoleByID(id);

                RoleViewModel lstRolesFromApi = await _apiClient.PostAsync <RoleViewModel>(userRole, apiURL);

                if (lstRolesFromApi != null)
                {
                    lstRolesFromApi.IsActive = lstRolesFromApi.Enabled;
                    if (role != null)
                    {
                        lstRolesFromApi.AliasName           = role.AliasName;
                        lstRolesFromApi.IsSystem            = role.IsSystem;
                        lstRolesFromApi.SelectedPageActions = role.SelectedPageActions;
                        lstRolesFromApi.CanEdit             = role.CanEdit;
                    }
                    else
                    {
                        lstRolesFromApi.AliasName           = string.Empty;
                        lstRolesFromApi.SelectedPageActions = string.Empty;
                    }
                }
                rolePermission.PageActions   = pageActions;
                rolePermission.RoleViewModel = lstRolesFromApi;
                Task <Dictionary <string, string> > localized = LocalizeData(Path.Combine("Localization", "Role", "role"));
                ViewData["localized"] = await localized;
                return(View("Create", rolePermission));
            }
            else
            {
                return(View(nameof(Index)));
            }
        }
        public ActionResult Edit(int id)
        {
            RolePermission          rolePermission          = db.RolePermissions.Find(id);
            RolePermissionViewModel rolePermissionViewModel = new RolePermissionViewModel();

            rolePermissionViewModel.RolePermissingID = rolePermission.RolePermissingID;
            rolePermissionViewModel.RoleID           = rolePermission.RoleID;
            rolePermissionViewModel.PageID           = rolePermission.PageID;

            List <Role> ListofRoles = db.Roles.ToList();

            ViewBag.Roles = new SelectList(ListofRoles, "RoleID", "RoleName", rolePermission.RoleID);
            List <Page> ListofPages = db.Pages.ToList();

            ViewBag.ListofPages = new SelectList(ListofPages, "PageID", "PageName", rolePermission.PageID);
            return(View(rolePermissionViewModel));
        }
Ejemplo n.º 14
0
        public static void AccessControl(List <CmsMenuViewModel> menus, RolePermission role)
        {
            foreach (var item in menus)
            {
                var permission = GetPermissionString(item);
                //var permission
                var haspermission = Kooboo.Sites.Authorization.PermissionService.HasPermission(permission, role.Tree);
                if (haspermission)
                {
                    continue;
                }
                else
                {
                    if (item.HasSubItem)
                    {
                        bool HasNonHideItem = false;
                        foreach (var submenu in item.Items)
                        {
                            var subPermission = GetPermissionString(submenu);
                            if (string.IsNullOrEmpty(subPermission))
                            {
                                continue;
                            }
                            var subHasPermission = Kooboo.Sites.Authorization.PermissionService.HasPermission(subPermission, role.Tree);
                            if (subHasPermission)
                            {
                                HasNonHideItem = true;
                            }
                            else
                            {
                                submenu.Hide = true;
                            }
                        }

                        if (!HasNonHideItem)
                        {
                            item.Hide = true;
                        }
                    }
                    else
                    {
                        item.Hide = true;
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public ActionResult RolePermission(string roleId, string[] selectedPermissions)
        {
            if (selectedPermissions == null)
            {
                return(RedirectToAction("RolePermission", new { roleId }));
            }

            List <int> selectPermissions = new List <int>();

            selectPermissions.AddRange(selectedPermissions.Select(ro => Convert.ToInt32(ro)));

            foreach (var permit in db.Permissions.ToList())
            {
                #region Add permission if is in selectedPermissions and is not in RolePermissions

                if (selectPermissions.Contains(permit.Id) && !db.RolePermissions
                    .Where(a => a.RoleId == roleId && a.PermissionId == permit.Id).Any())
                {
                    RolePermission rPermit = new RolePermission()
                    {
                        RoleId       = roleId,
                        PermissionId = permit.Id
                    };
                    db.RolePermissions.Add(rPermit);
                    db.SaveChanges();
                }

                #endregion

                #region Delete Role if is in UserRoles  and is not in selectRoles

                if (!selectPermissions.Contains(permit.Id) && db.RolePermissions
                    .Where(a => a.RoleId == roleId && a.PermissionId == permit.Id).Any())
                {
                    RolePermission rPermision = db.RolePermissions
                                                .Where(a => a.RoleId == roleId && a.PermissionId == permit.Id).FirstOrDefault();
                    db.RolePermissions.Remove(rPermision);
                    db.SaveChanges();
                }

                #endregion
            }

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Convert RolePermission to RolePermissionViewModel
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static RolePermissionViewModel ToViewModel(this RolePermission model)
        {
            var dto = new RolePermissionViewModel();

            if (model != null)
            {
                if (model.Permission != null)
                {
                    dto.PermissionId = model.Permission.Id;
                }
                if (model.Role != null)
                {
                    dto.RoleId = model.Role.Id;
                }
                dto.Id = model.Id;
            }
            return(dto);
        }
Ejemplo n.º 17
0
        private void btnCopy_Click(object sender, EventArgs e)
        {
            var rolePermission = new RolePermission();
            // 读取角色数据
            var userEntites = (from object t in this.cklstUser.CheckedItems select BaseEntity.Create <PiUserEntity>(((System.Data.DataRowView)t).Row)).ToList();

            // 角色复制到剪切板
            rolePermission.UserEntites = userEntites;
            // 模块访问权限复制到剪切板
            string[] grantModuleIds = this.GetGrantModuleIds();
            rolePermission.GrantModuleIds = grantModuleIds;
            // 操作权限复制到剪切板
            string[] grantPermissionIds = this.GetGrantPermissionIds();
            rolePermission.GrantPermissionIds = grantPermissionIds;

            Clipboard.SetData("rolePermission", rolePermission);
            this.btnPaste.Enabled = true;
        }
        public static Response <RolePermission> Delete(this RolePermission request,
                                                       Factory factory,
                                                       IHttpRequest httpRequest)
        {
            factory.Execute(proxy => {
                proxy.DeleteFromCache <AuthRolePermission>();
                proxy.Delete <RolePermission>(q => q.Id == request.Id);
            });

            List <RolePermission> data = new List <RolePermission>();

            data.Add(request);

            return(new Response <RolePermission>()
            {
                Data = data
            });
        }
        public IActionResult Create([FromBody] RolePermission o)
        {
#if DEBUG
            DataConnection.TurnTraceSwitchOn();
            DataConnection.WriteTraceLine = (msg, context) => Debug.WriteLine(msg, context);
#endif
            if (ModelState.IsValid)
            {
                using (var db = new peppaDB())
                {
                    o.created_by  = CurrentAccountId;
                    o.modified_by = CurrentAccountId;
                    o.uid         = db.InsertWithInt32Identity <RolePermission>(o);
                    return(CreatedAtAction(nameof(Get), new { roleId = o.role_id, permissionId = o.permission_id }, o));
                }
            }
            return(BadRequest());
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 更新角色权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="permissionIds"></param>
        public void UpdateRolePermission(int roleId, int[] permissionIds)
        {
            using (ISession session = AuthoritySessionProvider.GetSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    Role role = session
                                .QueryOver <Role>()
                                .And(x => x.Id == roleId)
                                .List()
                                .FirstOrDefault();

                    if (role != null)
                    {
                        if (role.RolePermissions.Any())
                        {
                            role.RolePermissions.Clear();
                        }

                        IList <Permission> permissions = session
                                                         .QueryOver <Permission>()
                                                         .And(Restrictions.In("Id", permissionIds))
                                                         .Fetch(SelectMode.Fetch, x => x.AuthorityPage)
                                                         .JoinQueryOver <AuthorityPage>(x => x.AuthorityPage)
                                                         .List();

                        foreach (var item in permissions)
                        {
                            RolePermission rolePermission = new RolePermission
                            {
                                AuthorityPage = item.AuthorityPage,
                                Permission    = item,
                                Role          = role
                            };
                            role.RolePermissions.Add(rolePermission);
                        }

                        session.SaveOrUpdate(role);
                    }

                    transaction.Commit();
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// this method is used to add role and permission
        /// </summary>
        /// <param name="rolePermission"></param>
        /// <returns></returns>
        public int AddRoleAndPermission(RolePermission rolePermission)
        {
            try
            {
                var currentRolePermission = _rolePermissionDataRepository.FirstOrDefault(x => x.RoleId == rolePermission.RoleId && x.ChildPermissionId == rolePermission.ChildPermissionId);
                if (currentRolePermission == null)
                {
                    _rolePermissionDataRepository.Add(rolePermission);
                    _rolePermissionDataRepository.SaveChanges();
                }

                return(rolePermission.Id);
            }
            catch (Exception ex)
            {
                _errorLog.LogException(ex);
                throw;
            }
        }
Ejemplo n.º 22
0
        public async Task <ActionResult> UpdatePermission(List <RolePermissionViewModel> permissions)
        {
            if (permissions != null)
            {
                try
                {
                    // Filter permission with status is true
                    var model = new List <RolePermission>();
                    foreach (var item in permissions)
                    {
                        if (item.IsUsed)
                        {
                            var tmp = new RolePermission
                            {
                                PermissionId = item.Id,
                                RoleId       = item.RoleId
                            };
                            model.Add(tmp);
                        }
                    }

                    //Call API Provider
                    var token = _userSession.BearerToken;
                    var ret   = await APIProvider.Authorize_DynamicTransaction <List <RolePermission>, string>(model, token, "Role/UpdatePermission", APIConstant.API_Resource_Authorize);

                    if (ret == null)
                    {
                        TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.SUCCESS, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_UPDATE, ApplicationGenerator.TypeResult.SUCCESS));
                    }
                    else
                    {
                        TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_UPDATE, ApplicationGenerator.TypeResult.FAIL));
                    }
                }
                catch (Exception ex)
                {
                    TempData["Alert"] = ApplicationGenerator.RenderResult(ApplicationGenerator.TypeResult.FAIL, ApplicationGenerator.GeneralActionMessage(APIConstant.ACTION_UPDATE, ApplicationGenerator.TypeResult.FAIL));
                    Logger.LogError(ex);
                    throw ex.GetBaseException();
                }
            }
            return(RedirectToAction("Index"));
        }
        public void ShoudAssignPermission()
        {
            // Arrange
            Guid expectedPermissionId = Guid.NewGuid();

            Role actual = Role.Create(Guid.NewGuid(), "Name",
                                      "Code");

            // Act
            actual.AssignPermission(expectedPermissionId);

            // Assert
            Assert.IsTrue(actual.RolePermissions != null);
            Assert.IsTrue(actual.RolePermissions.Count == 1);
            RolePermission link = actual.RolePermissions.FirstOrDefault();

            Assert.IsTrue(link != null);
            Assert.IsTrue(link.PermissionId == expectedPermissionId);
        }
Ejemplo n.º 24
0
        public ActionResult Updata(RolePermission pope)
        {
            if (pope.RoleID != null || pope.PermissionID != null)
            {
                pope.ID = sId;
                //声明数据库上下文类
                PermissionEntities perEntities = new PermissionEntities();
                System.Data.Entity.Infrastructure.DbEntityEntry entityEntry = perEntities.Entry(pope);
                entityEntry.State = System.Data.Entity.EntityState.Modified;
                perEntities.SaveChanges();
            }
            else
            {
                return(Content("名称为空"));
            }


            return(Redirect("/RolePermission_Zhang_/List"));
        }
Ejemplo n.º 25
0
        public async Task <ResponseResult> PostPermission(RolePermission rolePermission)
        {
            var result = new ResponseResult();

            if (rolePermission != null && rolePermission.FunctionIds != null)
            {
                var permissons = new List <RoleFunctionDto>();
                foreach (var fid in rolePermission.FunctionIds)
                {
                    permissons.Add(new RoleFunctionDto {
                        RoleId = rolePermission.RoleId, FunctionId = fid
                    });
                }

                await _roleService.UpdateRolePermission(rolePermission.RoleId, permissons);
            }

            return(result);
        }
Ejemplo n.º 26
0
 /// <summary>
 ///
 /// </summary>
 private void InsertPermissions()
 {
     foreach (HtmlInputCheckBox permissionsCheckBox in dirtyControls.Keys)
     {
         HtmlInputHidden rolePermissionIdField = dirtyControls[permissionsCheckBox];
         RolePermission  biz = new RolePermission();
         if (permissionsCheckBox.Checked)
         {
             biz[RolePermission.RoleId]       = _roleId;
             biz[RolePermission.PermissionId] = int.Parse(permissionsCheckBox.Value);
             biz.Save();
         }
         else if (!string.IsNullOrEmpty(rolePermissionIdField.Value))
         {
             int rolePermissionId = int.Parse(rolePermissionIdField.Value);
             biz.Delete(rolePermissionId);
         }
     }
 }
        public ReturnType UpdateRolePermission(RolePermission rolepermission)
        {
            try
            {
                using (AladingEntities alading = new AladingEntities(AppSettings.GetConnectionString()))
                {
                    /*RolePermission result = alading.RolePermission.Where(p => p.RolePermissionID == rolepermission.RolePermissionID).FirstOrDefault();*/
                    RolePermission result = alading.RolePermission.Where(p => p.RolePermissionCode == rolepermission.RolePermissionCode).FirstOrDefault();
                    if (result == null)
                    {
                        return(ReturnType.NotExisted);
                    }
                    #region   Using Attach() Function Update,Default USE;
                    alading.Attach(result);
                    alading.ApplyPropertyChanges("RolePermission", rolepermission);
                    #endregion

                    #region    Using All Items Replace To Update ,Default UnUse

                    /*
                     *
                     *  result.PermissionCode = rolepermission.PermissionCode;
                     *
                     *  result.RoleCode = rolepermission.RoleCode;
                     *
                     */
                    #endregion
                    if (alading.SaveChanges() == 1)
                    {
                        return(ReturnType.Success);
                    }
                    return(ReturnType.OthersError);
                }
            }
            catch (SqlException sex)
            {
                return(ReturnType.ConnFailed);
            }
            catch (Exception ex)
            {
                return(ReturnType.OthersError);
            }
        }
        private Role MapAndAddRole(AddRoleCommand command, IExecutionContext executionContext, List <Permission> permissions)
        {
            _permissionValidationService.EnforceHasPermissionToUserArea(command.UserAreaCode, executionContext.UserContext);

            var role = new Role();

            role.Title        = command.Title.Trim();
            role.UserAreaCode = command.UserAreaCode;

            foreach (var permission in EnumerableHelper.Enumerate(permissions))
            {
                var rolePermission = new RolePermission();
                rolePermission.Permission = permission;
                role.RolePermissions.Add(rolePermission);
            }

            _dbContext.Roles.Add(role);
            return(role);
        }
Ejemplo n.º 29
0
        public async Task <List <RolePermission> > UpdateRolePermissions(int toUpdateRoleId, List <int> toUpdatePermissionIds)
        {
            var dbRole = await GetSingleRole(toUpdateRoleId);

            if (dbRole == null)
            {
                return(null);
            }

            var oldRolePermissionsList = await _context.RolePermissions.Where(u => u.RoleId == dbRole.Id).ToListAsync();

            if (toUpdatePermissionIds == null) // do nothing, just show existed info.
            {
                return(oldRolePermissionsList);
            }

            var newRolePermissionsList = new List <RolePermission>();

            foreach (var permissionId in toUpdatePermissionIds)
            {
                var dbPermission = await _context.Permissions.FirstOrDefaultAsync(r => r.Id == permissionId);

                if (dbRole == null)
                {
                    continue;
                }

                var newRolePermission = new RolePermission
                {
                    PermissionId = dbPermission.Id,
                    RoleId       = dbRole.Id
                };
                newRolePermissionsList.Add(newRolePermission);
            }


            _context.RolePermissions.RemoveRange(oldRolePermissionsList);
            _context.RolePermissions.AddRange(newRolePermissionsList);
            await _context.SaveChangesAsync();

            return(newRolePermissionsList);
        }
        public async Task <RESTResult> SetPermissionToRoleAsync(Guid currentUserId, RolePermissionDto rolePermissionInfo)
        {
            RESTResult result = new RESTResult {
                Code = RESTStatus.NotData
            };

            if (rolePermissionInfo.RoleId == null)
            {
                result.Message = "The role id could not be null";
                return(result);
            }
            if (rolePermissionInfo.PermissionIds.Contains(null))
            {
                result.Message = "The permision ids could not be null";
                return(result);
            }
            //TOOD:Get the current role permission
            var rolePermissions = await _rolePermissionRepository.GetAllListAsync(item => item.RoleId.Equals(rolePermissionInfo.RoleId));

            //TODO: remove the exist role permission
            foreach (var item in rolePermissions)
            {
                await _rolePermissionRepository.DeleteAsync(item);
            }
            RolePermission rolePermissionEntity;

            foreach (var permissionId in rolePermissionInfo.PermissionIds)
            {
                //TODO: Add new permission;
                rolePermissionEntity = new RolePermission
                {
                    RoleId         = rolePermissionInfo.RoleId.Value,
                    PermissionId   = permissionId.Value,
                    CreateByUserId = currentUserId,
                    CreateTime     = DateTime.Now
                };
                await _rolePermissionRepository.InsertAsync(rolePermissionEntity);
            }
            result.Code    = RESTStatus.Success;
            result.Message = "Set permission to role successful";
            return(result);
        }
Ejemplo n.º 31
0
 /// <summary>
 /// To add the role permission details.
 /// </summary>
 /// <param name="rolepermission"></param>
 /// <param name="accessToken"></param>
 /// <returns></returns>
 public bool AddRolePermission(RolePermission rolepermission, string accessToken)
 {
     try
     {
         dynamic session = null;
         if (!string.IsNullOrEmpty(accessToken))
         {
             session = _sessionManager.GetSessionValues(accessToken);
         }
         if (!string.IsNullOrEmpty(session.DatabaseId()) || _isNonPCR)
         {
             using (var repository = new RolePermissionRepository(session.DatabaseId()))
             {
                 bool IsExistRoleAndPermission = repository.CheckRoleAndPermission(rolepermission.RoleID, rolepermission.PermissionID);
                 if (IsExistRoleAndPermission)
                 {
                     bool IsexistRolePermissionCount = repository.ExistRolePermission(rolepermission.RoleID, rolepermission.PermissionID);
                     if (IsexistRolePermissionCount)
                     {
                         rolepermission.CreatedDate = DateTime.Now;
                         rolepermission.UpdatedDate = DateTime.Now;
                         repository.AddRolePermission(rolepermission);
                         return(true);
                     }
                     else
                     {
                         return(false);
                     }
                 }
             }
         }
         else
         {
             throw new Exception("Unable to get database connection.");
         }
     }
     catch
     {
         throw;
     }
     return(false);
 }
Ejemplo n.º 32
0
        public bool AddOrUpdateRolePermissionInfo(IDbCommand icmd, RolePermission info, EnumAddOrUpdate mode)
        {
            icmd.Parameters.Clear();
            MySqlCommand cmd = icmd as MySqlCommand;

            cmd.CommandType = CommandType.Text;
            if (mode == EnumAddOrUpdate.Add)
            {
                string sql = @"insert into t_role_permission(id,rid,pid,updatetime) values('{0}','{1}','{2}','{3}')";
                cmd.CommandText = string.Format(sql, info.id, info.rid, info.pid, info.updatetime);
            }
            else if (mode == EnumAddOrUpdate.Update)
            {
                string sql = @"update t_role_permission set rid = '{0}',pid = '{1}',updatetime = '{2}'
                                where id = '{3}'";
                cmd.CommandText = string.Format(sql, info.rid, info.pid, info.updatetime, info.id);
            }
            cmd.ExecuteNonQuery();
            return(true);
        }
Ejemplo n.º 33
0
 public static int Update(Zippy.Data.IDalProvider db, RolePermission entity)
 {
     return db.Update(entity);
 }
Ejemplo n.º 34
0
        private void btnCopy_Click(object sender, EventArgs e)
        {
            RolePermission rolePermission = new RolePermission();
            // 模块访问权限复制到剪切板
            string[] grantModuleIds = this.GetGrantModuleIds();
            rolePermission.GrantModuleIds = grantModuleIds;
            // 操作权限复制到剪切板
            string[] grantPermissionIds = this.GetGrantPermissionIds();
            rolePermission.GrantPermissionIds = grantPermissionIds;

            Clipboard.SetData("rolePermission", rolePermission);
            this.btnPaste.Enabled = true;
        }
 public virtual void DeleteRolePermission(RolePermission entity)
 {
     Delete(entity);
 }
Ejemplo n.º 36
0
 public static int Insert(Zippy.Data.IDalProvider db, RolePermission entity)
 {
     int rtn = db.Insert(entity);
     return rtn;
 }
 public virtual void CreateRolePermission(RolePermission entity)
 {
     Create(entity);
 }
 public virtual void UpdateRolePermission(RolePermission entity)
 {
     Update(entity);
 }
        partial void UpdateRolePermission(RolePermission instance) {
            int rc;
            string errorinfo = null;

            rc = this.P_RolePermission_U(
                    m_UserContext,
                    (int?)instance.RolePermissionID,
                    (int?)instance.RoleID,
                    (int?)instance.PermissionID,
                    ref errorinfo);
            if (rc != 0) {
              throw new Exception(errorinfo != String.Empty ? errorinfo : string.Format(UnknownError, rc));
            }
        }
 public virtual void UpdateRolePermission(RolePermission entity)
 {
     entityDao.UpdateRolePermission(entity);
 }
Ejemplo n.º 41
0
 public void AddToRolePermissions(RolePermission rolePermission)
 {
     base.AddObject("RolePermissions", rolePermission);
 }
Ejemplo n.º 42
0
 public static RolePermission CreateRolePermission(string roleName, string permissionId)
 {
     RolePermission rolePermission = new RolePermission();
     rolePermission.RoleName = roleName;
     rolePermission.PermissionId = permissionId;
     return rolePermission;
 }
Ejemplo n.º 43
0
 /// <summary>
 /// 增加一种权限
 /// </summary>
 /// <param name="roleID"></param>
 /// <param name="permissionID"></param>
 /// <param name="permissionType"></param>
 /// <param name="tenantID"></param>
 /// <param name="optUser"></param>
 /// <param name="db"></param>
 public static void SetPermission(Guid roleID, long permissionID, int permissionType, Guid? tenantID, Guid? optUser, Zippy.Data.IDalProvider db)
 {
     RolePermission rp = db.FindUnique<RolePermission>("RoleID=@RoleID and PermissionID=@PermissionID and TenantID=@TenantID",
         db.CreateParameter("RoleID", roleID), db.CreateParameter("PermissionID", permissionID), db.CreateParameter("TenantID", tenantID));
     if (rp == null)
     {
         rp = new RolePermission();
         rp.RoleID = roleID;
         rp.PermissionID = permissionID;
         rp.PermissionType = permissionType;
         rp.TenantID = tenantID;
         rp.Creator = optUser;
         db.Insert(rp);
     }
     else
     {
         rp.PermissionType = rp.PermissionType | permissionType;
         rp.Updater = optUser;
         rp.UpdateDate = DateTime.Now;
         db.Update(rp);
     }
 }
Ejemplo n.º 44
0
        private void btnCopy_Click(object sender, EventArgs e)
        {
            RolePermission rolePermission = new RolePermission();
            // 读取角色数据
            List<BaseUserEntity> userEntites = new List<BaseUserEntity>();
            for (int i = 0; i < this.cklstUser.CheckedItems.Count; i++)
            {
                BaseUserEntity userEntity = new BaseUserEntity(((System.Data.DataRowView)this.cklstUser.CheckedItems[i]).Row);
                userEntites.Add(userEntity);
            }
            // 角色复制到剪切板
            rolePermission.UserEntites = userEntites;
            // 模块访问权限复制到剪切板
            string[] grantModuleIds = this.GetGrantModuleIds();
            rolePermission.GrantModuleIds = grantModuleIds;
            // 操作权限复制到剪切板
            string[] grantPermissionIds = this.GetGrantPermissionIds();
            rolePermission.GrantPermissionIds = grantPermissionIds;

            Clipboard.SetData("rolePermission", rolePermission);
            this.btnPaste.Enabled = true;
        }
 public virtual void CreateRolePermission(RolePermission entity)
 {
     entityDao.CreateRolePermission(entity);
 }
 public static RolePermission CreateRolePermission(long permissionID, bool allowed)
 {
     RolePermission rolePermission = new RolePermission();
     rolePermission.PermissionID = permissionID;
     rolePermission.Allowed = allowed;
     return rolePermission;
 }
        partial void InsertRolePermission(RolePermission instance) {
            int rc;
            string errorinfo = null;
            int? RolePermissionID = instance.RolePermissionID;

            rc = this.P_RolePermission_I(
                    m_UserContext,
                    ref RolePermissionID,
                    (int?)instance.RoleID,
                    (int?)instance.PermissionID,
                    ref errorinfo);
            instance.RolePermissionID = RolePermissionID.GetValueOrDefault();
            if (rc != 0) {
              throw new Exception(errorinfo != String.Empty ? errorinfo : string.Format(UnknownError, rc));
            }
        }
 public void SetData(Role role)
 {
     foreach (HtmlTableRow row in m_Table.Rows)
     {
         for (int i = 0; i < row.Cells.Count; i++)
         {
             if (row.Cells[i].Controls.Count > 0)
             {
                 if (row.Cells[i].Controls[0] is ASPxCheckBox)
                 {
                     ASPxCheckBox chk = (ASPxCheckBox)row.Cells[i].Controls[0];
                     char action = Char.Parse(chk.ID.Substring(4, 1));
                     int id = int.Parse(chk.ID.Remove(0, 6));
                     SelectionPermission sp = new SelectionPermission(id, "", action);
                     if (chk.Checked)
                     {
                         if (!selectedList.Contains(sp))
                         {
                             RolePermission rp = new RolePermission
                             {
                                 RoleID = role.RoleID,
                                 PermissionID = sp.PermissionID
                             };
                             role.RolePermissions.Add(rp);
                         }
                     }
                     else
                     {
                         if (selectedList.Contains(sp))
                         {
                             var result = from rps in GetDatabaseContext().RolePermissions where rps.RoleID == role.RoleID && rps.PermissionID == sp.PermissionID select rps;
                             RolePermission rp = result.SingleOrDefault();
                             if (rp != null)
                             {
                                 GetDatabaseContext().RolePermissions.DeleteOnSubmit(rp);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 public virtual void DeleteRolePermission(RolePermission entity)
 {
     entityDao.DeleteRolePermission(entity);
 }