예제 #1
0
		public void Test1()
		{
			var fixture = new Fixture();
			var project = new
			{
				Id = fixture.Create<string>(),
				CompnentList = new[]
				{
					new { Id = fixture.Create<string>(), ComponentName = fixture.Create<string>() },
					new { Id = fixture.Create<string>(), ComponentName = fixture.Create<string>() },
					new { Id = fixture.Create<string>(), ComponentName = fixture.Create<string>() }
				},
				EnvironmentList = new[]
				{
					new { Id = fixture.Create<string>(), EnvironmentName = fixture.Create<string>() },
					new { Id = fixture.Create<string>(), EnvironmentName = fixture.Create<string>() },
					new { Id = fixture.Create<string>(), EnvironmentName = fixture.Create<string>() }
				}
			};

			using(var session = EmbeddedRavenProvider.DocumentStore.OpenSession())
			{
				var repository = new RavenDBPermissionRepository(session);
				IPermissionManager sut = new PermissionManager(repository);
				var group = sut.CreateGroup(fixture.Create<string>(), null);
				var approveDeploymentPermissionDefinition = sut.CreatePermissionDefinition("ApproveDeployment", "Approve Deployment");

				var roleDataItems = new List<PermissionDataAssignment>
				{
					new PermissionDataAssignment { Id = fixture.Create<string>(), DataPropertyName="Project", DataPropertyValue = fixture.Create<string>() }
				};
				var role = sut.CreateRole("QA Approvers", roleDataItems);
				RoleGroupAssignment roleGroupAssignment = sut.AssignGroupToRole(role.Id, group.Id);
			}
		}
예제 #2
0
 /// <summary>
 /// Gets a list of the roles that a specified user is in for the application.
 /// </summary>
 /// <param name="username">The user to return a list of roles for.</param>
 /// <returns>A string array containing the names of all the roles that the specified user is in for the application.</returns>
 public override string[] GetRolesForUser(string username)
 {
     return(PermissionManager.GetPermissionsForUser(username));
 }
예제 #3
0
 /// <summary>
 /// Checks if a role has a permission.
 /// </summary>
 /// <param name="roleId">The role's id to check it's permission</param>
 /// <param name="permissionName">Name of the permission</param>
 /// <returns>True, if the role has the permission</returns>
 public virtual bool IsGranted(int roleId, string permissionName)
 {
     return(IsGranted(roleId, PermissionManager.GetPermission(permissionName)));
 }
예제 #4
0
 /// <summary>
 /// Checks if a role is granted for a permission.
 /// </summary>
 /// <param name="roleName">The role's name to check it's permission</param>
 /// <param name="permissionName">Name of the permission</param>
 /// <returns>True, if the role has the permission</returns>
 public virtual bool IsGranted(string roleName, string permissionName)
 {
     return(IsGranted((GetRoleByName(roleName)).Id, PermissionManager.GetPermission(permissionName)));
 }
        public IList <FlatPermissionDto> GetAllPermissions()
        {
            var permissions = PermissionManager.GetAllPermissions();

            return(ObjectMapper.Map <List <FlatPermissionDto> >(permissions).OrderBy(p => p.DisplayName).ToList());
        }
예제 #6
0
        /// <summary>
        /// 验证核心
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.HttpContext.Request.Url == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //判断action,controller上是否存在AllowAnonymous标签,任何用户都可以访问
            var actionAnonymous     = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true) as IEnumerable <AllowAnonymousAttribute>;
            var controllerAnonymous = filterContext.Controller.GetType().GetCustomAttributes(typeof(AllowAnonymousAttribute), true) as IEnumerable <AllowAnonymousAttribute>;

            if ((actionAnonymous != null && actionAnonymous.Any()) || (controllerAnonymous != null && controllerAnonymous.Any()))
            {
                return;
            }

            //当前用户
            Mng_User myInfo = new AdminState(filterContext.HttpContext).GetUserInfo();

            if (myInfo == null || !(bool)myInfo.InJob)
            {
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { Controller = "auth", action = "login", area = "" }));
            }
            else
            {
                // 判断action,controller上是否有CheckLoginAttribute标签 只要登录就可以访问
                var checkLoginActionAttr     = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckLoginAttribute), true) as IEnumerable <CheckLoginAttribute>;
                var checkLoginControllerAttr = filterContext.Controller.GetType().GetCustomAttributes(typeof(CheckLoginAttribute), true) as IEnumerable <CheckLoginAttribute>;
                if ((checkLoginActionAttr != null && checkLoginActionAttr.Any()) || (checkLoginControllerAttr != null && checkLoginControllerAttr.Any()))
                {
                    return;
                }

                //如果使用了权限控制标签,则优先使用标签
                var permissionFilterAttribute = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionFilterAttribute), true) as IEnumerable <PermissionFilterAttribute>;
                if (permissionFilterAttribute != null && permissionFilterAttribute.Any())
                {
                    return;
                }

                //获取当前路由信息
                string areaName       = filterContext.RouteData.DataTokens["area"]?.ToString() ?? "";
                string controllerName = filterContext.RouteData.Values["controller"].ToString();
                string actionName     = filterContext.RouteData.Values["action"].ToString();

                //拼接Url
                string url = (areaName != "" ? "/" + areaName : "") + "/" + controllerName + "/" + actionName;

                //验证权限
                bool isValid = PermissionManager.CheckPermission(myInfo, url.ToLower());
                if (!isValid)
                {
                    //验证不通过
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.Result = new HttpUnauthorizedResult(); //Ajax请求,返回401
                    }
                    else
                    {
                        //直接JS跳回上页,并提示
                        var content = new ContentResult()
                        {
                            Content = "<script type=\"text/javascript\">" +
                                      "window.history.go(-1);" +
                                      "alert('您没有该操作权限!');" +
                                      "</script>"
                        };
                        //或者直接跳转页面
                        filterContext.Result = new RedirectResult("/Home/UnAuthorized");//content
                    }
                }
                return;
            }
        }
