예제 #1
0
        public void CheckPermission2()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Permission, Guid> perRepository = new Repository<Permission, Guid>(store);
                PermissionService service = new PermissionService(perRepository);

                IRepository<Employee, Guid> empRepository = new Repository<Employee, Guid>(store);
                IRepository<Entity, Guid> entRepository = new Repository<Entity, Guid>(store);

                //人資部門可以看見Admin
                var operations = service.GetOperationFor(empRepository.Query(s => s.Name == "Fred").First()
                    , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(1, operations.Count);
                Assert.AreEqual("View", operations.First().Comment);

                //業務部門看不見
                var operation2s = service.GetOperationFor(empRepository.Query(s => s.Name == "Kalad").First()
                   , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(0, operation2s.Count);

                //老板通常是有超多權限,但只留較上層的權限
                var operation3s = service.GetOperationFor(empRepository.Query(s => s.Name == "Allen").First()
                  , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(1, operation3s.Count);
            }
        }
예제 #2
0
        public ActionResult Create(CreateAdminUserModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var service = new PermissionService(DataContext);
                    service.CreateUser(new AdminUser
                    {
                        UserName = model.UserName,
                        Email = model.Email,
                        Password = model.Password,
                        RoleId = model.RoleId
                    });
                    ShowSuccess(MessageResource.CreateSuccess);

                    return RedirectToIndex();
                }
                catch (Exception ex)
                {
                    LogError(ex.ToString());
                    ShowError(MessageResource.CreateFailed);
                }
            }

            return View(model);
        }
예제 #3
0
        public NavigatorModel CreateNavigatorModel(string userID, string selectedLocationId, int? selectedHeaderId)
        {
            var permissionsByUser = new PermissionService().GetPermissionDTOsByUserID(userID);
            var headers = new HeaderService().GetHeaderNavigationDTOs();

            return new NavigatorModel()
            {
                Locations = permissionsByUser.GroupBy(l => l.LocationId).Select(grp => CreateLocationItemModel(grp, headers, selectedLocationId, selectedHeaderId)),
                CurrentUserName = userID
            };
        }
        public void InitializeTest()
        {
            m_unitOfWork = new MemoryUnitOfWork();
            m_repository = new MemoryPermissionRepository(m_unitOfWork);

            for (int i = 1; i <= 5; i++)
            {
                m_repository.Add(new Permission() { ActionName = "Action " + i, ControllerName = "Controller" });
            }

            m_unitOfWork.Commit();

            m_target = new PermissionService(m_repository, m_unitOfWork);
        }
예제 #5
0
파일: UserFactory.cs 프로젝트: Dani88/GFIS
        public EditUserModel CreateEditUserModel(string userId)
        {
            var permissionFactory = new PermissionFactory();

            var userDetails = CreateUserDetailsModel(new UserService().GetUserById(userId));
            var locations = new LocationService().GetAllLocations().ToList();
            var permissions = new PermissionService().GetAllPermissions().Select(permissionFactory.CreatePermissionModel).ToList();

            return new EditUserModel()
            {
                Locations = locations,
                Permissions = permissions,
                UserDetails = userDetails
            };
        }
예제 #6
0
파일: UserFactory.cs 프로젝트: Dani88/GFIS
 public UserDetailsListModel CreateUserDetailsListModel(string userNameFilter, int pageIndex, int pageSize)
 {
 
     var permissionFactory = new PermissionFactory();
 
     var userDetailsModels = new UserService().GetUsersByName(userNameFilter, pageIndex, pageSize).Select(CreateUserDetailsModel).ToList();
 
     var locations = new LocationService().GetAllLocations();
 
     var permissions = new PermissionService().GetAllPermissions().Select(permissionFactory.CreatePermissionModel).ToList();
 
     return new UserDetailsListModel()
     {
         Locations = locations,
         Permission = permissions,
         Users = new Common.PageableList<UserDetailsModel>(userDetailsModels, pageSize, pageIndex)
     };
 }
예제 #7
0
        public void CheckPermission1()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Permission, Guid> perRepository = new Repository<Permission, Guid>(store);
                PermissionService service = new PermissionService(perRepository);

                IRepository<Employee, Guid> empRepository = new Repository<Employee, Guid>(store);
                IRepository<Entity,Guid> entRepository = new Repository<Entity,Guid>(store);

                var operations = service.GetOperationFor(empRepository.Query(s => s.Name == "Allen").First()
                    , entRepository.Query(q => q.Name == "Personal Information").First());

                Assert.AreEqual(1, operations.Count);
                Assert.AreEqual("Full Control", operations.First().Comment);

            }
        }
