Ejemplo n.º 1
0
        public static bool changeConfigFolder(Window parent, ASettings settings, string setting_name,
            string description, string error_message, Permissions required_permissions) {
            string old_path = settings.get(setting_name);
            string new_path = null;
            System.Windows.Forms.FolderBrowserDialog folderBrowser = new System.Windows.Forms.FolderBrowserDialog();
            folderBrowser.ShowNewFolderButton = true;
            folderBrowser.Description = description;
            folderBrowser.SelectedPath = old_path;
            bool try_again = false;
            do {
                if (folderBrowser.ShowDialog(GetIWin32Window(parent)) == System.Windows.Forms.DialogResult.OK) {
                    new_path = folderBrowser.SelectedPath;
                    if (PermissionsHelper.isReadable(new_path)) {
                        if (required_permissions < Permissions.Write 
                            ||PermissionsHelper.isWritable(new_path)) {

                                settings.set(setting_name, new_path);

                            return new_path != old_path;
                        } else {
                            folderBrowser.Description = error_message;
                            try_again = true;
                        }
                    } else {
                        folderBrowser.Description = error_message;
                        try_again = true;
                    }
                } else {
                    try_again = false;
                }
            } while (try_again);
            return false;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Converts Permission to string.
        /// </summary>
        /// <param name="permission">Permission to convert.</param>
        /// <returns>String describing permission.</returns>
        public static string GetString(Permissions permission)
        {
            string value = "";

            switch (permission)
            {
                case Permissions.CreateData:
                    value = "create_data";
                    break;
                case Permissions.ReadData:
                    value = "read_data";
                    break;
                case Permissions.ReadOwnData:
                    value = "read_own_data";
                    break;
                case Permissions.UpdateData:
                    value = "update_data";
                    break;
                case Permissions.UpdateOwnData:
                    value = "update_own_data";
                    break;
                case Permissions.DeleteData:
                    value = "delete_data";
                    break;
                case Permissions.DeleteOwnData:
                    value = "delete_own_data";
                    break;
            }

            return value;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Adds container-level permission to specified User API client. Requires Backend API key with Admin permission role.
        /// </summary>
        /// <param name="apiClientId">User API client id.</param>
        /// <param name="permission">User API client's permission to add.</param>
        /// <param name="projectId">Project id defining project that permission will be added to.</param>
        /// <returns>Boolen value indicating success of method.</returns>
        public Task<bool> Authorize(string apiClientId, Permissions permission, string projectId)
        {
            if(apiClientId == null || projectId == null)
                throw new ArgumentNullException();

            string permissionString = PermissionsParser.GetString(permission);
            return _syncanoClient.GetAsync("project.authorize",
                new {api_client_id = apiClientId, permission = permissionString, project_id = projectId});
        }
Ejemplo n.º 4
0
        /// <summary>Creates a new admin module attribute for an admin module.</summary>
        /// <param name="location">Location a URL should point to find module.</param>
        /// <param name="title">Title of module.</param>
        /// <param name="description">Description of module.</param>
        public PortletAdminAttribute(string location, string title, string description, Permissions permissions)
            : base(title, description, permissions)
        {
            // checks to see if location is set
            if (location == null || location.Length == 0)
                throw new ArgumentException("Location needs to be set for PortletAdminAttribute.  Cannot be String.Empty or null.", "folderName");

            this._location = location;
        }
Ejemplo n.º 5
0
		///<summary>Gets a GroupPermission based on the supplied userGroupNum and permType.  If not found, then it returns null.  Used in FormSecurity when double clicking on a dated permission or when clicking the all button.</summary>
		public static GroupPermission GetPerm(long userGroupNum,Permissions permType) {
			//No need to check RemotingRole; no call to db.
			for(int i=0;i<GroupPermissionC.List.Length;i++){
				if(GroupPermissionC.List[i].UserGroupNum==userGroupNum && GroupPermissionC.List[i].PermType==permType){
					return GroupPermissionC.List[i].Copy();
				}
			}
			return null;
		}
Ejemplo n.º 6
0
 public static string GetAuthenticationUrl(string apiKey, string sharedSecret, string frob, Permissions Permissions)
 {
     var authParams = new Dictionary<string, string>();
     authParams.Add("api_key", apiKey);
     authParams.Add("perms", "delete");
     authParams.Add("frob", frob);
     authParams.Add("api_sig", SignArguments(sharedSecret, authParams));
     return CreateUrl(Constants.AuthorizationUrl, authParams);
 }
Ejemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                this.id = base.Request.Params["id"];
                if ((this.id == null) || (this.id.Trim() == ""))
                {
                    base.Response.Redirect("treelist.aspx?TreeType=" + this.TreeType);
                    base.Response.End();
                }
                SysTree tree = new SysTree();
                SysNode node = tree.GetNode(int.Parse(this.id));
                this.lblID.Text = this.id;
                this.lblOrderid.Text = node.OrderID.ToString();
                this.lblName.Text = node.TreeText;
                if (node.ParentID == 0)
                {
                    this.lblTarget.Text = Site.lblRootDirectory;
                }
                else
                {
                    this.lblTarget.Text = tree.GetNode(node.ParentID).TreeText;
                }
                this.lblUrl.Text = node.Url;
                this.Image1.ImageUrl = node.ImageUrl;
                Permissions permissions = new Permissions();
                if (node.PermissionID == -1)
                {
                    this.lblPermission.Text = SysManage.lblPermissionText;
                }
                else
                {
                    this.lblPermission.Text = permissions.GetPermissionName(node.PermissionID);
                }
                switch (node.TreeType)
                {
                    case 0:
                        this.lblTreeType.Text = SysManage.dropBackendSystem;
                        break;

                    case 1:
                        this.lblTreeType.Text = SysManage.dropBackendEnterprise;
                        break;

                    case 2:
                        this.lblTreeType.Text = SysManage.dropBackendAgent;
                        break;

                    case 3:
                        this.lblTreeType.Text = SysManage.dropBackendUser;
                        break;
                }
                this.lblEnable.Text = node.Enabled ? SysManage.lblEnableTrue : SysManage.lblEnableFalse;
                this.lblDescription.Text = node.Comment;
            }
        }
 public ServerExplorerItem(string displayName, Guid resourceId, ResourceType resourceType,
                           IList<IExplorerItem> children, Permissions permissions, string resourcePath)
 {
     DisplayName = displayName;
     ResourceId = resourceId;
     ResourceType = resourceType;
     Children = children;
     Permissions = permissions;
     ResourcePath = resourcePath;
 }
Ejemplo n.º 9
0
 private void InjectDependencies()
 {
     this.Projects = new Projects(_httpWorker);
     this.Repositories = new Repositories(_httpWorker);
     this.Branches = new Branches(_httpWorker);
     this.Commits = new Commits(_httpWorker);
     this.PullRequests = new PullRequests(_httpWorker);
     Permissions = new Permissions(_httpWorker);
     RepoPermissions = new RepoPermissions(_httpWorker);
 }
        public IEnumerable<Person> FetchPeopleWithASpecificPermission(Permissions permission, int churchId)
        {
            var permissionInt = (int) permission;

            return from pc in Context.PersonChurches
                join pr in Context.PermissionRoles
                    on pc.RoleId equals pr.RoleId
                where pr.PermissionId == permissionInt
                    && pc.ChurchId == churchId
                select pc.Person;
        }
Ejemplo n.º 11
0
        public static bool UserHasPermission(string module, Permissions permission)
        {
            if (HttpContext.Current.Session["isAdmin"] != null)
            {
                return true;
            }

            List<ModulePermission> permissions = GetModulePermissionsFromSession();

            return permissions.Exists(e => e.Module == module && e.Permission == permission);
        }
		public List<Permission> Get(Permissions role)
		{
			var entities = new List<PermissionEntity>();

			entities = GenericRepository.GetList<PermissionEntity>(AuthAdminDatabase, PermissionsCollection);

			if (entities == null)
				return null;

			return entities.TranslateToResponse();
		}
Ejemplo n.º 13
0
 public static bool HasPermission( Permissions needed , User user )
 {
     if ( user != null )
     {
         return GetPermissions( user ) >= needed;
     }
     else
     {
         return true;
     }
 }
Ejemplo n.º 14
0
 ///<summary>PatNum can be 0.</summary>
 public static void MakeLogEntry(Permissions permType,long patNum,string logText)
 {
     //No need to check RemotingRole; no call to db.
     SecurityLog securityLog=new SecurityLog();
     securityLog.PermType=permType;
     securityLog.UserNum=Security.CurUser.UserNum;
     securityLog.LogText=logText;//"From: "+Environment.MachineName+" - "+logText;
     securityLog.CompName=Environment.MachineName;
     securityLog.PatNum=patNum;
     SecurityLogs.Insert(securityLog);
 }
Ejemplo n.º 15
0
Archivo: Security.cs Proyecto: mnisl/OD
		///<summary>Checks to see if current user is authorized.  It also checks any date restrictions.  If not authorized, it gives a Message box saying so and returns false.</summary>
		public static bool IsAuthorized(Permissions perm,DateTime date,bool suppressMessage){
			//No need to check RemotingRole; no call to db.
			if(Security.CurUser==null) {
				if(!suppressMessage) {
					MessageBox.Show(Lans.g("Security","Not authorized for")+"\r\n"+GroupPermissions.GetDesc(perm));
				}
				return false;
			}
			try {
				return IsAuthorized(perm,date,suppressMessage,curUser.UserGroupNum);
			}
			catch(Exception ex) {
				MessageBox.Show(ex.Message);
				return false;
			}
		}