예제 #7
0
        public Game()
        {
            Console.WriteLine();
            log.Info("» Iniciando Dual Server Para " + CloudServer.HotelName + "...");
            Console.WriteLine();

            SessionUserRecord = 0;
            // Run Extra Settings
            // BotFrankConfig.RunBotFrank();
            ExtraSettings.RunExtraSettings();

            // Run Catalog Settings
            CatalogSettings.RunCatalogSettings();

            // Run Notification Settings
            NotificationSettings.RunNotiSettings();


            _languageManager = new LanguageManager();
            _languageManager.Init();

            _settingsManager = new SettingsManager();
            _settingsManager.Init();

            _packetManager = new PacketManager();
            _clientManager = new GameClientManager();

            _moderationManager = new ModerationManager();
            _moderationManager.Init();

            _itemDataManager = new ItemDataManager();
            _itemDataManager.Init();

            _catalogManager = new CatalogManager();
            _catalogManager.Init(_itemDataManager);

            _craftingManager = new CraftingManager();
            _craftingManager.Init();

            _televisionManager = new TelevisionManager();

            _navigatorManager = new NavigatorManager();
            _roomManager      = new RoomManager();
            _chatManager      = new ChatManager();
            _groupManager     = new GroupManager();
            _groupManager.Init();
            _groupForumManager  = new GroupForumManager();
            _questManager       = new QuestManager();
            _achievementManager = new AchievementManager();
            _talentManager      = new TalentManager();
            _talentManager.Initialize();
            _talentTrackManager = new TalentTrackManager();
            _landingViewManager = new LandingViewManager();
            _gameDataManager    = new GameDataManager();

            _botManager = new BotManager();

            _cacheManager  = new CacheManager();
            _rewardManager = new RewardManager();

            _badgeManager = new BadgeManager();
            _badgeManager.Init();

            GetHallOfFame.GetInstance().Load();

            _permissionManager = new PermissionManager();
            _permissionManager.Init();

            _subscriptionManager = new SubscriptionManager();
            _subscriptionManager.Init();

            TraxSoundManager.Init();
            HelperToolsManager.Init();

            _figureManager = new FigureDataManager(CloudServer.GetConfig().data["game.legacy.figure_mutant"].ToString() == "1");
            _figureManager.Init();

            _crackableManager = new CrackableManager();
            _crackableManager.Initialize(CloudServer.GetDatabaseManager().GetQueryReactor());

            _furniMaticRewardsManager = new FurniMaticRewardsManager();
            _furniMaticRewardsManager.Initialize(CloudServer.GetDatabaseManager().GetQueryReactor());

            _targetedoffersManager = new TargetedOffersManager();
            _targetedoffersManager.Initialize(CloudServer.GetDatabaseManager().GetQueryReactor());
        }
예제 #8
0
 public void setUpAll()
 {
     pm = new PermissionManager(SzpifDatabase.DataBase);
 }
예제 #9
0
파일: Game.cs 프로젝트: aromaa/Skylight
        public void Init()
        {
            using (DatabaseClient dbClient = Skylight.GetDatabaseManager().GetClient())
            {
                ServerConfiguration.LoadConfigsFromDB(dbClient);

                this.GameClientManager = new GameClientManager();

                this.NavigatorManager = new NavigatorManager();
                this.NavigatorManager.LoadPublicRooms(dbClient);
                this.NavigatorManager.LoadFlatCats(dbClient);

                this.RoomManager = new RoomManager();
                this.RoomManager.LoadRoomModels(dbClient);
                this.RoomManager.LoadNewbieRooms(dbClient);

                this.ItemManager = new ItemManager();
                this.ItemManager.LoadItems(dbClient);
                this.ItemManager.LoadSoundtracks(dbClient);
                this.ItemManager.LoadNewbieRoomItems(dbClient);

                this.CatalogManager = new CatalogManager();
                this.CatalogManager.LoadCatalogItems(dbClient);
                this.CatalogManager.LoadCatalogPages(dbClient);
                this.CatalogManager.LoadPetRaces(dbClient);
                this.CatalogManager.LoadPresents(dbClient);

                this.CatalogManager.GetMarketplaceManager().LoadMarketplaceOffers(dbClient);

                this.PermissionManager = new PermissionManager();
                this.PermissionManager.LoadRanks(dbClient);

                this.BanManager = new BanManager();
                this.BanManager.LoadBans(dbClient);

                this.ModerationToolManager = new ModerationToolManager();
                this.ModerationToolManager.LoadIssues(dbClient);
                this.ModerationToolManager.LoadPresents(dbClient);
                this.ModerationToolManager.LoadSupportTickets(dbClient);

                this.CautionManager = new CautionManager();
                this.CautionManager.LoadCauctions(dbClient);

                this.HelpManager = new HelpManager();
                this.HelpManager.LoadFAQs(dbClient);

                this.ChatlogManager = new ChatlogManager();

                this.RoomvisitManager = new RoomvisitManager();

                this.AchievementManager = new AchievementManager();
                this.AchievementManager.LoadAchievements(dbClient);

                this.BotManager = new BotManager();
                this.BotManager.LoadBots(dbClient);
                this.BotManager.LoadNewbieBotActions(dbClient);

                TextUtilies.LoadWordfilter(dbClient);

                this.QuestManager = new QuestManager();
                this.QuestManager.LoadQuests(dbClient);

                this.TalentManager = new TalentManager();
                this.TalentManager.LoadTalents(dbClient);

                this.FastFoodManager = new FastFoodManager();
                this.FastFoodManager.CreateNewConnection();

                this.UserProfileManager = new UserProfileManager();

                this.GuideManager = new GuideManager();
            }

            this.ClientPingEnabled = TextUtilies.StringToBool(Skylight.GetConfig()["client.ping.enabled"]);

            this.AutoRestartEnabled = TextUtilies.StringToBool(Skylight.GetConfig()["auto.restart.enabled"]);
            if (this.AutoRestartEnabled)
            {
                this.AutoRestartBackup         = TextUtilies.StringToBool(Skylight.GetConfig()["auto.restart.backup"]);
                this.AutoRestartBackupCompress = TextUtilies.StringToBool(Skylight.GetConfig()["auto.restart.backup.compress"]);
                this.AutoRestartTime           = DateTime.ParseExact(Skylight.GetConfig()["auto.restart.time"], "HH:mm", CultureInfo.InvariantCulture);
            }

            this.LastUpdateEmulatorStatus = Stopwatch.StartNew();
            this.LastActivityBonusesCheck = Stopwatch.StartNew();
            this.LastTimeoutCheck         = Stopwatch.StartNew();

            this.GameCycleTimer           = new System.Timers.Timer();
            this.GameCycleTimer.Elapsed  += this.GameCycle;
            this.GameCycleTimer.AutoReset = true;
            this.GameCycleTimer.Interval  = 1; //moved from 25ms, 40 times in a second to 1ms, 1000 times in second to help keep everything be in sync
            this.GameCycleTimer.Start();
            GC.KeepAlive(this.GameCycleTimer); //IK timer adds itself to the gc already, but just for sure ;P
        }