예제 #8
0
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.flpResourcePanel.Controls.Count > 0)
                {
                    throw new ApplicationException("权限列表已经被初始化过,不能重复初始化。");
                }


                List <Resource> resList = new List <Resource>();
                resList.Add(new Resource("采购单录入"));
                resList.Add(new Resource("作废我的采购单"));
                resList.Add(new Resource("冲销我的采购单"));
                resList.Add(new Resource("查询我的采购单"));
                resList.Add(new Resource("查询全部采购单"));
                resList.Add(new Resource("作废全部采购单"));
                resList.Add(new Resource("冲销全部采购单"));
                resList.Add(new Resource("己方退货单录入"));
                resList.Add(new Resource("己方退货单作废"));
                resList.Add(new Resource("己方退货单查询"));
                resList.Add(new Resource("按商品汇总采购量"));
                resList.Add(new Resource("按品种汇总采购量"));
                resList.Add(new Resource("按产地汇总采购量"));
                resList.Add(new Resource("按开票员汇总采购量"));

                resList.Add(new Resource("销货单录入"));
                resList.Add(new Resource("作废我的销货单"));
                resList.Add(new Resource("冲销我的销货单"));
                resList.Add(new Resource("查询我的销货单"));
                resList.Add(new Resource("查询全部销货单"));
                resList.Add(new Resource("作废全部销货单"));
                resList.Add(new Resource("冲销全部销货单"));
                resList.Add(new Resource("客方退货单录入"));
                resList.Add(new Resource("客方退货单作废"));
                resList.Add(new Resource("客方退货单查询"));
                resList.Add(new Resource("按商品汇总销量"));
                resList.Add(new Resource("按品种汇总销量"));
                resList.Add(new Resource("按产地汇总销量"));
                resList.Add(new Resource("按开票员汇总销量"));

                resList.Add(new Resource("报废出库"));
                resList.Add(new Resource("废品库查询"));
                resList.Add(new Resource("废品库管理"));
                resList.Add(new Resource("盘亏调整"));
                resList.Add(new Resource("盘盈调整"));
                resList.Add(new Resource("盘点日志查询"));
                resList.Add(new Resource("缺货预警"));
                resList.Add(new Resource("积压预警"));
                resList.Add(new Resource("库存商品明细查询"));
                resList.Add(new Resource("库存分析"));
                resList.Add(new Resource("设置预警边界"));

                resList.Add(new Resource("调拨出库单"));
                resList.Add(new Resource("调补出库单作废"));
                resList.Add(new Resource("调拨入库单"));
                resList.Add(new Resource("调补入库单作废"));
                resList.Add(new Resource("调拨出库单查询"));
                resList.Add(new Resource("调拨入库单查询"));

                resList.Add(new Resource("销售收入统计"));
                resList.Add(new Resource("采购成本统计"));
                resList.Add(new Resource("利润统计"));
                resList.Add(new Resource("销售员考核"));
                resList.Add(new Resource("业务员考核"));

                PermissionService service = new PermissionService();
                service.InitResources(resList);

                //显示权限列表
                this.LoadResourceView();
            }
            catch (Exception ex)
            {
                ErrorHandler.OnError(ex);
            }
        }
        public ActionResult EditPost(EditPostViewModel editPostViewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Got to get a lot of things here as we have to check permissions
                // Get the post
                var post = PostService.Get(editPostViewModel.Id);

                // Get the topic
                var topic    = post.Topic;
                var category = CategoryService.Get(topic.CategoryId);
                topic.Category = category;

                // get the users permissions
                var permissions = PermissionService.GetPermissions(category, _membersGroup, MemberService, CategoryPermissionService);

                if (post.MemberId == CurrentMember.Id || permissions[AppConstants.PermissionModerate].IsTicked)
                {
                    // User has permission so update the post
                    post.PostContent = AppHelpers.GetSafeHtml(BannedWordService.SanitiseBannedWords(editPostViewModel.Content));
                    post.DateEdited  = DateTime.UtcNow;

                    // if topic starter update the topic
                    if (post.IsTopicStarter)
                    {
                        // if category has changed then update it
                        if (topic.Category.Id != editPostViewModel.Category)
                        {
                            var cat = CategoryService.Get(editPostViewModel.Category);
                            topic.Category = cat;
                        }

                        topic.IsLocked = editPostViewModel.IsLocked;
                        topic.IsSticky = editPostViewModel.IsSticky;
                        topic.Name     = AppHelpers.GetSafeHtml(BannedWordService.SanitiseBannedWords(editPostViewModel.Name));

                        // See if there is a poll
                        if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0)
                        {
                            // Now sort the poll answers, what to add and what to remove
                            // Poll answers already in this poll.
                            var postedIds = editPostViewModel.PollAnswers.Select(x => x.Id);
                            //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList();
                            var existingAnswers     = editPostViewModel.PollAnswers.Where(x => topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var newPollAnswers      = editPostViewModel.PollAnswers.Where(x => !topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();

                            // Loop through existing and update names if need be
                            //TODO: Need to think about this in future versions if they change the name
                            //TODO: As they could game the system by getting votes and changing name?
                            foreach (var existPollAnswer in existingAnswers)
                            {
                                // Get the existing answer from the current topic
                                var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id);
                                if (pa != null && pa.Answer != existPollAnswer.Answer)
                                {
                                    // If the answer has changed then update it
                                    pa.Answer = existPollAnswer.Answer;
                                }
                            }

                            // Loop through and remove the old poll answers and delete
                            foreach (var oldPollAnswer in pollAnswersToRemove)
                            {
                                // Delete
                                PollService.Delete(oldPollAnswer);

                                // Remove from Poll
                                topic.Poll.PollAnswers.Remove(oldPollAnswer);
                            }

                            // Poll answers to add
                            foreach (var newPollAnswer in newPollAnswers)
                            {
                                var npa = new PollAnswer
                                {
                                    Poll   = topic.Poll,
                                    Answer = newPollAnswer.Answer
                                };
                                PollService.Add(npa);
                                topic.Poll.PollAnswers.Add(npa);
                            }
                        }
                        else
                        {
                            // Need to check if this topic has a poll, because if it does
                            // All the answers have now been removed so remove the poll.
                            if (topic.Poll != null)
                            {
                                //Firstly remove the answers if there are any
                                if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any())
                                {
                                    var answersToDelete = new List <PollAnswer>();
                                    answersToDelete.AddRange(topic.Poll.PollAnswers);
                                    foreach (var answer in answersToDelete)
                                    {
                                        // Delete
                                        PollService.Delete(answer);

                                        // Remove from Poll
                                        topic.Poll.PollAnswers.Remove(answer);
                                    }
                                }

                                // Now delete the poll
                                var pollToDelete = topic.Poll;
                                PollService.Delete(pollToDelete);

                                // Remove from topic.
                                topic.Poll = null;
                            }
                        }
                    }

                    // redirect back to topic
                    var message = new GenericMessageViewModel
                    {
                        Message     = Lang("Post.Updated"),
                        MessageType = GenericMessages.Success
                    };
                    try
                    {
                        unitOfWork.Commit();
                        ShowMessage(message);
                        return(Redirect(topic.Url));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LogError(ex);
                        throw new Exception(Lang("Errors.GenericError"));
                    }
                }

                return(NoPermission(topic));
            }
        }