Ejemplo n.º 16
0
		///<summary></summary>
		public static void RemovePermission(long groupNum,Permissions permType) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Meth.GetVoid(MethodBase.GetCurrentMethod(),groupNum,permType);
				return;
			}
			string command;
			if(permType==Permissions.SecurityAdmin){
				//need to make sure that at least one other user has this permission
				command="SELECT COUNT(*) FROM grouppermission WHERE PermType='"+POut.Long((int)permType)+"'";
				DataTable table=Db.GetTable(command);
				if(table.Rows[0][0].ToString()=="1"){//only one, so this would delete the last one.
					throw new Exception(Lans.g("FormSecurity","At least one group must have Security Admin permission."));
				}
			}
			command="DELETE from grouppermission WHERE UserGroupNum='"+POut.Long(groupNum)+"' "
				+"AND PermType='"+POut.Long((int)permType)+"'";
 			Db.NonQ(command);
		}
Ejemplo n.º 17
0
 public GARITS()
 {
     InitializeComponent();
     permissions = new Permissions();
     try
     {
         settingsFile = new SettingsFile();
         db = new Database(settingsFile.getSetting("dbserver"), settingsFile.getSetting("dbname"), settingsFile.getSetting("dbuser"), settingsFile.getSetting("dbpassword"));
         db.Connect();
         permissions.readPermissions(db);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Environment.Exit(1);
     }
     permissions.AddComponent(administrationToolStripMenuItem, "Administration Menu Item");
 }
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

              #region Security check
              currentLoggedInUserPermissions = PermissionService.Instance.GetCurrentLoggedInUserPermissions();
              if ( currentLoggedInUserPermissions == null || !currentLoggedInUserPermissions.HasPermission( StoreSpecificPermissionType.AccessSettings, store.Id ) ) {
            throw new SecurityException();
              }
              #endregion

              AddTab( CommonTerms.Common, PnCommon, SaveButton_Clicked );
              AddTab( StoreTerms.Order, PnOrder, SaveButton_Clicked );
              AddTab( StoreTerms.Product, PnProduct, SaveButton_Clicked );
              AddTab( CommonTerms.GiftCards, PnGiftCard, SaveButton_Clicked );
              AddTab( "UI", PnTemplateRendering, SaveButton_Clicked );

              PPnlName.Text = CommonTerms.Name;
              PPnlDefaultCountry.Text = StoreTerms.DefaultCountry;
              PPnlDefaultVatGroup.Text = StoreTerms.DefaultVatGroup;
              PPnlDefaultOrderStatus.Text = StoreTerms.DefaultOrderStatus;
              PPnlConfirmationEmail.Text = StoreTerms.ConfirmationEmailTemplate;
              PPnlPaymentInconsistencyEmail.Text = StoreTerms.PaymentInconsistencyEmailTemplate;
              PPnlPricesIsSpecifiedWithVat.Text = StoreTerms.PricesIsSpecifiedWithVat;
              PPnlChkPersistOrderId.Text = StoreTerms.UseCookies;
              PPnlChkOrderPersistanceTimeout.Text = StoreTerms.CookieTimeout + "<br /><small>" + StoreTerms.CookieTimeoutHelp + "</small>";

              PPnlCartNumberPrefix.Text = StoreTerms.CartNumberPrefix;
              PPnlOrderNumberPrefix.Text = StoreTerms.OrderNumberPrefix;

              PPnlProductPropertyAliases.Text = StoreTerms.ProductPropertyAliases;
              PPnlProductUniquenessPropertyAliases.Text = StoreTerms.ProductUniquenessPropertyAliases;
              PPnlStockSharingStore.Text = StoreTerms.StockSharingStore + "<br /><small>" + StoreTerms.StockSharingStoreHelp + "</small>";

              PPnlGiftCardLength.Text = StoreTerms.Length;
              PPnlGiftCardDaysValid.Text = StoreTerms.DaysValid;
              PPnlGiftCardPrefix.Text = StoreTerms.Prefix;
              PPnlGiftCardSuffix.Text = StoreTerms.Suffix;

              PPnlEditOrderUIFile.Text = StoreTerms.EditOrderUiFile;
              PPnlTemplateRendering.Text = StoreTerms.AllowedTemplateFilesForRendering + "<br /><small>" + StoreTerms.AllowedTemplateFilesForRenderingHelp + "</small>";
        }
Ejemplo n.º 19
0
		///<summary></summary>
		public static void RemovePermission(long groupNum,Permissions permType) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Meth.GetVoid(MethodBase.GetCurrentMethod(),groupNum,permType);
				return;
			}
			string command;
			if(permType==Permissions.SecurityAdmin){
				//need to make sure that at least one other user has this permission
				command="SELECT COUNT(*) FROM (SELECT DISTINCT grouppermission.UserGroupNum "
					+"FROM grouppermission "
					+"INNER JOIN userod ON userod.UserGroupNum=grouppermission.UserGroupNum AND userod.IsHidden=0 "
					+"WHERE PermType='"+POut.Long((int)permType)+"') t";//This query is Oracle compatable
				if(Db.GetScalar(command)=="1") {//only one, so this would delete the last one.
					throw new Exception(Lans.g("FormSecurity","There must always be at least one user in a user group that has the Security Admin permission."));
				}
			}
			command="DELETE from grouppermission WHERE UserGroupNum='"+POut.Long(groupNum)+"' "
				+"AND PermType='"+POut.Long((int)permType)+"'";
 			Db.NonQ(command);
		}