예제 #10
0
파일: Game.cs 프로젝트: aromaa/Skylight
        public void Shutdown()
        {
            //we dont wnat dispose gameclientmanager

            if (this.GameCycleTimer != null)
            {
                this.GameCycleTimer.Stop();
            }
            this.GameCycleTimer = null;

            if (this.NavigatorManager != null)
            {
                this.NavigatorManager.Shutdown();
            }
            this.NavigatorManager = null;

            if (this.RoomManager != null)
            {
                this.RoomManager.Shutdown();
            }
            this.RoomManager = null;

            if (this.ItemManager != null)
            {
                this.ItemManager.Shutdown();
            }
            this.ItemManager = null;

            if (this.CatalogManager != null)
            {
                this.CatalogManager.Shutdown();
            }
            this.CatalogManager = null;

            if (this.PermissionManager != null)
            {
                this.PermissionManager.Shutdown();
            }
            this.PermissionManager = null;

            if (this.BanManager != null)
            {
                this.BanManager.Shutdown();
            }
            this.BanManager = null;

            if (this.ModerationToolManager != null)
            {
                this.ModerationToolManager.Shutdown();
            }
            this.ModerationToolManager = null;

            if (this.CautionManager != null)
            {
                this.CautionManager.Shutdown();
            }
            this.CautionManager = null;

            if (this.HelpManager != null)
            {
                this.HelpManager.Shutdown();
            }
            this.HelpManager = null;

            if (this.ChatlogManager != null)
            {
                this.ChatlogManager.Shutdown();
            }
            this.ChatlogManager = null;

            if (this.RoomvisitManager != null)
            {
                this.RoomvisitManager.Shutdown();
            }
            this.RoomvisitManager = null;

            if (this.AchievementManager != null)
            {
                this.AchievementManager.Shutdown();
            }
            this.AchievementManager = null;
        }
예제 #11
0
        private void ExportToExcel(GridState gs, IList <IFilter> filters)
        {
            Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture;

            GridView grdProductList = new GridView();

            grdProductList.AutoGenerateColumns = false;

            BoundField bf = new BoundField();

            bf.ItemStyle.Width = Unit.Pixel(95);
            bf.DataField       = "Code";
            bf.HeaderText      = "C&oacute;digo";
            bf.HtmlEncode      = false;
            // bf.DataFormatString = "{0:00000000}";
            grdProductList.Columns.Add(bf);


            bf = new BoundField();
            bf.ItemStyle.Width           = Unit.Pixel(600);
            bf.DataField                 = "FinalInfo";
            bf.HeaderText                = "Modelo";
            bf.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            grdProductList.Columns.Add(bf);

            //si sos Admin
            ExecutePermissionValidator epv = new ExecutePermissionValidator();

            epv.ClassType     = typeof(ProductListView);
            epv.KeyIdentifier = Config.CanExportAll;
            bool canExporAll = PermissionManager.Check(epv);

            if (canExporAll)
            {
                bf = new BoundField();
                bf.ItemStyle.Width = Unit.Pixel(150);
                bf.DataField       = "Provider";
                bf.HeaderText      = "Proveedor";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width  = Unit.Pixel(50);
                bf.DataField        = "Index";
                bf.HeaderText       = "Index";
                bf.HtmlEncode       = false;
                bf.DataFormatString = "{0:F2}";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width = Unit.Pixel(70);
                bf.DataField       = "Type";
                bf.HeaderText      = "Frecuencia";
                grdProductList.Columns.Add(bf);


                bf = new BoundField();
                bf.ItemStyle.Width = Unit.Pixel(30);
                bf.DataField       = "PricePurchaseCurrency";
                bf.HeaderText      = "M. TP";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width  = Unit.Pixel(70);
                bf.DataField        = "PricePurchase";
                bf.HeaderText       = "TP";
                bf.HtmlEncode       = false;
                bf.DataFormatString = "{0:F2}";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width = Unit.Pixel(30);
                bf.DataField       = "PriceSuggestCurrency";
                bf.HeaderText      = "M. GRP";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width  = Unit.Pixel(70);
                bf.DataField        = "PriceSuggest";
                bf.HeaderText       = "GRP";
                bf.HtmlEncode       = false;
                bf.DataFormatString = "{0:F2}";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width = Unit.Pixel(30);
                bf.DataField       = "PriceListCurrency";
                bf.HeaderText      = "M. PV";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width  = Unit.Pixel(70);
                bf.DataField        = "PriceSell";
                bf.HeaderText       = "PV";
                bf.HtmlEncode       = false;
                bf.DataFormatString = "{0:F2}";
                grdProductList.Columns.Add(bf);
            }

            bf = new BoundField();
            bf.ItemStyle.Width = Unit.Pixel(10);
            bf.DataField       = "PriceListCurrency";
            bf.HeaderText      = "M. PL";
            grdProductList.Columns.Add(bf);

            bf = new BoundField();
            bf.ItemStyle.Width  = Unit.Pixel(70);
            bf.DataField        = "Price";
            bf.HeaderText       = "PL";
            bf.HtmlEncode       = false;
            bf.DataFormatString = "{0:F2}";
            grdProductList.Columns.Add(bf);

            if (canExporAll)
            {
                bf = new BoundField();
                bf.ItemStyle.Width = Unit.Pixel(30);
                bf.DataField       = "PriceListCurrency";
                bf.HeaderText      = "M. CTM";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width  = Unit.Pixel(70);
                bf.DataField        = "CTM";
                bf.HeaderText       = "CTM";
                bf.HtmlEncode       = false;
                bf.DataFormatString = "{0:F2}";
                grdProductList.Columns.Add(bf);

                bf = new BoundField();
                bf.ItemStyle.Width  = Unit.Pixel(70);
                bf.DataField        = "CTR";
                bf.HeaderText       = "CTR";
                bf.HtmlEncode       = false;
                bf.DataFormatString = "{0:F2}";
                grdProductList.Columns.Add(bf);

                //bf = new BoundField();
                //bf.ItemStyle.Width = Unit.Pixel(70);
                //bf.DataField = "Status";
                //bf.HeaderText = "Estado";
                //grdProductList.Columns.Add(bf);
            }
            //***************//



            grdProductList.DataSource = GetFiltered(gs, filters);
            grdProductList.DataBind();

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=ListadePrecios.xls"));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
            table.GridLines = grdProductList.GridLines;

            //Set the Cell format
            string codeFormat = @"<style>.cF  { mso-number-format:'\@'; }</style>";

            //  add the header row to the table
            if (grdProductList.HeaderRow != null)
            {
                PrepareControlForExport(grdProductList.HeaderRow);
                table.Rows.Add(grdProductList.HeaderRow);
                table.Rows[0].ForeColor = System.Drawing.Color.FromArgb(102, 102, 102);

                for (int i = 0; i < table.Rows[0].Cells.Count; i++)
                {
                    table.Rows[0].Cells[i].BackColor = System.Drawing.Color.FromArgb(225, 224, 224);
                }
            }

            //  add each of the data rows to the table
            foreach (GridViewRow row in grdProductList.Rows)
            {
                PrepareControlForExport(row);
                int pos = table.Rows.Add(row);

                table.Rows[pos].Cells[0].Attributes.Add("class", "cF");
                table.Rows[pos].Cells[0].HorizontalAlign  = HorizontalAlign.Right;
                table.Rows[pos].Cells[0].Width            = 95;
                table.Rows[pos].Cells[1].Width            = 600;
                table.Rows[pos].Cells[2].Width            = 110;
                table.Rows[pos].Cells[2].HorizontalAlign  = HorizontalAlign.Left;
                table.Rows[pos].Cells[4].HorizontalAlign  = HorizontalAlign.Right;
                table.Rows[pos].Cells[5].HorizontalAlign  = HorizontalAlign.Right;
                table.Rows[pos].Cells[7].HorizontalAlign  = HorizontalAlign.Right;
                table.Rows[pos].Cells[9].HorizontalAlign  = HorizontalAlign.Right;
                table.Rows[pos].Cells[11].HorizontalAlign = HorizontalAlign.Right;
                table.Rows[pos].Cells[13].HorizontalAlign = HorizontalAlign.Right;
                //Set Euro Symbol Correctly
                if (row.Cells[13].Text == "€")
                {
                    table.Rows[pos].Cells[13].Text = "&#8364";
                }
                if (canExporAll)
                {
                    if (row.Cells[5].Text == "€")
                    {
                        table.Rows[pos].Cells[5].Text = "&#8364";
                    }
                    if (row.Cells[7].Text == "€")
                    {
                        table.Rows[pos].Cells[7].Text = "&#8364";
                    }
                    if (row.Cells[9].Text == "€")
                    {
                        table.Rows[pos].Cells[9].Text = "&#8364";
                    }
                    if (row.Cells[11].Text == "€")
                    {
                        table.Rows[pos].Cells[11].Text = "&#8364";
                    }
                }
                table.Rows[pos].Cells[3].Attributes.Add("class", "pF");
                table.Rows[pos].Cells[3].Width = 110;
            }

            //  render the table into the htmlwriter
            table.RenderControl(htw);

            //  render the htmlwriter into the response adding de style

            HttpContext.Current.Response.Write(codeFormat + sw.ToString());
            HttpContext.Current.Response.End();
        }