예제 #10
0
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (e.Action == TreeViewAction.ByKeyboard || e.Action == TreeViewAction.ByMouse)
                {
                    lblDescription.Text = e.Node.Tag == null ? "" : e.Node.Tag.ToString();
                }

                PermissionService service = new PermissionService();
                if (e.Node.Parent != null)
                {
                    if (!service.IsUserAccess(e.Node.Text))
                    {
                        throw new ApplicationException("权限不足,无法执行此操作!");
                    }
                }

                switch (e.Node.Text)
                {
                case "销货单录入":
                    CtrlBillInput ctrl = new CtrlBillInput();
                    this.AddCtrlIntoPanel(ctrl);
                    ctrl.BillType    = new CacheService().GetBillType(BILL_TYPE);
                    ctrl.CompanyType = Tg029.Storage.Model.CompanyType.Customer;
                    break;

                case "作废我的销货单":
                    CtrlBillOp ctrlOp = new CtrlBillOp();
                    this.AddCtrlIntoPanel(ctrlOp);
                    ctrlOp.BillType = new CacheService().GetBillType(BILL_TYPE);
                    ctrlOp.CancelOutButtonVisible = false;
                    ctrlOp.BlankOutButtonVisible  = true;
                    ctrlOp.MakerConditionVisible  = false;
                    break;

                case "冲销我的销货单":
                    CtrlBillOp ctrlC = new CtrlBillOp();
                    this.AddCtrlIntoPanel(ctrlC);
                    ctrlC.BillType = new CacheService().GetBillType(BILL_TYPE);
                    ctrlC.BlankOutButtonVisible  = false;
                    ctrlC.CancelOutButtonVisible = true;
                    ctrlC.MakerConditionVisible  = false;
                    break;

                case "作废全部销货单":
                    CtrlBillOp ctrlOpAll = new CtrlBillOp();
                    this.AddCtrlIntoPanel(ctrlOpAll);
                    ctrlOpAll.BillType = new CacheService().GetBillType(BILL_TYPE);
                    ctrlOpAll.CancelOutButtonVisible = false;
                    ctrlOpAll.BlankOutButtonVisible  = true;
                    ctrlOpAll.MakerConditionVisible  = true;
                    break;

                case "冲销全部销货单":
                    CtrlBillOp ctrlCAll = new CtrlBillOp();
                    ctrlCAll.BillType = new CacheService().GetBillType(BILL_TYPE);
                    ctrlCAll.CancelOutButtonVisible = true;
                    ctrlCAll.BlankOutButtonVisible  = false;
                    ctrlCAll.MakerConditionVisible  = true;
                    break;

                case "客户退货单录入":
                    CtrlBillInput cbi = new CtrlBillInput();
                    this.AddCtrlIntoPanel(cbi);
                    cbi.BillType    = new CacheService().GetBillType("客户退货单");
                    cbi.CompanyType = Tg029.Storage.Model.CompanyType.Customer;
                    break;

                case "客户退还单作废":
                    CtrlBillOp cbo = new CtrlBillOp();
                    this.AddCtrlIntoPanel(cbo);
                    cbo.BillType = new CacheService().GetBillType("客户退货单");
                    cbo.BlankOutButtonVisible  = true;
                    cbo.CancelOutButtonVisible = false;
                    cbo.MakerConditionVisible  = true;
                    break;

                case "查询我的销货单":
                    CtrlReport rpt = new CtrlReport();
                    rpt.ReportTemplateFile   = System.IO.Path.Combine(Application.StartupPath, "MySalesBill.grf");
                    rpt.IsSupportChildReport = true;
                    this.AddCtrlIntoPanel(rpt);

                    break;

                case "按商品汇总销量":
                    CtrlReport rpt1 = new CtrlReport();
                    rpt1.ReportTemplateFile   = System.IO.Path.Combine(Application.StartupPath, "RptSalesByGoods.grf");
                    rpt1.IsSupportChildReport = false;
                    this.AddCtrlIntoPanel(rpt1);
                    break;

                default:

                    break;
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.OnError(ex);
            }
        }
 public ActionResult GetPermission(int id)
 {
     PermissionService permissionService = new PermissionService();
     Dictionary<string, string> permissionList = permissionService.BuildPermission(id);
     return Json(permissionList, JsonRequestBehavior.AllowGet);
 }