Ejemplo n.º 20
0
        ///// <summary>
        ///// 查询时获取对应实体的权限,适合判断GridView上面的按钮
        ///// </summary>
        ///// <param name="menuCode">实体菜单</param>
        ///// <param name="perm">权限类型</param>
        ///// <returns>权限范围</returns>
        //public static int GetPermissionValue(string menuCode, Permissions perm)
        //{

        //        //return 1;
        //        int rslt = 0;
        //        if (CurrentContext.Common.CurrentConfig.CurrentUser.PermissionInfo != null)
        //        {

        //            int permvalue = Convert.ToInt32(perm);

        //            //CurrentContext.Common.CurrentConfig.CurrentUser.PermissionInfo.ForEach(item =>
        //            //{
        //            //    System.Diagnostics.Debug.WriteLine(item.EntityMenu.MENUCODE + ":" + item.Permission.PERMISSIONNAME);
        //            //});
        //            var objs = from o in CurrentContext.Common.CurrentConfig.CurrentUser.PermissionInfo
        //                       where o.Permission.PERMISSIONVALUE == Convert.ToInt32(permvalue).ToString()
        //                       && o.EntityMenu.MENUCODE == menuCode
        //                       select o;

        //            //获取查询的权限,值越小,权限越大
        //            if (objs == null || objs.Count() <= 0)
        //                rslt = -1;
        //            else
        //                rslt = objs.Min(p => Convert.ToInt32(p.RoleMenuPermission.DATARANGE));

        //        }
        //        return rslt;


        //}

        /// <summary>
        /// 查询时获取对应实体的权限,适合判断GridView上面的按钮
        /// </summary>
        /// <param name="menuCode">实体菜单</param>
        /// <param name="perm">权限类型</param>
        /// <returns>权限范围</returns>
        public static int GetPermissionValue(string menuCode, Permissions perm)
        {
            //return 1;
            // edit liujx  将rslt=0 改为rslt=-1 有集团的权限为0 ,为最大权限
            int rslt = -1;
            try
            {
                if (CurrentContext.Common.CurrentLoginUserInfo != null)
                {
                    if (CurrentContext.Common.CurrentLoginUserInfo.PermissionInfoUI != null)
                    {

                        int permvalue = Convert.ToInt32(perm);
                        //var objs = from o in CurrentContext.Common.CurrentLoginUserInfo.PermissionInfoUI
                        //           where o.PermissionDataRange == Convert.ToInt32(permvalue).ToString()
                        //           && o.EntityMenuCode == menuCode
                        //           select o;
                        var objs = from o in CurrentContext.Common.CurrentLoginUserInfo.PermissionInfoUI
                                   where o.PermissionValue == Convert.ToInt32(permvalue).ToString()
                                   && o.MenuCode == menuCode
                                   select o;
                        //获取查询的权限,值越小,权限越大
                        if (objs == null || objs.Count() <= 0)
                        {
                            rslt = -1;
                        }
                        else
                        {
                            rslt = objs.Min(p => Convert.ToInt32(p.DataRange));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return rslt;
        }
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

              umbraco.BusinessLogic.User currentUser = umbraco.helper.GetCurrentUmbracoUser();

              #region Security check
              currentUserPermissions = PermissionService.Instance.GetCurrentLoggedInUserPermissions();
              if ( currentUserPermissions == null || !currentUserPermissions.HasPermission( GeneralPermissionType.AccessSecurity ) ) {
            throw new SecurityException();
              } else {
            bool showUser = true;

            umbraco.BusinessLogic.User user = umbraco.BusinessLogic.User.GetUser( int.Parse( HttpContext.Current.Request.QueryString[ "id" ] ) );
            showUser = !user.IsRoot(); //Don't ever show admin user

            if ( showUser ) {
              bool showAllUsers = currentUser.IsRoot() || currentUser.Applications.Any( a => a.alias == "users" );
              showUser = showAllUsers || currentUser.Id == user.Id || ( permissions != null && currentUserPermissions.StoreSpecificPermissions.Any( p => p.Value.HasFlag( StoreSpecificPermissionType.AccessStore ) && permissions.HasPermission( StoreSpecificPermissionType.AccessStore, p.Key ) ) );
            }

            if ( !showUser ) {
              throw new SecurityException();
            }
              }
              #endregion

              AddTab( CommonTerms.Common, PnlCommon, SaveButton_Clicked );

              PPnlAccessSecurity.Text = StoreTerms.Security;
              ImgAccessSecurity.ImageUrl = WebUtils.GetWebResourceUrl( Constants.TreeIcons.Lock );
              PPnlAccessLicenses.Text = DeveloperTerms.Licenses;
              ImgAccessLicenses.ImageUrl = WebUtils.GetWebResourceUrl( Constants.TreeIcons.LicenseKey );
              PPnlCreateAndDeleteStore.Text = CommonTerms.CreateAndDeleteStore;
              ImgCreateAndDeleteStore.ImageUrl = WebUtils.GetWebResourceUrl( Constants.TreeIcons.Store );

              PnStoreSpecificPermissions.Text = CommonTerms.Stores;
              PPnlStoreSpecificPermissions.Text = CommonTerms.StoreSpecificPermissions;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 查询时获取对应实体的权限,适合判断GridView上面的按钮
        /// </summary>
        /// <param name="menuCode">实体菜单</param>
        /// <param name="perm">权限类型</param>
        /// <returns>权限范围</returns>
        public static int GetPermissionValue(string menuCode, Permissions perm)
        {
            //return 1;
            // edit liujx  将rslt=0 改为rslt=-1 有集团的权限为0 ,为最大权限
            int rslt = -1;
            //if (Common.CurrentConfig.CurrentUser.PermissionInfoUI != null)
            //{

            //    int permvalue = Convert.ToInt32(perm);
                
            //    var objs = from o in Common.CurrentConfig.CurrentUser.PermissionInfoUI
            //               where o.PermissionValue == Convert.ToInt32(permvalue).ToString()
            //               && o.MenuCode == menuCode
            //               select o;
            //    //获取查询的权限,值越小,权限越大
            //    if (objs == null || objs.Count() <= 0)
            //        rslt = -1;
            //    else
            //        rslt = objs.Min(p => Convert.ToInt32(p.DataRange));

            //}
            return rslt;

        }
Ejemplo n.º 23
0
        ///<summary>Used when viewing securityLog from the security admin window.  PermTypes can be length 0 to get all types.</summary>
        public static SecurityLog[] Refresh(DateTime dateFrom,DateTime dateTo,Permissions permType,long patNum,
			long userNum)
        {
            if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
                return Meth.GetObject<SecurityLog[]>(MethodBase.GetCurrentMethod(),dateFrom,dateTo,permType,patNum,userNum);
            }
            string command="SELECT securitylog.*,LName,FName,Preferred,MiddleI FROM securitylog "
                +"LEFT JOIN patient ON patient.PatNum=securitylog.PatNum "
                +"WHERE LogDateTime >= "+POut.Date(dateFrom)+" "
                +"AND LogDateTime <= "+POut.Date(dateTo.AddDays(1));
            if(patNum !=0) {
                command+=" AND securitylog.PatNum= '"+POut.Long(patNum)+"'";
            }
            if(permType!=Permissions.None) {
                command+=" AND PermType="+POut.Long((int)permType);
            }
            if(userNum!=0) {
                command+=" AND UserNum="+POut.Long(userNum);
            }
            command+=" ORDER BY LogDateTime";
            DataTable table=Db.GetTable(command);
            List<SecurityLog> list=Crud.SecurityLogCrud.TableToList(table);
            for(int i=0;i<list.Count;i++) {
                if(table.Rows[i]["PatNum"].ToString()=="0") {
                    list[i].PatientName="";
                }
                else {
                    list[i].PatientName=table.Rows[i]["PatNum"].ToString()+"-"
                        +Patients.GetNameLF(table.Rows[i]["LName"].ToString()
                        ,table.Rows[i]["FName"].ToString()
                        ,table.Rows[i]["Preferred"].ToString()
                        ,table.Rows[i]["MiddleI"].ToString());
                }
            }
            return list.ToArray();
        }
        object Convert(Permissions requiredPermission, Permissions userPermissions)
        {
            // unauthorized icon is visible if user does not have View and Execute permissions
            var isUnauthorizedIconVisible = userPermissions == Permissions.None
                                            || !(
                                                userPermissions.HasFlag(Permissions.View) ||
                                                userPermissions.HasFlag(Permissions.Execute) ||
                                                userPermissions.HasFlag(Permissions.Contribute) ||
                                                userPermissions.HasFlag(Permissions.Administrator)
                                                );

            var visible = isUnauthorizedIconVisible;
            if(requiredPermission != Permissions.None)
            {
                // View or Execute
                visible = !isUnauthorizedIconVisible
                          && (
                              userPermissions.HasFlag(requiredPermission) ||
                              userPermissions.HasFlag(Permissions.Contribute) ||
                              userPermissions.HasFlag(Permissions.Administrator)
                              );
            }
            return visible ? Visibility.Visible : Visibility.Collapsed;
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Adds a channel permission overwrite for specified member.
 /// </summary>
 /// <param name="member"></param>
 /// <param name="allow"></param>
 /// <param name="deny"></param>
 /// <param name="reason">Reason for audit logs.</param>
 /// <returns></returns>
 public Task AddOverwriteAsync(DiscordMember member, Permissions allow = Permissions.None, Permissions deny = Permissions.None, string reason = null)
 => this.Discord.ApiClient.EditChannelPermissionsAsync(this.Id, member.Id, allow, deny, "member", reason);
Ejemplo n.º 26
0
 ///<summary>Checks to see if current user is authorized.  It also checks any date restrictions.  If not authorized, it gives a Message box saying so and returns false.</summary>
 public static bool IsAuthorized(Permissions perm, DateTime date, bool suppressMessage, bool suppressLockDateMessage)
 {
     return(IsAuthorized(perm, date, suppressMessage, suppressLockDateMessage, 0, -1, 0, 0));
 }
Ejemplo n.º 27
0
        private async void startIndexGalleryCommand(object obj)
        {
            PermissionManager permissions = new PermissionManager();
            var taskPermissionRead        = await permissions.CheckAndRequestStorageReadPermission();

            if (taskPermissionRead.HasFlag(Xamarin.Essentials.PermissionStatus.Granted))
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    var statusReadExtStorage = await Permissions.CheckStatusAsync <Permissions.StorageRead>().ConfigureAwait(false);
                    if (statusReadExtStorage != Xamarin.Essentials.PermissionStatus.Granted)
                    {
                        await Permissions.RequestAsync <Permissions.StorageRead>().ConfigureAwait(false);
                    }
                });

                ImagesCacheDbManager imagesCache     = new ImagesCacheDbManager(new ImageManager(), PeriodRouteBegin, PeriodRouteEnd);
                string           pathToDCIMDirectory = string.Empty;
                ParameterManager parameterManager    = new ParameterManager();

                if (!parameterManager.Get("CameraDirectoryFullPath", out pathToDCIMDirectory))
                {
                    pathToDCIMDirectory = imagesCache.GetPathToCameraDirectory();
                    parameterManager.Set("CameraDirectoryFullPath", pathToDCIMDirectory);
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        UserDialogs.Instance.Alert(CommonResource.AutoRoutes_WarningDefaultImagePath, CommonResource.CommonMsg_FirstStartDetected, "Ок");
                    });
                }

                PathToImageDirectory = pathToDCIMDirectory;

                await Task.Factory.StartNew(() =>
                {
                    int maxCountFilesForShowModalDialog = 20; //кол-во файлов которое считаем большим и достаточным для отображения диалога обработки
                    var listFilesForIndexing            = imagesCache.GetFilenamesForIndexing(PathToImageDirectory);
                    IsShowModalDialog     = false;
                    int countFiles        = listFilesForIndexing.Count;
                    IsGalleryIndexed      = !(countFiles > 0);
                    IsRouteMaking         = countFiles > maxCountFilesForShowModalDialog;
                    MaxCountProgressItems = countFiles;
                    attachReceiverMessagesForProgress();
                    imagesCache.UpdateFilenames(listFilesForIndexing, PathToImageDirectory);
                    detachReceiverMessagesForProgress();
                    CurrentProgressIndex = 0;
                });

                await Task.Factory.StartNew(() => {
                    _countImagesForToday   = imagesCache.GetCountImagesForDaysAgo(0, PathToImageDirectory);
                    _countImagesFor1Day    = imagesCache.GetCountImagesForDaysAgo(1, PathToImageDirectory);
                    _countImagesFor7Day    = imagesCache.GetCountImagesForDaysAgo(7, PathToImageDirectory);
                    int days               = 7300;
                    _countImagesForAllDays = imagesCache.GetCountImagesForDaysAgo(days, PathToImageDirectory);
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CountImagesForToday"));
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CountImagesFor1Day"));
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CountImagesFor7Day"));
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CountImagesForAllDays"));
                        IsRouteMaking = false;
                    });
                });

                Device.BeginInvokeOnMainThread(() =>
                {
                    MinRangeDate              = _localFileCacheManager.GetMinDate(PathToImageDirectory);
                    MaxRangeDate              = _localFileCacheManager.GetMaxDate(PathToImageDirectory);
                    IsGalleryIndexed          = true;
                    CurrentMonthChart         = DateTime.Now;
                    IsShowWarningNeedIndexing = false;
                });
            }
        }