예제 #12
0
        private ChannelTreeItem(SiteInfo siteInfo, ChannelInfo channelInfo, bool enabled, PermissionManager permissionManager)
        {
            _siteInfo          = siteInfo;
            _channelInfo       = channelInfo;
            _enabled           = enabled;
            _permissionManager = permissionManager;

            var treeDirectoryUrl = SiteServerAssets.GetIconUrl("tree");

            //为后台栏目树中的首页和外链栏目添加图标
            if (_channelInfo.ParentId == 0)
            {
                _contentModelIconClass = "ion-ios-home";
            }
            else if (_channelInfo.LinkUrl.Length != 0)
            {
                _contentModelIconClass = "ion-link";
            }
            else
            {
                _contentModelIconClass = "ion-folder";
            }

            _iconEmptyUrl = PageUtils.Combine(treeDirectoryUrl, "empty.gif");
            _iconMinusUrl = PageUtils.Combine(treeDirectoryUrl, "minus.png");
            _iconPlusUrl  = PageUtils.Combine(treeDirectoryUrl, "plus.png");
        }
예제 #13
0
 public static ChannelTreeItem CreateInstance(SiteInfo siteInfo, ChannelInfo channelInfo, bool enabled, PermissionManager permissionManager)
 {
     return(new ChannelTreeItem(siteInfo, channelInfo, enabled, permissionManager));
 }
예제 #14
0
 public UserGroupController(RoleManager roleManager, PermissionManager permissionManager, AuthorizationManager authorizationManager)
 {
     m_roleManager          = roleManager;
     m_permissionManager    = permissionManager;
     m_authorizationManager = authorizationManager;
 }
예제 #15
0
        /// <summary>
        /// 获取所有权限(该方法和上面的重复了?)
        /// </summary>
        /// <returns></returns>
        public IReadOnlyList <Permission> GetAllPermissionsNotMap()
        {
            var per = PermissionManager.GetAllPermissions();

            return(per);
        }
예제 #16
0
        private void LoadFields()
        {
            if (PriceListId != 0)
            {
                PriceList pl = ControllerManager.PriceList.GetById(PriceListId);

                //if (!MembershipManager.IsAdministrator())
                ExecutePermissionValidator epv = new ExecutePermissionValidator();
                epv.ClassType     = typeof(PriceList);
                epv.KeyIdentifier = Config.SeePriceLists;

                if (PermissionManager.Check(epv) == false)
                {
                    PermissionManager.Validate(pl);
                }
                txtName.Text        = pl.Name;
                txtDescripcion.Text = pl.Description;
                lblDiscount.Text    = pl.Discount.ToString("#0.###") + "%";

                if (pl.Type != null)
                {
                    ddlType.SelectedValue = ddlType.Items.FindByValue(pl.Type.ID.ToString()).Value;
                }
                else
                {
                    ddlType.SelectedIndex = 0;
                }

                if (pl.SaleCondition != null)
                {
                    ddlIncoterm.SelectedValue = ddlIncoterm.Items.FindByValue(pl.SaleCondition.ID.ToString()).Value;
                }
                else
                {
                    ddlIncoterm.SelectedIndex = 0;
                }

                lblStatus.Text = Resource.Business.GetString(pl.CurrentState.Status.ToString());

                if (pl.CurrentState.LastPublishedOn.HasValue)
                {
                    lblLastPubDate.Text = pl.CurrentState.LastPublishedOn.Value.ToShortDateString();
                }
                else
                {
                    lblLastPubDate.Text = "N/D";
                }

                if (pl.Frecuency != null)
                {
                    ddlFrequency.SelectedValue = ddlFrequency.Items.FindByValue(pl.Frecuency.ToString()).Value;
                }
                else
                {
                    ddlFrequency.SelectedIndex = 0;
                }

                if (pl.Currency != null)
                {
                    ddlCurrency.SelectedValue = ddlCurrency.Items.FindByValue(pl.Currency.ID.ToString()).Value;
                    lblCurrency.Text          = pl.Currency.Description;
                }
                else
                {
                    ddlCurrency.SelectedIndex = 0;
                }

                lblCountry.Text    = pl.PriceGroup.Name;
                lblCountry.Visible = true;
            }
        }
 public PermissionManageAppService(
     PermissionManager permissionManager)
 {
     _permissionManager = permissionManager;
 }
예제 #18
0
        public Task <ListResultDto <PermissionDto> > GetAllPermissions()
        {
            var permissions = PermissionManager.GetAllPermissions();

            return(Task.FromResult(new ListResultDto <PermissionDto>(permissions.MapTo <List <PermissionDto> >())));
        }