예제 #12
0
        public void Setup()
        {
            this.assembler = new Assembler(this.uri);
            this.session   = new Mock <ISession>();
            this.session.Setup(x => x.Assembler).Returns(this.assembler);
            var dal = new Mock <IDal>();

            dal.Setup(x => x.IsReadOnly).Returns(false);
            this.session.Setup(x => x.Dal).Returns(dal.Object);

            this.sitedir         = new SiteDirectory(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.modelsetup      = new EngineeringModelSetup(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.iterationSetup  = new IterationSetup(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.person          = new Person(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.domain1         = new DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.domain2         = new DomainOfExpertise(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.personRole      = new PersonRole(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.participant     = new Participant(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.participantRole = new ParticipantRole(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.model           = new EngineeringModel(Guid.NewGuid(), this.assembler.Cache, this.uri)
            {
                EngineeringModelSetup = this.modelsetup
            };
            this.iteration = new Iteration(Guid.NewGuid(), this.assembler.Cache, this.uri)
            {
                IterationSetup = this.iterationSetup
            };
            this.definition   = new Definition(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.srdl         = new SiteReferenceDataLibrary(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.booleanpt    = new BooleanParameterType(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.person2      = new Person(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.elementDef   = new ElementDefinition(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.relationship = new BinaryRelationship(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.parameter    = new Parameter(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.valueset     = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.requirementsSpecification = new RequirementsSpecification(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.requirement     = new Requirement(Guid.NewGuid(), this.assembler.Cache, this.uri);
            this.commonFileStore = new CommonFileStore(Guid.NewGuid(), this.assembler.Cache, this.uri);

            this.sitedir.Model.Add(this.modelsetup);
            this.sitedir.Person.Add(this.person);
            this.sitedir.Person.Add(this.person2);
            this.sitedir.PersonRole.Add(this.personRole);
            this.sitedir.Domain.Add(this.domain1);
            this.sitedir.Domain.Add(this.domain2);
            this.modelsetup.IterationSetup.Add(this.iterationSetup);
            this.modelsetup.Participant.Add(this.participant);
            this.sitedir.ParticipantRole.Add(this.participantRole);
            this.model.Iteration.Add(this.iteration);
            this.person.Role        = this.personRole;
            this.participant.Person = this.person;
            this.participant.Role   = this.participantRole;
            this.participant.Domain.Add(this.domain1);
            this.modelsetup.Definition.Add(this.definition);
            this.sitedir.SiteReferenceDataLibrary.Add(this.srdl);
            this.srdl.ParameterType.Add(this.booleanpt);
            this.iteration.Element.Add(this.elementDef);
            this.iteration.Relationship.Add(this.relationship);
            this.elementDef.Parameter.Add(this.parameter);
            this.parameter.ValueSet.Add(this.valueset);

            this.modelsetup.EngineeringModelIid = this.model.Iid;
            this.iterationSetup.IterationIid    = this.iteration.Iid;
            this.elementDef.Owner   = this.domain1;
            this.relationship.Owner = this.domain1;
            this.parameter.Owner    = this.domain1;
            this.requirementsSpecification.Requirement.Add(this.requirement);
            this.iteration.RequirementsSpecification.Add(this.requirementsSpecification);
            this.model.CommonFileStore.Add(this.commonFileStore);

            this.session.Setup(x => x.ActivePerson).Returns(this.person);
            this.session.Setup(x => x.Assembler).Returns(this.assembler);
            this.session.Setup(x => x.OpenIterations).Returns(new Dictionary <Iteration, Tuple <DomainOfExpertise, Participant> >
            {
                { this.iteration, new Tuple <DomainOfExpertise, Participant>(this.domain1, this.participant) }
            });

            this.permissionService = new PermissionService(this.session.Object);
        }
        public IActionResult SavePermissionRole([FromBody] PermissionModel model)
        {
            var result = PermissionService.SavePermissionMenu(model.RoleId, model.MenuIds, null);

            return(MyJson(result));
        }
예제 #14
0
 public PermissionValidator(PermissionService permissionService)
 {
     _permissionService = permissionService ?? throw new ArgumentNullException(nameof(permissionService));
     ConfigureRules();
 }
예제 #15
0
 /// <summary>
 /// 查询设置单位的最大禁止有效菜单数据 (禁止菜单数据源)
 /// </summary>
 public object QueryCompanyMaxValidForbiddenMenus(string id)
 {
     return(ConstructMenuViews(PermissionService.QueryPermissionOfUserRole(getUserRole(Guid.Parse(id)), Website.Transaction)));
 }
예제 #16
0
 /// <summary>
 /// 得到公司的已有的额外权限
 /// </summary>
 /// <returns></returns>
 public object QueryCompantValidMenusOfCompanyId(string companyId)
 {
     return(ConstructMenuViews(PermissionService.QueryCompanyAllowablePermission(Guid.Parse(companyId), Website.Transaction)));
 }
예제 #17
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     try
     {
         //Verify
         if (string.IsNullOrEmpty(this.txtCode.Text.Trim()))
         {
             throw new ApplicationException("编码不能为空");
         }
         if (string.IsNullOrEmpty(this.txtName.Text.Trim()))
         {
             throw new ApplicationException("名称不能为空");
         }
         if (string.IsNullOrEmpty(this.txtUnit.Text.Trim()))
         {
             throw new ApplicationException("单位不能为空");
         }
         if (string.IsNullOrEmpty(this.txtStandard.Text.Trim()))
         {
             throw new ApplicationException("规格不能为空");
         }
         if (this.cmbCategory.SelectedItem == null)
         {
             throw new ApplicationException("品种不能为空");
         }
         if (this.cmbFrom.SelectedItem == null)
         {
             throw new ApplicationException("产地不能为空");
         }
         //save
         ModelService modelService = new ModelService();
         if (this.Model == null)//新建
         {
             Drugs model = new Drugs();
             model.Code      = this.txtCode.Text.Trim();
             model.Name      = this.txtName.Text.Trim();
             model.UnitPrice = Convert.ToDecimal(this.txtUnitPrice.Text.Trim());
             model.Standard  = this.txtStandard.Text.Trim();
             model.Unit      = this.txtUnit.Text.Trim();
             model.From      = (DrugFrom)this.cmbFrom.SelectedItem;
             model.Category  = (DrugCategory)this.cmbCategory.SelectedItem;
             model.Actived   = this.ckbActived.Checked;
             model.Remark    = this.txtRemark.Text.Trim();
             modelService.CreateDrug(model, PermissionService.GetCurrentUser().Name);
         }
         else//修改
         {
             this.Model.Code      = this.txtCode.Text.Trim();
             this.Model.Name      = this.txtName.Text.Trim();
             this.Model.UnitPrice = Convert.ToDecimal(this.txtUnitPrice.Text.Trim());
             this.Model.Standard  = this.txtStandard.Text.Trim();
             this.Model.Unit      = this.txtUnit.Text.Trim();
             this.Model.From      = (DrugFrom)this.cmbFrom.SelectedItem;
             this.Model.Category  = (DrugCategory)this.cmbCategory.SelectedItem;
             this.Model.Actived   = this.ckbActived.Checked;
             this.Model.Remark    = this.txtRemark.Text.Trim();
             modelService.SaveDrug(this.Model, PermissionService.GetCurrentUser().Name);
         }
         //close diaglog
         this.DialogResult = DialogResult.OK;
     }
     catch (Exception ex)
     {
         ErrorHandler.OnError(ex);
     }
 }
예제 #18
0
        void cmdChatRepair(BasePlayer player)
        {
            if (!PermissionService.HasPermission(player.userID, REPAIR_TOOL_PERM))
            {
                SendReply(player, "<color=#fec384>У вас нет доступа к данной команде!\nДля разблокировки приобретите услугу в магазине <color=#d2722d>rustylife.ru</color></color>");
                return;
            }
            if (cooldowns.ContainsKey(player.userID))
            {
                SendReply(player, string.Format(Messages["cooldown"], cooldowns[player.userID]));
                return;
            }
            List <ulong>       owners = GetClanMembers(player.userID);
            List <DecayEntity> blocks = new List <DecayEntity>();

            Vis.Entities(player.GetNetworkPosition(), radius, blocks, repairLayer, QueryTriggerInteraction.Ignore);

            Dictionary <ItemDefinition, int> repairCost = new Dictionary <ItemDefinition, int>();

            foreach (var block in blocks)
            {
                if (owners.Contains(block.OwnerID) && (block.ShortPrefabName.ContainsAny("foundation", "gates", "wall.external.high")))
                {
                    var cost = block.RepairCost(GetRepairFraction(block));
                    foreach (var item in cost)
                    {
                        if (!repairCost.ContainsKey(item.itemDef))
                        {
                            repairCost[item.itemDef] = 0;
                        }
                        repairCost[item.itemDef] += (int)item.GetAmount();
                    }
                    if (block.ShortPrefabName.ContainsAny("gates", "wall.external.high") && block.health < block.MaxHealth())
                    {
                        if (!repairCost.ContainsKey(stones))
                        {
                            repairCost[stones] = 0;
                        }
                        repairCost[stones] += 500;
                    }
                }
            }
            cooldowns[player.userID] = cooldownSeconds;
            if (repairCost.Count == 0)
            {
                SendReply(player, Messages["damagedObjectNotFound"]);
                return;
            }

            foreach (var cost in repairCost)
            {
                var amount = player.inventory.GetAmount(cost.Key.itemid);
                if (amount < cost.Value)
                {
                    SendReply(player, string.Format(Messages["insufficientResources"], cost.Value - amount, cost.Key.displayName.english));
                    return;
                }
            }

            foreach (var block in blocks)
            {
                block.health = block.MaxHealth();
                block.SendNetworkUpdate();
            }

            var msg = "<color=#ffcc00><size=16>Ремонт:\n";

            foreach (var cost in repairCost)
            {
                List <Item> items = new List <Item>();
                player.inventory.Take(items, cost.Key.itemid, cost.Value);
                foreach (var item in items)
                {
                    item.Remove();
                }
                msg += $"<color=#ff2200>{cost.Value}</color> x {cost.Key.displayName.english}\n";
            }

            msg += "</size></color>";

            SendReply(player, msg);
        }
예제 #19
0
 public MenuController(PermissionService permissionService, MenuService menuService)
 {
     _permissionService = permissionService;
     _menuService       = menuService;
 }
예제 #20
0
 public HomeController(ArticleService articleService, PermissionService permissionService)
 {
     _articleService    = articleService;
     _permissionService = permissionService;
 }
예제 #21
0
 public PermissionManager(string userId)
 {
     _userId  = userId;
     _service = new PermissionService();
     Init();
 }
예제 #22
0
 public void Reload()
 {
     Permissions = PermissionService.GetAll();
     NotifyOfPropertyChange(() => Permissions);
 }
예제 #23
0
 public MyResult <object> DeleteRoles([FromBody] RoleModel model)
 {
     return(PermissionService.DeleteRoles(model));
 }
예제 #24
0
 /// <summary>
 /// 得到公司的已有的禁止权限
 /// </summary>
 /// <returns></returns>
 public object QueryCompanyMaxValidForbiddenMenusOfCompanyId(string companyId)
 {
     return(ConstructMenuViews(PermissionService.QueryCompanyForbiddenPermission(Guid.Parse(companyId), Website.Transaction)));
 }
        /// <summary>
        /// 查询可用角色Id
        /// </summary>
        /// <returns>用户Id</returns>
        public IActionResult QueryRoleIds([FromQuery] Guid accountId)
        {
            var data = PermissionService.QueryMenuIds(accountId);

            return(MyJson(data));
        }
예제 #26
0
        /// <summary>
        /// 查询当前单位最大有效的菜单数据
        /// </summary>
        /// <param name="website">网站</param>
        public object QueryCompanyValidMenus(Website website)
        {
            UserRole userrole = GetUserRoles(this.CurrentCompany);

            return(ConstructMenuViews(PermissionService.QueryPermissionOfCompany(this.CurrentCompany.CompanyId, userrole, website)));
        }
        public IActionResult SaveAccountRole([FromBody] AccountRoleModel model)
        {
            var result = PermissionService.SavePermissionRole(model.AccountId, model.Roles, null);

            return(MyJson(result));
        }
예제 #28
0
 /// <summary>
 /// 保存单位的额外权限
 /// </summary>
 /// <param name="company">单位Id</param>
 /// <param name="permissionView">权限信息</param>
 public void SaveCompanyAllowablePermission(string company, List <PermissionView.MenuView> menuViews)
 {
     PermissionService.SaveCompanyAllowablePermission(Guid.Parse(company), Website.Transaction, menuViews, this.CurrentUser.UserName);
 }
예제 #29
0
 public PermissionModule(PermissionService ps)
 {
     this.PermissionService = ps;
 }
예제 #30
0
 public PermissionController()
 {
     _service = new PermissionService();
 }
 public void SetPermission(int id, FormCollection formInfo)
 {
     //ToTest
     //int modifyUserId = Convert.ToInt32(Session["UserId"]);
     int modifyUserId = 1;
     PermissionService permissionService = new PermissionService();
     permissionService.ClearPermission(id);
     permissionService.CreatePermission(id, formInfo.AllKeys, modifyUserId);
 }
예제 #32
0
 public AdminMembersController(RoleSevice roleSevice, PermissionService permissionService, LoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, MembershipService membershipService, SettingsService settingsService, LocalizationService localizationService)
     : base(loggingService, unitOfWorkManager, membershipService, settingsService, localizationService)
 {
     _permissionService = permissionService;
     _roleSevice        = roleSevice;
 }
 public PageBaseViewModel()
 {
     _permissionService = new PermissionService();
     Connectivity.ConnectivityChanged += ConnectivityOnConnectivityChanged;
     IsNotConnected = Connectivity.NetworkAccess != NetworkAccess.Internet;
 }
예제 #34
0
        public void CheckPermission7()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Permission, Guid> perRepository = new Repository<Permission, Guid>(store);
                PermissionService service = new PermissionService(perRepository);

                IRepository<Post, Guid> postRepository = new Repository<Post, Guid>(store);
                IRepository<Entity, Guid> entRepository = new Repository<Entity, Guid>(store);

                var operations = service.GetOperationFor(postRepository.Query(s => s.Name == "管理課副主管").First()
                    , entRepository.Query(q => q.Name == "員工請假報表").First());

                Assert.AreEqual(1, operations.Count);
                Assert.AreEqual("Full Control", operations.First().Comment);
            }
        }
예제 #35
0
 public PermissionsController(PermissionService permissionService)
 {
     _permissionService = permissionService;
 }
예제 #36
0
        public void CheckPermission9()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Permission, Guid> perRepository = new Repository<Permission, Guid>(store);
                PermissionService service = new PermissionService(perRepository);

                IRepository<Organization, Guid> orgRepository = new Repository<Organization, Guid>(store);
                IRepository<Entity, Guid> entRepository = new Repository<Entity, Guid>(store);

                var operations = service.GetOperationFor(orgRepository.Query(s => s.Name == "企畫課").First()
                    , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(1, operations.Count);
                Assert.AreEqual("View", operations.First().Comment);
            }
        }
예제 #37
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName)
        {
            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            // Create Hangfire tables
            new SqlServerStorage(connectionStringName);

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance <Func <IPlatformRepository> >(platformRepositoryFactory);
            var moduleCatalog    = container.Resolve <IModuleCatalog>();
            var manifestProvider = container.Resolve <IModuleManifestProvider>();

            #region Caching

            var cacheProvider = new HttpCacheProvider();
            var cacheSettings = new[]
            {
                new CacheSettings(CacheGroups.Settings, TimeSpan.FromDays(1)),
                new CacheSettings(CacheGroups.Security, TimeSpan.FromMinutes(1)),
            };

            var cacheManager = new CacheManager(cacheProvider, cacheSettings);
            container.RegisterInstance <CacheManager>(cacheManager);

            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Settings = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid UserName",
                                    Description = "Your SendGrid account username"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid Password",
                                    Description = "Your SendGrid account password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>();

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            var notificationManager         = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);

            var emailNotificationSendingGateway = new DefaultEmailNotificationSendingGateway(settingsManager);

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();

            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);
            container.RegisterInstance <INotificationTemplateResolver>(resolver);
            container.RegisterInstance <IEmailNotificationSendingGateway>(emailNotificationSendingGateway);
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);


            #endregion

            #region Assets

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties             = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider               = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");

                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var fileSystemBlobProvider = new FileSystemBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
                }
                else if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var azureBlobProvider = new AzureBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
                }
            }

            #endregion

            #region Packaging

            var packagesPath   = HostingEnvironment.MapPath("~/App_Data/InstalledPackages");
            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath);
            container.RegisterInstance <IPackageService>(packageService);

            var uploadsPath = HostingEnvironment.MapPath("~/App_Data/Uploads");
            container.RegisterType <ModulesController>(new InjectionConstructor(packageService, uploadsPath, notifier));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security

            var permissionService = new PermissionService(platformRepositoryFactory, manifestProvider, cacheManager);
            container.RegisterInstance <IPermissionService>(permissionService);

            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion
        }
예제 #38
0
        public ActionResult GroupEdit(int id, string module, bool grant)
        {
            string [] str = module.Split("_".ToCharArray());

            int moduleId = Convert.ToInt32(str[1]);
            Permissions permisson =(Permissions) Enum.Parse(typeof(Permissions), str[0]);
            PermissionService servie = new PermissionService();

            bool value = servie.EnsurePermssionForGroup(id,moduleId, permisson, grant);
            return Json(true, JsonRequestBehavior.AllowGet);
        }
예제 #39
0
        public ActionResult UserEdit(int id, string module, bool grant)
        {
            PermissionService servie = new PermissionService();
            if (module == "SA")
            {
                servie.GrantSA(id, grant, SessionManager.UserInfo.UserID);
                return Json(true, JsonRequestBehavior.AllowGet);
            }

            string[] str = module.Split("_".ToCharArray());

            int moduleId = Convert.ToInt32(str[1]);
            Permissions permisson = (Permissions)Enum.Parse(typeof(Permissions), str[0]);

            bool value = servie.EnsurePermssionForUser(id, moduleId, permisson, grant);
            return Json(true, JsonRequestBehavior.AllowGet);
        }
예제 #40
0
 public MyResult GetRoles()
 {
     return(PermissionService.GetRoles());
 }
예제 #41
0
        public ActionResult Index()
        {
            GMRService<Group> servie = new GMRService<Group>();
            PermissionService pservice = new PermissionService();
            IndexPermissionModel model = new IndexPermissionModel()
            {
                Groups = servie.GetPaged(p => p.GroupID > 0, new Common.EF.IOrderByClause<Group>[] { new OrderByClause<Group, string>(p => p.GroupName, SortDirection.Ascending) }, 1, 100),
                Permissions = pservice.GetPaged(p => p.PermissionID > 0, new Common.EF.IOrderByClause<Permission>[] { new OrderByClause<Permission, DateTime>(p => p.UpdatedDate.Value, SortDirection.Decending) }, 1, 100)
            };

            return View(model);
        }
예제 #42
0
        public UserTests(bool useInMemoryDB = true)
        {
            var roleStore       = useInMemoryDB ? new InMemoryRoleStore() : (IRoleStore) new CouchDbRoleStore(this.DbService(), this.Logger, this.EventContextResolverService);
            var userStore       = useInMemoryDB ? new InMemoryUserStore() : (IUserStore) new CouchDbUserStore(this.DbService(), this.Logger, this.EventContextResolverService, _identifierFormatter);
            var groupStore      = useInMemoryDB ? new InMemoryGroupStore() : (IGroupStore) new CouchDbGroupStore(this.DbService(), this.Logger, this.EventContextResolverService, _identifierFormatter);
            var clientStore     = useInMemoryDB ? new InMemoryClientStore() : (IClientStore) new CouchDbClientStore(this.DbService(), this.Logger, this.EventContextResolverService);
            var permissionStore = useInMemoryDB ? new InMemoryPermissionStore() : (IPermissionStore) new CouchDbPermissionStore(this.DbService(), this.Logger, this.EventContextResolverService);

            var clientService     = new ClientService(clientStore);
            var roleService       = new RoleService(roleStore, permissionStore, clientService);
            var groupService      = new GroupService(groupStore, roleStore, userStore, roleService);
            var userService       = new UserService(userStore);
            var permissionService = new PermissionService(permissionStore, roleService);

            this.Browser = new Browser(with =>
            {
                with.Module(new RolesModule(
                                roleService,
                                clientService,
                                new Domain.Validators.RoleValidator(roleService),
                                this.Logger));

                with.Module(new ClientsModule(
                                clientService,
                                new Domain.Validators.ClientValidator(clientService),
                                this.Logger));

                with.Module(new UsersModule(
                                clientService,
                                permissionService,
                                userService,
                                new Domain.Validators.UserValidator(),
                                this.Logger));

                with.Module(new GroupsModule(
                                groupService,
                                new Domain.Validators.GroupValidator(groupService),
                                this.Logger));

                with.Module(new PermissionsModule(
                                permissionService,
                                clientService,
                                new Domain.Validators.PermissionValidator(permissionService),
                                this.Logger));

                with.RequestStartup((_, pipelines, context) =>
                {
                    context.CurrentUser = new ClaimsPrincipal(
                        new ClaimsIdentity(new List <Claim>
                    {
                        new Claim(Claims.Scope, Scopes.ManageClientsScope),
                        new Claim(Claims.Scope, Scopes.ReadScope),
                        new Claim(Claims.Scope, Scopes.WriteScope),
                        new Claim(Claims.ClientId, "userprincipal"),
                        new Claim(Claims.Sub, "userprincipal"),
                        new Claim(JwtClaimTypes.Role, Group1),
                        new Claim(JwtClaimTypes.Role, Group2),
                        new Claim(JwtClaimTypes.IdentityProvider, IdentityProvider)
                    }, "userprincipal"));
                    pipelines.BeforeRequest += (ctx) => RequestHooks.SetDefaultVersionInUrl(ctx);
                });
            }, withDefaults => withDefaults.HostName("testhost"));

            this.Browser.Post("/clients", with =>
            {
                with.HttpRequest();
                with.FormValue("Id", "userprincipal");
                with.FormValue("Name", "userprincipal");
                with.Header("Accept", "application/json");
            }).Wait();
        }
예제 #43
0
 public UsersService(UsersRepository userRepository, PermissionService permissionService)
 {
     m_userRepository    = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
     m_permissionService = permissionService ?? throw new ArgumentNullException(nameof(permissionService));
 }
예제 #44
0
 public FileUploaderService(IConfiguration configuration, FileUploaderRepository fileUploaderRepository, PermissionService permissionService)
 {
     _configuration          = configuration ?? throw new ArgumentNullException(nameof(configuration));
     _connectionString       = _configuration["AzureStorage:ConnectionString"];
     _fileUploaderRepository = fileUploaderRepository ?? throw new ArgumentNullException(nameof(fileUploaderRepository));
     _permissionService      = permissionService ?? throw new ArgumentNullException(nameof(permissionService));
 }