Ejemplo n.º 28
0
        private static bool HasPermission(Context context, string schemaName)
        {
            var permission = Permissions.ForApp(Permissions.AppContentsRead, context.App.Name, schemaName);

            return(context.Permissions.Allows(permission));
        }
Ejemplo n.º 29
0
 internal void Ensure_Declared_Throws(PermissionType permission)
 {
     Assert.Throws <PermissionException>(() => Permissions.EnsureDeclared(permission));
 }
Ejemplo n.º 30
0
 internal Task Check_Status_Throws(PermissionType permission)
 {
     return(Assert.ThrowsAsync <PermissionException>(async() => await Permissions.CheckStatusAsync(permission)));
 }
Ejemplo n.º 31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Permissions.ComRedirect(Page, Permissions.redirUrl);
        Response.Cache.SetExpires(DateTime.Now.ToUniversalTime());
        Permissions.CheckManagePermission(EnumCompanyPermission.StorageProductTreeManager);

        if (!IsPostBack)
        {
            if (Request.QueryString["action"] == null || Request.QueryString["action"] == "")
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "", Transforms.ReturnAlert(GetTran("003202", "程序调用错误,请联系管理员!")));
                Response.End();
            }

            this.action = Request.QueryString["action"].Trim();
            //产品ID
            this.id         = Convert.ToInt32(Request.QueryString["id"].Trim().Replace("N", ""));
            ViewState["ID"] = this.id;


            //接收的国家编码
            if (Request.QueryString["countryCode"] != null)
            {
                ViewState["CountryCode"] = Request.QueryString["countryCode"].Trim();
                ///通过联合查询获取币种ID
                ViewState["CurrencyID"] = AddNewProductBLL.GetMoreCurrencyIDByCountryCode(ViewState["CountryCode"].ToString());
                ///初始化
                IniteCurrency(ViewState["CountryCode"].ToString());
            }

            else
            {
                //通过产品ID获取币种ID
                ViewState["CurrencyID"] = AddNewProductBLL.GetCurrencyIDByProductID(Convert.ToInt32(id));
                //通过产品ID获取国家ID
                ViewState["CountryCode"] = AddNewProductBLL.GetCountryCodeByProductID(Convert.ToInt32(id));
                IniteCurrency(ViewState["CountryCode"].ToString());
            }

            int AdStyleCount = 0, AdProductCount = 0, EdStCount = 0, DeStCount = 0, EdPrCount = 0, DePrCount = 0;

            //Check Rights
            AdStyleCount   = Permissions.GetPermissions(EnumCompanyPermission.StorageProductTreeManageAddStyle);
            AdProductCount = Permissions.GetPermissions(EnumCompanyPermission.StorageProductTreeManagerAddProduct);
            EdStCount      = Permissions.GetPermissions(EnumCompanyPermission.StorageProductTreeManagerEditStyle);
            DeStCount      = Permissions.GetPermissions(EnumCompanyPermission.StorageProductTreeManagerDeleteStyle);
            EdPrCount      = Permissions.GetPermissions(EnumCompanyPermission.StorageProductTreeManagerEditProduct);
            DePrCount      = Permissions.GetPermissions(EnumCompanyPermission.StorageProductTreeManagerDeleteProduct);

            //Add Product
            if (this.action == "add")
            {
                imgProduct.Visible = false;
                if (AdProductCount.ToString() != "2108")
                {
                    lblMessage.Text = GetTran("003207", "对不起,你没有添加产品权限!");

                    //Right No Pass
                    AddEditRightNoPass_Visible_Enable();
                    return;
                }
                this.lblMessage.Text = GetTran("003212", "当前") + ":" + GetTran("006851", "添加新品");
                lblname.Text         = GetTran("002186", "产品");
                this.pID             = this.id;
                this.editingID       = 0;
                this.addP.Checked    = true;

                //1 stand for edit image,0 stand for add image
                ViewState["imageState"] = 0;

                //Right Pass
                AddEditRightPass_Visible_Enable();
            }

            //Add ProductKind
            else if (action == "addFold")
            {
                if (AdStyleCount.ToString() != "2107")
                {
                    lblMessage.Text = GetTran("003222", "对不起,您没有添加新类权限!");

                    //No Pass
                    AddEditFoldNoPass_Visible_Enable();
                    return;
                }

                lblname.Text          = GetTran("003224", "类别");
                this.lblMessage.Text  = GetTran("003212", "当前") + ":" + GetTran("003228", "添加新类");
                this.pID              = this.id;
                this.editingID        = 0;
                this.addClass.Checked = true;
                Panel3.Visible        = false;
                //Pass
                AddEditFoldPass_Visible_Enable();

                lblclassName.Visible = true;
                //CombineProduct
                chbcombine.Visible = false;
            }
            else if (this.action == "editFold")
            {
                if (EdStCount.ToString() != "2109")
                {
                    lblMessage.Text = GetTran("003232", "对不起,您没有修改产品类权限!");

                    //No Pass
                    AddEditFoldNoPass_Visible_Enable();
                    return;
                }
                lblname.Text         = GetTran("003224", "类别");
                this.lblMessage.Text = GetTran("003212", "当前") + ":" + GetTran("003236", "编辑产品类");
                this.getItem(id, true);
                this.editingID = this.id;

                //Pass
                AddEditFoldPass_Visible_Enable();

                //CombineProduct
                chbcombine.Visible = false;
                Panel3.Visible     = false;
            }

            //Edit Product
            else if (this.action == "editItem")
            {
                imgProduct.Visible = true;
                if (EdPrCount.ToString() != "2111")
                {
                    lblMessage.Text = GetTran("003239", "对不起,您没有修改产品权限!");

                    //Right No Pass
                    AddEditRightNoPass_Visible_Enable();

                    return;
                }
                lblname.Text         = GetTran("002186", "产品");
                this.lblMessage.Text = GetTran("003212", "当前") + ":" + GetTran("003243", "编辑产品");
                this.getItem(id, false);
                this.editingID = this.id;

                //Right Pass
                AddEditRightPass_Visible_Enable();
            }

            else if (this.action == "deleteItem")
            {
                if (DePrCount.ToString() != "2112")
                {
                    lblMessage.Text = GetTran("003247", "对不起,您没有删除产品权限!");

                    //No Pass
                    DeleteRightNoPass_Visible_Enable();

                    return;
                }
                Panel3.Visible = false;
                Panel4.Visible = false;
                //No Pass
                DeleteRightNoPass_Visible_Enable();

                this.deleteItem(id);
            }

            else if (this.action == "deleteFold")
            {
                if (DeStCount.ToString() != "2110")
                {
                    lblMessage.Text = GetTran("003251", "对不起,您没有删除产品类权限!");

                    //No Pass
                    DeleteRightNoPass_Visible_Enable();
                    return;
                }
                Panel3.Visible = false;
                Panel4.Visible = false;

                //No Pass
                DeleteRightNoPass_Visible_Enable();
                this.deleteFold(id);
            }

            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "", Transforms.ReturnAlert(GetTran("003202", "程序调用错误,请联系管理员!")));
                Response.End();
            }
        }
        Translations_More();
    }
Ejemplo n.º 32
0
        public ServerPermissions(ulong id, string name)
        {
            Id = id;
            PermissionsControllerRole = "Nadeko";
            Verbose = true;

            Permissions = new Permissions(name);
            Permissions.Modules.TryAdd("NSFW", false);
            UserPermissions = new Dictionary<ulong, Permissions>();
            ChannelPermissions = new Dictionary<ulong, Permissions>();
            RolePermissions = new Dictionary<ulong, Permissions>();
            CommandCooldowns = new ConcurrentDictionary<string, int>();
            Words = new HashSet<string>();
        }