예제 #19
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsPostBack || !Page.IsValid)
            {
                return;
            }

            if (!string.IsNullOrEmpty(_theRoleName))
            {
                try
                {
                    var sitePermissionsInRolesInfoList = Session[SystemPermissionsInfoListKey] as List <SitePermissionsInfo>;

                    var generalPermissionList = ControlUtils.GetSelectedListControlValueStringList(CblPermissions);
                    DataProvider.PermissionsInRolesDao.UpdateRoleAndGeneralPermissions(_theRoleName, TbDescription.Text, generalPermissionList);

                    DataProvider.SitePermissionsDao.UpdateSitePermissions(_theRoleName, sitePermissionsInRolesInfoList);

                    PermissionManager.ClearAllCache();

                    AuthRequest.AddAdminLog("修改管理员角色", $"角色名称:{_theRoleName}");
                    SuccessMessage("角色修改成功!");
                    AddWaitAndRedirectScript(PageAdminRole.GetRedirectUrl());
                }
                catch (Exception ex)
                {
                    FailMessage(ex, "角色修改失败!");
                }
            }
            else
            {
                if (EPredefinedRoleUtils.IsPredefinedRole(TbRoleName.Text))
                {
                    FailMessage($"角色添加失败,{TbRoleName.Text}为系统角色!");
                }
                else if (DataProvider.RoleDao.IsRoleExists(TbRoleName.Text))
                {
                    FailMessage("角色添加失败,角色标识已存在!");
                }
                else
                {
                    var sitePermissionsInRolesInfoList = Session[SystemPermissionsInfoListKey] as List <SitePermissionsInfo>;
                    var generalPermissionList          = ControlUtils.GetSelectedListControlValueStringList(CblPermissions);

                    try
                    {
                        DataProvider.SitePermissionsDao.InsertRoleAndPermissions(TbRoleName.Text, AuthRequest.AdminName, TbDescription.Text, generalPermissionList, sitePermissionsInRolesInfoList);

                        PermissionManager.ClearAllCache();

                        AuthRequest.AddAdminLog("新增管理员角色",
                                                $"角色名称:{TbRoleName.Text}");

                        SuccessMessage("角色添加成功!");
                        AddWaitAndRedirectScript(PageAdminRole.GetRedirectUrl());
                    }
                    catch (Exception ex)
                    {
                        FailMessage(ex, $"角色添加失败,{ex.Message}");
                    }
                }
            }
        }
예제 #20
0
        public async Task Reload(CommandContext ctx)
        {
            await PermissionManager.GetEngine(ctx.Guild).Store.ClearCacheAsync();

            await ctx.ReplyReactionAsync(true);
        }
예제 #21
0
파일: TextUtility.cs 프로젝트: zr53722/cms
 public static bool IsEdit(SiteInfo siteInfo, int channelId, PermissionManager permissionManager)
 {
     return(permissionManager.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentEdit));
 }
예제 #22
0
        public async Task <JsonResult> Authenticate([FromBody] AuthenticateModel model)
        {   //AuthenticateResultModel
            SortedDictionary <string, object> DgDict = new SortedDictionary <string, object>();

            var loginResult = await GetLoginResultAsync(
                model.UserNameOrEmailAddress,
                model.Password,
                GetTenancyNameOrNull()
                );

            #region 角色列表版本

            DgDict.Add("permissionsToRolesVersion", 1001);

            #endregion

            #region 用户信息【暂无】

            //DgDict.Add("permissionsToRolesVersion", 1001);

            //  ////用户信息
            //  //UserAppService userAppService = new UserAppService();
            //  //var user = await userAppService.GetEntityByIdAsync( loginResult.User.Id)
            //  //.FirstOrDefaultAsync(x => x.Id == loginResult.User.Id);

            //  var user = await _userManager.GetUserByIdAsync(loginResult.User.Id);
            //  //DgDict.Add(loginResult.User.EmailAddress);
            //  //ObjectMapper.Map<User>(user);
            //  //      {
            //  //var user = await Repository.GetAllIncluding(x => x.Roles).FirstOrDefaultAsync(x => x.Id == id);



            //  DgDict.Add("CurrentLogin", Mapper.Map<CreateUserDto>(user)
            ////ObjectMapper.Map<UserDto> (loginResult.User)
            //  );

            //IList<object> DgDict = new List<object>();

            //new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles));

            //ICollection<UserRole> roles = loginResult.User.Roles;
            ////ICollection<UserRole> roles = user.Roles;
            //DgDict.Add(roles);

            //var allPermissions = PermissionManager.GetAllPermissions();

            //DgDict.Add(allPermissions);
            //var allRoles = await _roleRepository.GetAllListAsync();

            //DgDict.Add(allRoles);
            //.Roles
            //.WhereIf(
            //    !input.Permission.IsNullOrWhiteSpace(),
            //    r => r.Permissions.Any(rp => rp.Name == input.Permission && rp.IsGranted)
            //)
            //.ToListAsync();

            //return new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(roles));



            #endregion

            #region 权限列表
            var allPermissions = PermissionManager.GetAllPermissions();
            DgDict.Add("allPermissions", new ListResultDto <PermissionDto>(
                           ObjectMapper.Map <List <PermissionDto> >(allPermissions)
                           ));

            #endregion

            #region 角色列表
            var allRoles = await _roleRepository.GetAllListAsync();

            DgDict.Add("allRoles", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(allRoles)));

            //new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles));

            #endregion

            #region  是否有审核权 canAssignInspectionToOther
            bool canAssignInspectionToOther = PermissionChecker.IsGranted(PermissionNames.Pages_Inspection);
            //如果任务已经分配且未分配给自己,且不具有分配任务权限,则抛出异常
            //if (input.AssignedPersonId.Value != AbpSession.GetUserId() && !canAssignInspectionToOther)
            //{
            //    throw new AbpAuthorizationException("没有分配任务给他人的权限!");
            //}

            //var UserId = AbpSession.GetUserId();
            //DgDict.Add("UserId", UserId);

            if (!canAssignInspectionToOther)
            {
                DgDict.Add("canAssignInspectionToOther", "没有Pages_Inspection");
                DgDict.Add("canAssignInspectionToOtherValue", false);
            }
            else
            {
                DgDict.Add("canAssignInspectionToOther", "拥有Pages_Inspection");
                DgDict.Add("canAssignInspectionToOtherValue", true);
            }

            //return Json(DgDict);

            #endregion

            #region 可分配角色列表
            bool        canAssignRolesFromAdmin      = PermissionChecker.IsGranted(PermissionNames.Pages_Inspection);
            bool        canAssignRolesFromRQAdmin    = PermissionChecker.IsGranted(PermissionNames.Pages_Inspection);
            bool        canAssignRolesFromRQAssitant = PermissionChecker.IsGranted(PermissionNames.Pages_Inspection);
            List <Role> RolescanAssigned             = allRoles;

            string[] outAdmin = { "" };
            //List<Role> RolesSource = allRoles;
            //如果任务已经分配且未分配给自己,且不具有分配任务权限,则抛出异常
            if (canAssignRolesFromAdmin) //var RolesUnderYouers = allRoles;
            {
                foreach (Role item in RolescanAssigned)
                {
                    if (outAdmin.Contains(item.Name))
                    {
                        RolescanAssigned.Remove(item);
                    }  //item.SetNormalizedName in
                }
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
                //throw new AbpAuthorizationException("没有分配任务给他人的权限!");
            }
            else if (canAssignRolesFromRQAdmin)
            {
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
            }
            else if (canAssignRolesFromRQAssitant)
            {
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
            }
            else
            {
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
            }
            //    = await _roleRepository.GetAllListAsync();
            //DgDict.Add("allRoles", new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles)));
            #endregion


            #region 登录返回UserId-accessToken--EncryptedAccessToken-ExpireInSeconds

            //DgDict.Add("permissionsToRolesVersion", 1001);


            var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
            DgDict.Add("AuthenticateResultModel",
                       new AuthenticateResultModel
            {
                AccessToken          = accessToken,
                EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
                ExpireInSeconds      = (int)_configuration.Expiration.TotalSeconds,
                UserId = loginResult.User.Id
            }
                       );


            #endregion


            return(Json(DgDict));
        }
예제 #23
0
 public PermissionController(PermissionManager permissionsManager)
 {
     m_permissionManager = permissionsManager;
 }
예제 #24
0
        public async Task <JsonResult> All()
        {//AuthenticateResultModel
            SortedDictionary <string, object> DgDict = new SortedDictionary <string, object>();

            //IList<object> DgDict = new List<object>();

            #region 权限列表
            var allPermissions = PermissionManager.GetAllPermissions();
            DgDict.Add("allPermissions", new ListResultDto <PermissionDto>(
                           ObjectMapper.Map <List <PermissionDto> >(allPermissions)
                           ));

            #endregion

            #region 角色列表
            var allRoles = await _roleRepository.GetAllListAsync();

            DgDict.Add("allRoles", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(allRoles)));

            //new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles));

            #endregion

            #region 可分配角色列表
            bool        canAssignRolesFromAdmin      = PermissionChecker.IsGranted(PermissionNames.Pages_Inspection);
            bool        canAssignRolesFromRQAdmin    = PermissionChecker.IsGranted(PermissionNames.Pages_Inspection);
            bool        canAssignRolesFromRQAssitant = PermissionChecker.IsGranted(PermissionNames.Pages_Inspection);
            List <Role> RolescanAssigned             = allRoles;

            string[] outAdmin = { "" };
            //List<Role> RolesSource = allRoles;
            //如果任务已经分配且未分配给自己,且不具有分配任务权限,则抛出异常
            if (canAssignRolesFromAdmin) //var RolesUnderYouers = allRoles;
            {
                foreach (Role item in RolescanAssigned)
                {
                    if (outAdmin.Contains(item.Name))
                    {
                        RolescanAssigned.Remove(item);
                    }  //item.SetNormalizedName in
                }
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
                //throw new AbpAuthorizationException("没有分配任务给他人的权限!");
            }
            else if (canAssignRolesFromRQAdmin)
            {
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
            }
            else if (canAssignRolesFromRQAssitant)
            {
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
            }
            else
            {
                DgDict.Add("RolescanAssigned", new ListResultDto <RoleListDto>(ObjectMapper.Map <List <RoleListDto> >(RolescanAssigned)));
            }
            //    = await _roleRepository.GetAllListAsync();
            //DgDict.Add("allRoles", new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles)));
            #endregion

            #region
            #endregion


            #region
            #endregion

            #region TrafficLogDict物流状态字典
            TrafficLog[] TrafficLogDict =
            {
                new TrafficLog(0,     " 1", "2"),
                new TrafficLog(1,     " 1", "2"),
                new TrafficLog(2,     " 1", "2"),
                new TrafficLog(3,     " 1", "2"),
                new TrafficLog(4,     " 1", "2"),
                new TrafficLog(5,     " 1", "2"),
                new TrafficLog(6,     " 1", "2"),
                new TrafficLog(7,     " 1", "2"),
                new TrafficLog(10086, " 1", "2")
            };
            DgDict.Add("TrafficLogDict", TrafficLogDict);

            #endregion

            return(Json(DgDict));
        }
예제 #25
0
 /// <summary>
 /// Checks if a role is granted for a permission.
 /// </summary>
 /// <param name="roleName">The role's name to check it's permission</param>
 /// <param name="permissionName">Name of the permission</param>
 /// <returns>True, if the role has the permission</returns>
 public virtual async Task <bool> IsGrantedAsync(string roleName, string permissionName)
 {
     return(await IsGrantedAsync((await GetRoleByNameAsync(roleName)).Id,
                                 PermissionManager.GetPermission(permissionName)));
 }