Ejemplo n.º 33
0
        internal static async Task CopyUserPermissions(User fromUser, User toUser)
        {
            var server = fromUser.Server;
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            var from = GetUserPermissionsById(server, fromUser.Id);
            if (from == null)
                serverPerms.UserPermissions.Add(fromUser.Id, from = new Permissions(fromUser.Name));
            var to = GetUserPermissionsById(server, toUser.Id);
            if (to == null)
                serverPerms.UserPermissions.Add(toUser.Id, to = new Permissions(toUser.Name));

            to.CopyFrom(from);

            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 34
0
        private static void EnsurePermission(List<Permissions> list, Permissions permissions, bool? nullable)
        {
            if (nullable == null) return;

            if (nullable == true && !list.Contains(permissions))
            {
                list.Add(permissions);
            }
        }
Ejemplo n.º 35
0
        ///<summary>Surrond with Try/Catch. Error messages will be thrown to caller.</summary>
        public static bool IsGlobalDateLock(Permissions perm, DateTime date, bool isSilent = false, long codeNum = 0, double procFee = -1, long sheetDefNum = 0)
        {
            if (!(new[] {
                Permissions.AdjustmentCreate
                , Permissions.AdjustmentEdit
                , Permissions.PaymentCreate
                , Permissions.PaymentEdit
                , Permissions.ProcComplCreate
                , Permissions.ProcComplEdit
                , Permissions.ProcExistingEdit
                //,Permissions.ProcComplEditLimited
                //,Permissions.ImageDelete
                , Permissions.InsPayCreate
                , Permissions.InsPayEdit
                //,Permissions.InsWriteOffEdit//per Nathan 7/5/2016 this should not be affected by the global date lock
                , Permissions.SheetEdit
                , Permissions.SheetDelete
                , Permissions.CommlogEdit
                //,Permissions.ClaimDelete //per Nathan 01/18/2018 this should not be affected by the global date lock
                , Permissions.PayPlanEdit
                //,Permissions.ClaimHistoryEdit //per Nathan & Mark 03/01/2018 this should not be affected by the global lock date, not financial data.
            }).Contains(perm))
            {
                return(false);               //permission being checked is not affected by global lock date.
            }
            if (date.Year == 1)
            {
                return(false);               //Invalid or MinDate passed in.
            }
            if (!PrefC.GetBool(PrefName.SecurityLockIncludesAdmin) && GroupPermissions.HasPermission(Security.CurUser, Permissions.SecurityAdmin, 0))
            {
                return(false);               //admins are never affected by global date limitation when preference is false.
            }
            if (perm.In(Permissions.ProcComplCreate, Permissions.ProcComplEdit, Permissions.ProcExistingEdit) &&
                ProcedureCodes.CanBypassLockDate(codeNum, procFee))
            {
                return(false);
            }
            if (perm.In(Permissions.SheetEdit, Permissions.SheetDelete) && sheetDefNum > 0 && SheetDefs.CanBypassLockDate(sheetDefNum))
            {
                return(false);
            }
            //If global lock is Date based.
            if (date <= PrefC.GetDate(PrefName.SecurityLockDate))
            {
                if (!isSilent)
                {
                    MessageBox.Show(Lans.g("Security", "Locked by Administrator before ") + PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString());
                }
                return(true);
            }
            //If global lock is days based.
            int lockDays = PrefC.GetInt(PrefName.SecurityLockDays);

            if (lockDays > 0 && date <= DateTime.Today.AddDays(-lockDays))
            {
                if (!isSilent)
                {
                    MessageBox.Show(Lans.g("Security", "Locked by Administrator before ") + lockDays.ToString() + " days.");
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 36
0
        ///<summary>Will throw an error if not authorized and message not suppressed.</summary>
        public static bool IsAuthorized(Permissions perm, DateTime date, bool suppressMessage, bool suppressLockDateMessage, Userod curUser,
                                        long procCodeNum, double procFee, long sheetDefNum, long fKey)
        {
            //No need to check RemotingRole; no call to db.
            date = date.Date;           //Remove the time portion of date so we can compare strictly as a date later.
            //Check eConnector permission first.
            if (IsValidEServicePermission(perm))
            {
                return(true);
            }
            if (!GroupPermissions.HasPermission(curUser, perm, fKey))
            {
                if (!suppressMessage)
                {
                    throw new Exception(Lans.g("Security", "Not authorized.") + "\r\n"
                                        + Lans.g("Security", "A user with the SecurityAdmin permission must grant you access for") + ":\r\n" + GroupPermissions.GetDesc(perm));
                }
                return(false);
            }
            if (perm == Permissions.AccountingCreate || perm == Permissions.AccountingEdit)
            {
                if (date <= PrefC.GetDate(PrefName.AccountingLockDate))
                {
                    if (!suppressMessage && !suppressLockDateMessage)
                    {
                        throw new Exception(Lans.g("Security", "Locked by Administrator."));
                    }
                    return(false);
                }
            }
            //Check the global security lock------------------------------------------------------------------------------------
            if (IsGlobalDateLock(perm, date, suppressMessage || suppressLockDateMessage, procCodeNum, procFee, sheetDefNum))
            {
                return(false);
            }
            //Check date/days limits on individual permission----------------------------------------------------------------
            if (!GroupPermissions.PermTakesDates(perm))
            {
                return(true);
            }
            //Include CEMT users, as a CEMT user could be logged in when this is checked.
            DateTime dateLimit = GetDateLimit(perm, curUser.GetGroups(true).Select(x => x.UserGroupNum).ToList());

            if (date > dateLimit)          //authorized
            {
                return(true);
            }
            //Prevents certain bugs when 1/1/1 dates are passed in and compared----------------------------------------------
            //Handling of min dates.  There might be others, but we have to handle them individually to avoid introduction of bugs.
            if (perm == Permissions.ClaimDelete ||      //older versions did not have SecDateEntry
                perm == Permissions.ClaimSentEdit ||              //no date sent was entered before setting claim received
                perm == Permissions.ProcComplEdit ||              //a completed procedure with a min date.
                perm == Permissions.ProcComplEditLimited ||              //because ProcComplEdit was in this list
                perm == Permissions.ProcExistingEdit ||              //a completed EO or EC procedure with a min date.
                perm == Permissions.InsPayEdit ||              //a claim payment with no date.
                perm == Permissions.InsWriteOffEdit ||              //older versions did not have SecDateEntry or DateEntryC
                perm == Permissions.TreatPlanEdit ||
                perm == Permissions.AdjustmentEdit ||
                perm == Permissions.CommlogEdit ||              //usually from a conversion
                perm == Permissions.ProcDelete ||              //because older versions did not set the DateEntryC.
                perm == Permissions.ImageDelete ||              //In case an image has a creation date of DateTime.MinVal.
                perm == Permissions.PerioEdit ||              //In case perio chart exam has a creation date of DateTime.MinValue.
                perm == Permissions.PreAuthSentEdit ||              //older versions did not have SecDateEntry
                perm == Permissions.ClaimProcReceivedEdit)                 //
            {
                if (date.Year < 1880 && dateLimit.Year < 1880)
                {
                    return(true);
                }
            }
            if (!suppressMessage)
            {
                throw new Exception(Lans.g("Security", "Not authorized for") + "\r\n"
                                    + GroupPermissions.GetDesc(perm) + "\r\n" + Lans.g("Security", "Date limitation"));
            }
            return(false);
        }
Ejemplo n.º 37
0
 public static bool IsAuthorized(Permissions perm, DateTime date, long procCodeNum, double procCodeFee)
 {
     return(IsAuthorized(perm, date, false, false, procCodeNum, procCodeFee, 0, 0));
 }
        private static Permissions CheckPermissionOnDir(DirectoryInfo dir)
        {
            var permissions  = new Permissions(No);
            var disSecurity  = dir.GetAccessControl(AccessControlSections.Access);
            var accessRules  = disSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));
            var poolIdentity = WindowsIdentity.GetCurrent();

            if (poolIdentity.User != null && poolIdentity.Groups != null)
            {
                foreach (FileSystemAccessRule rule in accessRules)
                {
                    if (poolIdentity.User.Value == rule.IdentityReference.Value || poolIdentity.Groups.Contains(rule.IdentityReference))
                    {
                        if ((rule.FileSystemRights & (FileSystemRights.CreateDirectories | FileSystemRights.CreateFiles)) != 0)
                        {
                            if (rule.AccessControlType == AccessControlType.Allow)
                            {
                                permissions.Create = Yes;
                            }
                            else
                            {
                                permissions.SetThenLockCreate(No);
                            }
                        }

                        if ((rule.FileSystemRights & FileSystemRights.Write) != 0)
                        {
                            if (rule.AccessControlType == AccessControlType.Allow)
                            {
                                permissions.Write = Yes;
                            }
                            else
                            {
                                permissions.SetThenLockWrite(No);
                            }
                        }

                        if ((rule.FileSystemRights & (FileSystemRights.Read | FileSystemRights.ReadData)) != 0)
                        {
                            if (rule.AccessControlType == AccessControlType.Allow)
                            {
                                permissions.Read = Yes;
                            }
                            else
                            {
                                permissions.SetThenLockRead(No);
                            }
                        }

                        if ((rule.FileSystemRights & (FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles)) != 0)
                        {
                            if (rule.AccessControlType == AccessControlType.Allow)
                            {
                                permissions.Delete = Yes;
                            }
                            else
                            {
                                permissions.SetThenLockDelete(No);
                            }
                        }
                    }
                }
            }

            return(permissions);
        }
Ejemplo n.º 39
0
        internal async Task Request(PermissionType permission, PermissionStatus expectedStatus)
        {
            var status = await Permissions.CheckStatusAsync(permission);

            Assert.Equal(expectedStatus, status);
        }
Ejemplo n.º 40
0
        public override void Render(ref XmlTree tree)
        {
            XmlTreeNode node;

            switch (CurrentNodeType)
            {
            case StoreTreeNodeType.Stores:
                #region Render tree
                Permissions permissions = PermissionService.Instance.GetCurrentLoggedInUserPermissions();

                foreach (Store store in StoreService.Instance.GetAll())
                {
                    if (permissions != null && permissions.HasPermission(StoreSpecificPermissionType.AccessStore, store.Id))
                    {
                        node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.Store, store.Id, store.Id), store.Name, Constants.TreeIcons.Store, "store", true);

                        if (permissions.HasPermission(StoreSpecificPermissionType.AccessSettings, store.Id))
                        {
                            node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditStore) + "?id=" + store.Id) + "})";
                        }

                        if (permissions.HasPermission(GeneralPermissionType.CreateAndDeleteStore))
                        {
                            node.Menu.Add(ActionDelete.Instance);
                        }
                        tree.Add(node);
                    }
                }
                #endregion
                break;

            case StoreTreeNodeType.Store:
                #region Render tree

                permissions = PermissionService.Instance.GetCurrentLoggedInUserPermissions();

                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.Orders, CurrentStoreId), CommonTerms.Orders, Constants.TreeIcons.Clipboard, "orders", true /*There is always a default order status*/);
                tree.Add(node);

                if (permissions != null && permissions.HasPermission(StoreSpecificPermissionType.AccessMarketing, CurrentStoreId))
                {
                    node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.Campaigns, CurrentStoreId), CommonTerms.Marketing, Constants.TreeIcons.Target, "campaigns", CampaignService.Instance.GetAll(CurrentStoreId).Any());
                    node.Menu.Add(ActionNew.Instance);
                    node.Menu.Add(new SortCampaignsAction());
                    node.Menu.Add(ContextMenuSeperator.Instance);
                    node.Menu.Add(ActionRefresh.Instance);
                    tree.Add(node);

                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.GiftCards, CurrentStoreId), CommonTerms.GiftCards, Constants.TreeIcons.Certificate, "giftCards");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.GiftCardOverview) + "?storeId=" + CurrentStoreId) + "})";
                    node.Menu.Add(ActionNew.Instance);
                    tree.Add(node);
                }

                if (permissions != null && permissions.HasPermission(StoreSpecificPermissionType.AccessSettings, CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.Settings, CurrentStoreId), CommonTerms.Settings, Constants.TreeIcons.Toolbox, "settings", true);
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditStore) + "?id=" + CurrentStoreId) + "})";
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.Orders:
                #region Render tree
                foreach (OrderStatus orderStatus in OrderStatusService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.OrderStatus, CurrentStoreId, orderStatus.Id), orderStatus.Name, Constants.TreeIcons.DocumentTask, "order-status");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.SearchOrders) + "?storeId=" + orderStatus.StoreId + "&orderStatusId=" + orderStatus.Id) + "})";
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.Campaigns:
                #region Render tree
                foreach (Campaign campaign in CampaignService.Instance.GetAll(CurrentStoreId))
                {
                    node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.Campaign, CurrentStoreId, campaign.Id), campaign.Name, Constants.TreeIcons.TagLabel, "campaign");

                    if (!campaign.IsActive || (campaign.StartDate != null && campaign.StartDate > DateTime.Now) || (campaign.EndDate != null && campaign.EndDate < DateTime.Now))
                    {
                        node.Style.DimNode();
                    }

                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditCampaign) + "?id=" + campaign.Id + "&storeId=" + campaign.StoreId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.Settings:
                #region Render tree
                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsOrderStatuses, CurrentStoreId), CommonTerms.OrderStatuses, Constants.TreeIcons.ClipboardTask, "settings-order-statuses", true);
                node.Menu.Add(ActionNew.Instance);
                node.Menu.Add(new SortOrderStatusesAction());
                node.Menu.Add(ContextMenuSeperator.Instance);
                node.Menu.Add(ActionRefresh.Instance);
                tree.Add(node);


                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsShippingMethods, CurrentStoreId), CommonTerms.ShippingMethods, Constants.TreeIcons.TruckBoxLabel, "settings-shipping-methods", ShippingMethodService.Instance.GetAll(CurrentStoreId).Any());
                node.Menu.Add(ActionNew.Instance);
                node.Menu.Add(new SortShippingMethodsAction());
                node.Menu.Add(ContextMenuSeperator.Instance);
                node.Menu.Add(ActionRefresh.Instance);
                tree.Add(node);

                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsPaymentMethods, CurrentStoreId), CommonTerms.PaymentMethods, Constants.TreeIcons.CreditCards, "settings-payment-methods", PaymentMethodService.Instance.GetAll(CurrentStoreId).Any());
                node.Menu.Add(ActionNew.Instance);
                node.Menu.Add(new SortPaymentMethodsAction());
                node.Menu.Add(ContextMenuSeperator.Instance);
                node.Menu.Add(ActionRefresh.Instance);
                tree.Add(node);

                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsInternationalization, CurrentStoreId), CommonTerms.Internationalization, Constants.TreeIcons.LocaleAlternate, "settings-internationalization", true);
                tree.Add(node);

                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsEmailTemplates, CurrentStoreId), CommonTerms.EmailTemplates, Constants.TreeIcons.MailStack, "settings-email-templates", EmailTemplateService.Instance.GetAll(CurrentStoreId).Any());
                node.Menu.Add(ActionNew.Instance);
                node.Menu.Add(new SortEmailTemplatesAction());
                node.Menu.Add(ContextMenuSeperator.Instance);
                node.Menu.Add(ActionRefresh.Instance);
                tree.Add(node);
                #endregion
                break;

            case StoreTreeNodeType.SettingsOrderStatuses:
                #region Render tree
                foreach (OrderStatus orderStatus in OrderStatusService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsOrderStatus, CurrentStoreId, orderStatus.Id), orderStatus.Name, Constants.TreeIcons.DocumentTask, "settings-order-status");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditOrderStatus) + "?id=" + orderStatus.Id + "&storeId=" + orderStatus.StoreId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.SettingsShippingMethods:
                #region Render tree
                foreach (ShippingMethod shippingMethod in ShippingMethodService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsShippingMethod, CurrentStoreId, shippingMethod.Id), shippingMethod.Name, Constants.TreeIcons.BoxLabel, "settings-shipping-method");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditShippingMethod) + "?id=" + shippingMethod.Id + "&storeId=" + shippingMethod.StoreId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.SettingsPaymentMethods:
                #region Render tree
                foreach (PaymentMethod paymentMethod in PaymentMethodService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsPaymentMethod, CurrentStoreId, paymentMethod.Id), paymentMethod.Name, Constants.TreeIcons.CreditCard, "settings-payment-method");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditPaymentMethod) + "?id=" + paymentMethod.Id + "&storeId=" + paymentMethod.StoreId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.SettingsInternationalization:
                #region Render tree
                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsCountries, CurrentStoreId), CommonTerms.Countries, Constants.TreeIcons.GlobeModel, "settings-countries", true /*There is always a default country*/);
                node.Menu.Add(ActionNew.Instance);
                node.Menu.Add(new CreateAllCountriesAction());
                node.Menu.Add(new SortCountriesAction());
                node.Menu.Add(ContextMenuSeperator.Instance);
                node.Menu.Add(ActionRefresh.Instance);
                tree.Add(node);

                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsCurrencies, CurrentStoreId), CommonTerms.Currencies, Constants.TreeIcons.MoneyCoin, "settings-currencies", true /*There is always a default currency*/);
                node.Menu.Add(ActionNew.Instance);
                node.Menu.Add(new SortCurrenciesAction());
                node.Menu.Add(ContextMenuSeperator.Instance);
                node.Menu.Add(ActionRefresh.Instance);
                tree.Add(node);

                node = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsVatGroups, CurrentStoreId), CommonTerms.VatGroups, Constants.TreeIcons.ZoneMoney, "settings-vat-groups", true /*There is always a default vat group*/);
                node.Menu.Add(ActionNew.Instance);
                node.Menu.Add(new SortVatGroupsAction());
                node.Menu.Add(ContextMenuSeperator.Instance);
                node.Menu.Add(ActionRefresh.Instance);
                tree.Add(node);
                #endregion
                break;

            case StoreTreeNodeType.SettingsCountries:
                #region Render tree
                foreach (Country country in CountryService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsCountry, CurrentStoreId, country.Id), country.Name, Constants.TreeIcons.Map, "settings-country", CountryRegionService.Instance.GetAll(CurrentStoreId, country.Id).Any());
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditCountry) + "?id=" + country.Id + "&storeId=" + country.StoreId) + "})";
                    node.Menu.Add(ActionNew.Instance);
                    node.Menu.Add(new SortCountryRegionsAction());
                    node.Menu.Add(ContextMenuSeperator.Instance);
                    node.Menu.Add(ActionDelete.Instance);
                    node.Menu.Add(ContextMenuSeperator.Instance);
                    node.Menu.Add(ActionRefresh.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.SettingsCountry:
                #region Render tree
                long countryId = long.Parse(NodeKey.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries)[2]);
                foreach (CountryRegion countryRegion in CountryRegionService.Instance.GetAll(CurrentStoreId, countryId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsCountryRegion, CurrentStoreId, countryRegion.Id), countryRegion.Name, Constants.TreeIcons.Map, "settings-country-region");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditCountryRegion) + "?id=" + countryRegion.Id + "&storeId=" + countryRegion.StoreId + "&countryId=" + countryId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.SettingsCurrencies:
                #region Render tree
                foreach (Currency currency in CurrencyService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsCurrency, CurrentStoreId, currency.Id), currency.Name, Constants.TreeIcons.Money, "settings-currency");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditCurrency) + "?id=" + currency.Id + "&storeId=" + currency.StoreId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.SettingsVatGroups:
                #region Render tree
                foreach (VatGroup vatGroup in VatGroupService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsVatGroup, CurrentStoreId, vatGroup.Id), vatGroup.Name, Constants.TreeIcons.Zone, "settings-vat-group");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditVatGroup) + "?id=" + vatGroup.Id + "&storeId=" + vatGroup.StoreId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;

            case StoreTreeNodeType.SettingsEmailTemplates:
                #region Render tree
                foreach (EmailTemplate emailTemplate in EmailTemplateService.Instance.GetAll(CurrentStoreId))
                {
                    node        = CreateNode(GetNodeIdentifier(StoreTreeNodeType.SettingsEmailTemplate, CurrentStoreId, emailTemplate.Id), emailTemplate.Name, Constants.TreeIcons.Mail, "settings-email-template");
                    node.Action = "javascript:(function(){" + ClientTools.Scripts.ChangeContentFrameUrl(WebUtils.GetPageUrl(Constants.Pages.EditEmailTemplate) + "?id=" + emailTemplate.Id + "&storeId=" + emailTemplate.StoreId) + "})";
                    node.Menu.Add(ActionDelete.Instance);
                    tree.Add(node);
                }
                #endregion
                break;
            }
        }
        private static HtmlBuilder NavigationMenu(
            this HtmlBuilder hb,
            Context context,
            SiteSettings ss,
            long siteId,
            string referenceType)
        {
            var canManageGroups        = context.UserSettings?.DisableGroupAdmin != true;
            var canManageSite          = siteId != 0 && context.CanManageSite(ss: ss, site: true);
            var canManageDepts         = Permissions.CanManageTenant(context: context);
            var canManageUsers         = Permissions.CanManageTenant(context: context);
            var canManageRegistrations = Permissions.CanManageRegistrations(context: context);
            var canManageTenants       = Permissions.CanManageTenant(context: context) ||
                                         context.UserSettings?.EnableManageTenant == true;
            var canManageTrashBox = CanManageTrashBox(context: context, ss: ss);

            return(hb.Ul(
                       id: "NavigationMenu",
                       action: () => hb
                       .Li(
                           action: () => hb
                           .Div(action: () => hb
                                .A(
                                    href: NewHref(context: context, ss: ss),
                                    attributes: SiteIndex(context: context, ss: ss)
                                        ? new HtmlAttributes()
                                    .OnClick("$p.templates($(this));")
                                    .DataAction("Templates")
                                    .DataMethod("post")
                                        : null,
                                    action: () => hb
                                    .Span(css: "ui-icon ui-icon-plus")
                                    .Text(text: Displays.New(context: context)))),
                           _using: ss.ReferenceType == "Sites" && context.Action == "index"
                            ? context.CanManageSite(ss: ss)
                            : context.CanCreate(ss: ss) &&
                           ss.ReferenceType != "Wikis" &&
                           context.Action != "trashbox")
                       .Li(
                           css: "sub-menu",
                           action: () => hb
                           .Div(
                               attributes: new HtmlAttributes().DataId("ViewModeMenu"),
                               action: () => hb
                               .Span(css: "ui-icon ui-icon-triangle-1-e")
                               .Text(text: Displays.View(context: context)))
                           .ViewModeMenu(context: context, ss: ss),
                           _using: Def.ViewModeDefinitionCollection
                           .Any(o => o.ReferenceType == referenceType))
                       .Li(
                           css: "sub-menu",
                           action: () => hb
                           .Div(
                               attributes: new HtmlAttributes().DataId("SettingsMenu"),
                               action: () => hb
                               .Span(css: "ui-icon ui-icon-gear")
                               .Text(text: Displays.Manage(context: context)))
                           .SettingsMenu(
                               context: context,
                               ss: ss,
                               siteId: siteId,
                               canManageSite: canManageSite,
                               canManageDepts: canManageDepts,
                               canManageGroups: canManageGroups,
                               canManageUsers: canManageUsers,
                               canManageRegistrations: canManageRegistrations,
                               canManageTenants: canManageTenants,
                               canManageTrashBox: canManageTrashBox),
                           _using:
                           canManageSite ||
                           canManageDepts ||
                           canManageGroups ||
                           canManageUsers)
                       .Li(
                           css: "sub-menu",
                           action: () => hb
                           .Div(
                               attributes: new HtmlAttributes()
                               .DataId("AccountMenu")
                               .Id("AccountUserName"),
                               action: () => hb
                               .Span(css: "ui-icon ui-icon-person")
                               .Text(text: SiteInfo.UserName(
                                         context: context,
                                         userId: context.UserId)))
                           .AccountMenu(context: context))));
        }
Ejemplo n.º 42
0
        private static bool HasPermission(Context context, ISchemaEntity schema)
        {
            var permission = Permissions.ForApp(Permissions.AppContentsRead, context.App.Name, schema.SchemaDef.Name);

            return(context.Permissions.Allows(permission));
        }
Ejemplo n.º 43
0
 internal void Ensure_Declared(PermissionType permission)
 {
     Permissions.EnsureDeclared(permission);
 }
Ejemplo n.º 44
0
        ///<summary>Will throw an error if not authorized and message not suppressed.</summary>
        public static bool IsAuthorized(Permissions perm, DateTime date, bool suppressMessage, long userGroupNum)
        {
            //No need to check RemotingRole; no call to db.
            if (!GroupPermissions.HasPermission(userGroupNum, perm))
            {
                if (!suppressMessage)
                {
                    throw new Exception(Lans.g("Security", "Not authorized for") + "\r\n" + GroupPermissions.GetDesc(perm));
                }
                return(false);
            }
            if (perm == Permissions.AccountingCreate || perm == Permissions.AccountingEdit)
            {
                if (date <= PrefC.GetDate(PrefName.AccountingLockDate))
                {
                    if (!suppressMessage)
                    {
                        throw new Exception(Lans.g("Security", "Locked by Administrator."));
                    }
                    return(false);
                }
            }
            //the list below is NOT the list of permissions that take dates. See GroupPermissions.PermTakesDates().
            if (perm == Permissions.AdjustmentCreate ||
                perm == Permissions.AdjustmentEdit ||
                perm == Permissions.PaymentCreate ||
                perm == Permissions.PaymentEdit ||
                perm == Permissions.ProcComplCreate ||
                perm == Permissions.ProcComplEdit ||
                perm == Permissions.ImageDelete ||
                perm == Permissions.InsPayCreate ||
                perm == Permissions.InsPayEdit ||
                perm == Permissions.SheetEdit ||
                perm == Permissions.CommlogEdit
                )
            {
                if (date.Year > 1 &&          //if a valid date was passed in
                    date <= PrefC.GetDate(PrefName.SecurityLockDate))                       //and that date is earlier than the lock
                {
                    if (PrefC.GetBool(PrefName.SecurityLockIncludesAdmin) ||                //if admins are locked out too
                        !GroupPermissions.HasPermission(userGroupNum, Permissions.SecurityAdmin))                          //or is not an admin
                    {
                        if (!suppressMessage)
                        {
                            throw new Exception(Lans.g("Security", "Locked by Administrator before ") + PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString());
                        }
                        return(false);
                    }
                }
                if (date.Year > 1 &&          //if a valid date was passed in
                    PrefC.GetInt(PrefName.SecurityLockDays) > 0 &&
                    date <= DateTime.Today.AddDays(-PrefC.GetInt(PrefName.SecurityLockDays)))                       //and that date is earlier than the lock
                {
                    if (PrefC.GetBool(PrefName.SecurityLockIncludesAdmin) ||                //if admins are locked out too
                        !GroupPermissions.HasPermission(userGroupNum, Permissions.SecurityAdmin))                          //or is not an admin
                    {
                        if (!suppressMessage)
                        {
                            throw new Exception(Lans.g("Security", "Locked by Administrator before ") + PrefC.GetInt(PrefName.SecurityLockDays).ToString() + " days.");
                        }
                        return(false);
                    }
                }
            }
            if (!GroupPermissions.PermTakesDates(perm))
            {
                return(true);
            }
            DateTime dateLimit = GetDateLimit(perm, userGroupNum);

            if (date > dateLimit)          //authorized
            {
                return(true);
            }
            //Handling of min dates.  There might be others, but we have to handle them individually to avoid introduction of bugs.
            if (perm == Permissions.ClaimSentEdit ||      //no date sent was entered before setting claim received
                perm == Permissions.ProcComplEdit ||              //a completed procedure with a min date.
                perm == Permissions.InsPayEdit ||              //a claim payment with no date.
                perm == Permissions.TreatPlanEdit ||
                perm == Permissions.AdjustmentEdit ||
                perm == Permissions.CommlogEdit ||              //usually from a conversion
                perm == Permissions.ProcDelete)                 //because older versions did not set the DateEntryC.
            {
                if (date.Year < 1880 && dateLimit.Year < 1880)
                {
                    return(true);
                }
            }
            if (!suppressMessage)
            {
                throw new Exception(Lans.g("Security", "Not authorized for") + "\r\n"
                                    + GroupPermissions.GetDesc(perm) + "\r\n" + Lans.g("Security", "Date limitation"));
            }
            return(false);
        }
        /// <inheritdoc />
        public async void Startup(string url, string sessionId)
        {
            if (_appState != AppState.Stopped)
            {
                Shutdown();
            }

            ServerUri      = new Uri(url, UriKind.Absolute);
            ServerAssetUri = new Uri(Regex.Replace(ServerUri.AbsoluteUri, "^ws(s?):", "http$1:"));
            SessionId      = sessionId;

            _appState = AppState.WaitingForPermission;
            OnWaitingForPermission?.Invoke();

            // download manifest
            var         manifestUri = new Uri(ServerAssetUri, "./manifest.json");
            AppManifest manifest;

            try
            {
                manifest = await AppManifest.DownloadManifest(manifestUri);
            }
            catch (Exception e)
            {
                Debug.LogErrorFormat("Error downloading MRE manifest \"{0}\":\n{1}", manifestUri, e.ToString());
                manifest = new AppManifest()
                {
                    Permissions = new Permissions[] { Permissions.UserTracking, Permissions.UserInteraction }
                };
            }

            var neededFlags = Permissions.Execution | (manifest.Permissions?.ToFlags() ?? Permissions.None);
            var wantedFlags = manifest.OptionalPermissions?.ToFlags() ?? Permissions.None;

            // set up cancel source
            if (permissionRequestCancelSource != null)
            {
                permissionRequestCancelSource.Cancel();
            }
            permissionRequestCancelSource = new CancellationTokenSource();

            // get permission to run from host app
            var grantedPerms = await MREAPI.AppsAPI.PermissionManager.PromptForPermissions(
                appLocation : ServerUri,
                permissionsNeeded : new HashSet <Permissions>(manifest.Permissions ?? new Permissions[0])
            {
                Permissions.Execution
            },
                permissionsWanted : manifest.OptionalPermissions,
                permissionFlagsNeeded : neededFlags,
                permissionFlagsWanted : wantedFlags,
                appManifest : manifest,
                cancellationToken : permissionRequestCancelSource.Token);

            // clear cancel source once we don't need it anymore
            permissionRequestCancelSource = null;

            // only use permissions that are requested, even if the user offers more
            GrantedPermissions = grantedPerms & (neededFlags | wantedFlags);

            MREAPI.AppsAPI.PermissionManager.OnPermissionDecisionsChanged += OnPermissionsUpdated;

            // make sure all needed perms are granted
            if (!GrantedPermissions.HasFlag(neededFlags))
            {
                OnPermissionDenied?.Invoke();
                Shutdown(reactivateOnPermissions: true);
                return;
            }

            _appState = AppState.Starting;

            var connection = new WebSocket();

            connection.Url = url;
            connection.Headers.Add(Constants.SessionHeader, SessionId);
            connection.Headers.Add(Constants.LegacyProtocolVersionHeader, $"{Constants.LegacyProtocolVersion}");
            connection.Headers.Add(Constants.CurrentClientVersionHeader, Constants.CurrentClientVersion);
            connection.Headers.Add(Constants.MinimumSupportedSDKVersionHeader, Constants.MinimumSupportedSDKVersion);
            connection.OnConnecting    += Conn_OnConnecting;
            connection.OnConnectFailed += Conn_OnConnectFailed;
            connection.OnConnected     += Conn_OnConnected;
            connection.OnDisconnected  += Conn_OnDisconnected;
            connection.OnError         += Connection_OnError;
            _conn = connection;
            _conn.Open();
        }