예제 #26
0
        public async Task<JsonResult> Authenticate([FromBody] AuthenticateModel model)
        { 
            //AuthenticateResultModel 返回的字典类型
            SortedDictionary<string, object> DgDict = new SortedDictionary<string, object>();
            //返回登录结果
            var loginResult = await GetLoginResultAsync(
                model.UserNameOrEmailAddress,
                model.Password,
                GetTenancyNameOrNull()
            );
            AbpClaimTypes.UserId = loginResult.User.Id.ToString();
            #region 角色列表版本  暂时没用
            DgDict.Add("permissionsToRolesVersion", 1001);
            #endregion
           
            #region 获取所有权限列表
            var Permissions = PermissionManager.GetAllPermissions();
            Treelist = new List<TreeClass>();
            TreeClass treeClass1 = new TreeClass();
            treeClass1.id = 1;
            treeClass1.parentId = 0;
            treeClass1.label = Mapper.Map<PermissionDto>(Permissions.Where(x => x.Name == PermissionNames.Pages_Staff).FirstOrDefault()).DisplayName;
            treeClass1.Permission = Mapper.Map<PermissionDto>(Permissions.Where(x => x.Name == PermissionNames.Pages_Staff).FirstOrDefault());           
            Treelist = Recursion(Permissions.Where(x => x.Name == PermissionNames.Pages_Staff).FirstOrDefault(), 1);
            Treelist.Add(treeClass1);
            DgDict.Add("allPermissions", new ListResultDto<PermissionDto>(
                ObjectMapper.Map<List<PermissionDto>>(Permissions)
            ));
            try
            { 
                DgDict.Add("allPermissionsForTree", Treelist);
            }
            catch (Exception ex)
            {

            }
            num = 1;
            //权限列表
            List<Permission> allPermissions = new List<Permission>();
            foreach (var item in Permissions)
            {
                allPermissions.Add(item);
            }
            #endregion
           
            #region 角色列表
            //var allRoles = await _roleRepository.GetAllListAsync();
            var allRoleIReadOnlyList = await _roleRepository.GetAllListAsync();
            List<Role> allRoles = new List<Role>();
            foreach (var item in allRoleIReadOnlyList.Where(x=>x.IsDeleted==false).ToList())
            {
                allRoles.Add(item);
            }
            DgDict.Add("allRoles", Mapper.Map<List<RoleListDto>>(allRoles));
            //DgDict.Add("allRoles", new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles)));

            //new ListResultDto<RoleListDto>(ObjectMapper.Map<List<RoleListDto>>(allRoles));

            #endregion
            //获取登录用户的所拥有的所有权限
            var grantedPermissionNames = new List<string>();
            if (loginResult.User.Id>0)
            {
                foreach (var permissionName in allPermissions)
                {
                   Abp.UserIdentifier Identifier=UserIdentifier.Parse(loginResult.User.Id.ToString());
                    if (await PermissionChecker.IsGrantedAsync(Identifier, permissionName.Name))
                    {
                        grantedPermissionNames.Add(permissionName.Name);  // 获取当前用户的权限
                    }
                }
            }
          
            #region  是否有审核权 canAssignInspectionToOther
            bool canAssignInspectionToOther = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_Inspection);
            if (!canAssignInspectionToOther)
            {
                DgDict.Add("canAssignInspectionToOther", "没有Pages_Inspection");
                DgDict.Add("canAssignInspectionToOtherValue", false);
            }
            else
            {
                DgDict.Add("canAssignInspectionToOther", "拥有Pages_Inspection");
                DgDict.Add("canAssignInspectionToOtherValue", true);
            }
            #endregion

            bool canAssignRolesFromAdmin = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_Tenants);
            bool canAssignRolesFromRQAdmin = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_Admin);
            bool canAssignRolesFromRQAssitant = await PermissionChecker.IsGrantedAsync(UserIdentifier.Parse(loginResult.User.Id.ToString()), PermissionNames.Pages_RQAssitant);
 
            #region 可分配角色列表--针对员工管理

            List<Role> RolescanAssigned = allRoles;
            List<string> RolescanAssignedString = new List<string>();//角色名数组初始化
            foreach (var item in allRoleIReadOnlyList.Where(x => x.IsDeleted == false).ToList())
            {
                RolescanAssignedString.Add(item.Name);
            }
            //如果任务已经分配且未分配给自己,且不具有分配任务权限,则抛出异常
            if (canAssignRolesFromAdmin) 
            {
                List<Role> allmyRoles = new List<Role>();//当前用户可分配的角色 初始化
                string[] outAdmin = { "Admin"};
                foreach (var item in outAdmin)
                {
                    if (RolescanAssignedString.Contains(item))
                    {
                        RolescanAssignedString.Remove(item);
                    }  //item.SetNormalizedName in
                }
                foreach (var itemStr in RolescanAssignedString)
                {
                    foreach (var item in allRoles)
                    {
                        if (item.Name == itemStr)
                        {
                            allmyRoles.Add(item);
                        }
                    }
                }
                DgDict.Add("RolescanAssigned", Mapper.Map<List<RoleDto>>(allmyRoles));
            }
            else if (canAssignRolesFromRQAdmin)
            {
                List<Role> allmyRoles = new List<Role>();//当前用户可分配的角色 初始化
                string[] outAdmin = { "Admin","RQAdmin","RQAdminPermissions"};
                foreach (var item in outAdmin)
                {
                    if (RolescanAssignedString.Contains(item))
                    {
                        RolescanAssignedString.Remove(item);
                    }  //item.SetNormalizedName in
                }
                foreach (var itemStr in RolescanAssignedString)
                {
                    foreach (var item in allRoles)
                    {
                        if (item.Name == itemStr)
                        {
                            allmyRoles.Add(item);
                        }
                    }
                }
                DgDict.Add("RolescanAssigned", Mapper.Map<List<RoleDto>>(allmyRoles));

            }
            else if (canAssignRolesFromRQAssitant)
            {
                string[] outAdmin = { "Admin", "RQAssitantPermissions",
                    "RQAdmin" , "RQAssitant" ,"RQAdminPermissions"};
                List<Role> allmyRoles = new List<Role>();//当前用户可分配的角色 初始化
                foreach (var item in outAdmin)
                {
                    if (RolescanAssignedString.Contains(item))
                    {
                        RolescanAssignedString.Remove(item);
                    }  //item.SetNormalizedName in
                }
                foreach (var itemStr in RolescanAssignedString)
                {
                    foreach (var item in allRoles)
                    {
                        if (item.Name == itemStr)
                        {
                            allmyRoles.Add(item);
                        }
                    }
                }
                DgDict.Add("RolescanAssigned", Mapper.Map<List<RoleDto>>(allmyRoles));

            }
            else
            { 
                DgDict.Add("RolescanAssigned", null);
            }
            #endregion
            
            #region 可分配权限列表【角色管理-分配权限】
            var PermissionscanAssigned = allPermissions;
            List<string> PermissionscanAssignedString = new List<string>();
            foreach (var item in PermissionscanAssigned)
            {
                PermissionscanAssignedString.Add(item.Name);
            }

            if (canAssignRolesFromAdmin) 
            {
                DgDict.Add("PermissionscanAssigned", Mapper.Map<List<PermissionDto>>(PermissionscanAssigned));
            }
            else if (canAssignRolesFromRQAdmin)
            {
                List<Permission> allMyPermission = new List<Permission>();//当前用户可分配的权限 初始化
                string[] outAdmin = {"Pages","Pages.Tenants",
                    "Pages.Users", "Pages.Roles", "Pages.Admin",
                    "Pages.Admin.Users","Pages.Admin.Roles"
                };
                foreach (var item in outAdmin)
                {
                    if (PermissionscanAssignedString.Contains(item))
                    {
                        PermissionscanAssignedString.Remove(item);
                    }  
                }
                foreach (var itemStr in PermissionscanAssignedString)
                {
                    foreach (var item in PermissionscanAssigned)
                    {
                        if (item.Name == itemStr)
                        {
                            allMyPermission.Add(item);
                        }
                    }
                }
                DgDict.Add("PermissionscanAssigned", Mapper.Map<List<PermissionDto>>(allMyPermission));

            }
            else if (canAssignRolesFromRQAssitant)
            {
                List<Permission> allMyPermission = new List<Permission>();//当前用户可分配的权限 初始化
                string[] outAdmin = {"Pages","Pages.Tenants",
                    "Pages.Users", "Pages.Roles", "Pages.Admin",
                    "Pages.Admin.Users","Pages.Admin.Roles",
                    "Pages.RQAssitant.Roles", "Pages.RQAssitant.Users",
                    "Pages.RQAssitant"
                };
                foreach (var item in outAdmin)
                {
                    if (PermissionscanAssignedString.Contains(item))
                    {
                        PermissionscanAssignedString.Remove(item);
                    }
                }
                foreach (var itemStr in PermissionscanAssignedString)
                {
                    foreach (var item in PermissionscanAssigned)
                    {
                        if (item.Name == itemStr)
                        {
                            allMyPermission.Add(item);
                        }
                    }
                }
                DgDict.Add("PermissionscanAssigned", Mapper.Map<List<PermissionDto>>(allMyPermission));

            }
            else
            {
                DgDict.Add("PermissionscanAssigned", null);
            }

            #endregion
            
            #region 登录返回UserId-accessToken--EncryptedAccessToken-ExpireInSeconds
            var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
            DgDict.Add("AuthenticateResultModel",
                   new AuthenticateResultModel
                   {
                       AccessToken = accessToken,
                       EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
                       ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
                       UserId = loginResult.User.Id
                   }
                );
            #endregion

            return Json(DgDict);
        }