Ejemplo n.º 46
0
 /// <summary>
 /// Return true if is allowed
 /// </summary>
 /// <param name="manifest">Manifest</param>
 /// <param name="method">Method</param>
 /// <returns>Return true or false</returns>
 public bool CanCall(ContractManifest manifest, string method)
 {
     return(Permissions.Any(u => u.IsAllowed(manifest, method)));
 }
Ejemplo n.º 47
0
 public Task EditChannelPermissionsAsync(ulong channel_id, ulong overwrite_id, Permissions allow, Permissions deny, string type, string reason)
 => ApiClient.EditChannelPermissionsAsync(channel_id, overwrite_id, allow, deny, type, reason);
Ejemplo n.º 48
0
 /// <summary>
 /// Adds a channel permission overwrite for specified role.
 /// </summary>
 /// <param name="role"></param>
 /// <param name="allow"></param>
 /// <param name="deny"></param>
 /// <param name="reason">Reason for audit logs.</param>
 /// <returns></returns>
 public Task AddOverwriteAsync(DiscordRole role, Permissions allow = Permissions.None, Permissions deny = Permissions.None, string reason = null)
 => this.Discord.ApiClient.EditChannelPermissionsAsync(this.Id, role.Id, allow, deny, "role", reason);
Ejemplo n.º 49
0
 ///<summary>Checks to see if current user is authorized.  It also checks any date restrictions.  If not authorized, it gives a Message box saying so and returns false.</summary>
 public static bool IsAuthorized(Permissions perm, DateTime date)
 {
     //No need to check RemotingRole; no call to db.
     return(IsAuthorized(perm, date, false));
 }
        public static async Task RequestStoragePermission()
        {
            await Permissions.RequestAsync <Permissions.StorageRead>();

            await Permissions.RequestAsync <Permissions.StorageWrite>();
        }
Ejemplo n.º 51
0
 public SecurityResult(Permissions level)
 {
     Code        = HttpStatusCode.OK;
     Message     = string.Empty;
     Permissions = level;
 }
Ejemplo n.º 52
0
 ///<summary>Checks to see if current user is authorized.  It also checks any date restrictions.  If not authorized, it gives a Message box saying so and returns false.</summary>
 public static bool IsAuthorized(Permissions perm, bool suppressMessage)
 {
     //No need to check RemotingRole; no call to db.
     return(IsAuthorized(perm, DateTime.MinValue, suppressMessage));
 }
Ejemplo n.º 53
0
 ///<summary>Returns the Date that the user is restricted to for the passed-in PermType.
 ///Returns MinVal if the user is not restricted or does not have the permission.</summary>
 private static DateTime GetDateLimit(Permissions permType, List <long> listUserGroupNums)
 {
     //No need to check RemotingRole; no call to db.
     return(GroupPermissions.GetDateRestrictedForPermission(permType, listUserGroupNums));
 }
Ejemplo n.º 54
0
 public HasPermissionAttribute(Permissions permission) : base(permission.ToString())
 {
 }
Ejemplo n.º 55
0
        internal static async Task CopyChannelPermissions(Channel fromChannel, Channel toChannel)
        {
            var server = fromChannel.Server;
            var serverPerms = PermissionsDict.GetOrAdd(server.Id,
                new ServerPermissions(server.Id, server.Name));

            var from = GetChannelPermissionsById(server, fromChannel.Id);
            if (from == null)
                serverPerms.ChannelPermissions.Add(fromChannel.Id, from = new Permissions(fromChannel.Name));
            var to = GetChannelPermissionsById(server, toChannel.Id);
            if (to == null)
                serverPerms.ChannelPermissions.Add(toChannel.Id, to = new Permissions(toChannel.Name));

            to.CopyFrom(from);

            await WriteServerToJson(serverPerms).ConfigureAwait(false);
        }
Ejemplo n.º 56
0
 public virtual bool HasStockPermission()
 {
     return(Permissions.Any(r => r.Name.Match("STCK")));
 }
Ejemplo n.º 57
0
 public void CopyFrom(Permissions other)
 {
     Modules.Clear();
     foreach (var mp in other.Modules)
         Modules.AddOrUpdate(mp.Key, mp.Value, (s, b) => mp.Value);
     Commands.Clear();
     foreach (var cp in other.Commands)
         Commands.AddOrUpdate(cp.Key, cp.Value, (s, b) => cp.Value);
     FilterInvites = other.FilterInvites;
     FilterWords = other.FilterWords;
 }
Ejemplo n.º 58
0
 public virtual bool HasCashPermission()
 {
     return(Permissions.Any(r => r.Name.Match("CASH")));
 }
Ejemplo n.º 59
0
 public PermissionStruct(Permissions userPermissions, Permissions pageRestrictionsMask, Permissions pageGrantPermissions) {
     UserPermissions = userPermissions;
     PageRestrictionsMask = pageRestrictionsMask;
     PageGrantPermissions = pageGrantPermissions;
 }
Ejemplo n.º 60
0
 public virtual bool HasOrderPermission()
 {
     // пользователь имеет право работать с заказами, если это право ему было дано явно,
     // либо по умолчанию, если права он ещё не получал
     return(Permissions.Any(r => r.Name.Match("ORDR")) || !Permissions.Any(r => r.Name.Match("STCK") || r.Name.Match("CASH")));
 }