예제 #27
0
 /// <summary>
 /// Checks if a role has a permission.
 /// </summary>
 /// <param name="roleId">The role's id to check it's permission</param>
 /// <param name="permissionName">Name of the permission</param>
 /// <returns>True, if the role has the permission</returns>
 public virtual async Task <bool> IsGrantedAsync(int roleId, string permissionName)
 {
     return(await IsGrantedAsync(roleId, PermissionManager.GetPermission(permissionName)));
 }
예제 #28
0
        private void ShowPermissibleMenu(AdminUser user)
        {
            var PermMgr = new PermissionManager(Session);

            if (PermMgr.CanWorkWithCandidates || PermMgr.CanApprove)
            {
                //CandidateSearchmenu.Visible = true;
            }
            else
            {
                //CandidateSearchmenu.Visible = false;
            }
            if (PermMgr.CanWorkWithCandidates || PermMgr.CanApprove)
            {
                Candidatemenu.Visible = true;
            }
            else
            {
                Candidatemenu.Visible = false;
            }
            if (user.Role == 1 || user.Supervisor.HasValue?user.Supervisor.Value:false)
            {
                adminLnk.Visible  = true;
                admins.Visible    = true;
                AddAdmins.Visible = true;
                AddRoles.Visible  = true;
            }
            else
            {
                adminLnk.Visible  = false;
                admins.Visible    = false;
                AddAdmins.Visible = false;
                AddRoles.Visible  = false;
            }

            if (PermMgr.CanManageQuestion)
            {
                QuestionsListsmenu.Visible = true;
            }
            else
            {
                QuestionsListsmenu.Visible = false;
            }
            //if ( PermMgr.CanManageQuestion)
            //{
            //    QuestionImagemenu.Visible = true;
            //}
            //else
            //{
            //    QuestionImagemenu.Visible = false;
            //}
            if (PermMgr.CanManageQuestion)
            {
                UploadQuestions.Visible = true;
            }
            else
            {
                UploadQuestions.Visible = false;
            }
            //if ( PermMgr.CanManageQuestion)
            //{
            //    EssayQuestionsmenu.Visible = true;
            //}
            //else
            //{
            //    EssayQuestionsmenu.Visible = false;
            //}
            if (PermMgr.CanManageTestBatches)
            {
                Batchesmenu.Visible = true;
            }
            else
            {
                Batchesmenu.Visible = false;
            }
            if (PermMgr.CanManageTestBatches)
            {
                // AddCandidateToBatchmenu.Visible = true;
            }
            else
            {
                // AddCandidateToBatchmenu.Visible = false;
            }
            if (PermMgr.CanManageTestResults)
            {
                Individual.Visible = true;
            }
            else
            {
                Individual.Visible = false;
            }
            //if ( PermMgr.CanManageTestResults)
            //{
            //    PsychTestResultsmenu.Visible = true;
            //}
            //else
            //{
            //    PsychTestResultsmenu.Visible = false;
            //}
            //if (PermMgr.CanManageTestResults)
            //{
            //    BackgroundQuestResultsmenu.Visible = true;
            //}
            //else
            //{
            //    BackgroundQuestResultsmenu.Visible = false;
            //}
            if (PermMgr.CanManageTestResults)
            {
                BatchRep.Visible = true;
            }
            else
            {
                BatchRep.Visible = false;
            }
            if (PermMgr.CanManageTestBatches)
            {
                ActivateCandidateSessionmenu.Visible = true;
            }
            else
            {
                ActivateCandidateSessionmenu.Visible = false;
            }
            if (PermMgr.CanManagePortal)
            {
                notImp.Visible = true;
            }
            else
            {
                notImp.Visible = false;
            }

            if (PermMgr.CanManagePortal)
            {
                Settingsmenu.Visible = false;
            }
            else
            {
                Settingsmenu.Visible = false;
            }
        }
예제 #29
0
        public ActionResult SignIn()
        {
            string userName  = RequestString("username");
            string password  = RequestString("password");
            string checkCode = RequestString("checkcode").ToUpper();

            if (userName == "" || password == "")
            {
                return(MessageBoxAndReturn("请把表单填写完整!"));
            }

            if (ShowCode())
            {
                if (checkCode == "")
                {
                    return(MessageBoxAndReturn("请把表单填写完整!"));
                }
                if (Session["ImageCode"] == null)
                {
                    return(MessageBoxAndJump("验证码过期,请重新登录!", "/auth/login"));
                }
                if (Session["ImageCode"].ToString() != checkCode)
                {
                    return(MessageBoxAndReturn("验证码出错!"));
                }
            }

            Mng_User model = Bll.BllMng_User.CheckLogin(userName, password, Request.UserHostAddress.ToString());

            if (model == null || model.Id == 0)
            {
                //登录错误次数
                if (Session[ErrorRate] == null)
                {
                    Session.Add(ErrorRate, 1);
                }
                else
                {
                    Session[ErrorRate] = (int)Session[ErrorRate] + 1;
                    if ((int)Session[ErrorRate] == LimitTime)
                    {
                        return(Redirect("/auth/login"));
                    }
                }

                return(MessageBoxAndReturn("用户名或密码出错!"));
            }
            else
            {
                Response.Cookies[sitePreName + "AdminName"].Value   = userName;
                Response.Cookies[sitePreName + "AdminName"].Expires = DateTime.Now.AddDays(30);

                //设置Session信息
                Tools.Utility.Admin.SetSession(model.Id, model);

                //清除权限缓存
                PermissionManager.ClearPermissions();

                //清除登录次数限制
                if (Session[ErrorRate] != null)
                {
                    Session.Remove(ErrorRate);
                }

                return(Redirect("/"));
            }
        }
예제 #30
0
 public PermissionitemController(ILogger <PermissionitemController> logger, PermissionManager permissionManager)
 {
     _logger            = logger;
     _permissionManager = permissionManager;
 }
예제 #31
0
 private async Task UpdateGrantedPermissionsAsync(Role role, List <string> grantedPermissionNames)
 {
     var grantedPermissions = PermissionManager.GetPermissionsFromNamesByValidating(grantedPermissionNames);
     await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
 }
예제 #32
0
        private void InitializeUser(int uid)
        {
            using (KuanMaiEntities db = new KuanMaiEntities())
            {
                this.CurrentUser = (from u in db.User
                                    where u.User_ID == uid && u.IsSystemUser == true
                                    select new BSysUser
                                    {
                                         ID=u.User_ID,
                                         Name=u.Name,
                                         Created=(long)u.Created,
                                         Modified=(long)u.Modified,
                                         NickName=u.NickName
                                    }).FirstOrDefault<BSysUser>();

                PermissionManager pManager = new PermissionManager();

                Admin_Super adminUser=(from a in db.Admin_Super where a.user_id==this.CurrentUser.ID select a).FirstOrDefault<Admin_Super>();
                if (adminUser != null)
                {
                    this.CurrentUser.Permission = pManager.GetAllPermission();
                }
                else
                {
                    this.CurrentUser.Permission = pManager.GetUserPermission(new BUser { ID = this.CurrentUser.ID });
                }
            }
        }