public KenticoAuthorizeAttribute(bool CacheAuthenticationResults = true, bool CheckPageACL = false, string CustomUnauthorizedRedirect = null, NodePermissionsEnum NodePermissionToCheck = NodePermissionsEnum.Read, string ResourceAndPermissionNames = null, string Roles = null, bool UserAuthenticationRequired = true, string Users = null ) : base(typeof(KenticoAuthorizeFilter)) { // Build Configuration KenticoAuthorizeConfiguration Config = new KenticoAuthorizeConfiguration() { CacheAuthenticationResults = CacheAuthenticationResults, CustomUnauthorizedRedirect = CustomUnauthorizedRedirect, CheckPageACL = CheckPageACL, NodePermissionToCheck = NodePermissionToCheck, ResourceAndPermissionNames = ResourceAndPermissionNames, Roles = Roles, UserAuthenticationRequired = UserAuthenticationRequired, Users = Users }; string Serialized = JsonSerializer.Serialize(Config); Arguments = new object[] { new Claim("KenticoAuthorize", Serialized), }; }
/// <summary> /// Full configuration /// </summary> /// <param name="pageTemplateIdentifiers">Page template code names that this rule applies to, comma or semi-colon separated list</param> /// <param name="templateIdentifiersArePrefix">If true, then the given page template identifiers are treated as prefixes and any page template that starts with any of those values will have this rule apply.</param> /// <param name="pageClassNames">Page type class names that this rule applies to, , comma or semi-colon separated list</param> /// <param name="userAuthenticationRequired">If the user is required to be authenticated, true by default.</param> /// <param name="checkPageACL">If the Page's ACL security settings should be checked/enforced. false by default.</param> /// <param name="nodePermissionToCheck">What node permission to check if Page ACL is being used. Default is the Read Permission</param> /// <param name="resourceAndPermissionNames">Resource+Permisssion names, comma or semi-colon separated list (ex: "mymodule.dosomething;mymodule.doanotherthing")</param> /// <param name="customUnauthorizedRedirect">If instead of throwing the general Login or Unauthorized result, you wish to redirect to another location.</param> /// <param name="roles">Roles the user must be part of, comma or semi-colon separated list</param> /// <param name="users">Usernames of the authorized users, comma or semi-colon separated list</param> /// <param name="customAuthorization">Type of the IAuthorization inherited class that you wish to use to authorize this request. Must register this class in the services container BEFORE the services.UseAuthorization().</param> /// <param name="cacheAuthenticationResults">If the authenticated results should be cached to decrease time for re-validating on the same resources, default is true.</param> public RegisterPageBuilderAuthorizationAttribute( string pageTemplateIdentifiers = null, bool templateIdentifiersArePrefix = false, string pageClassNames = null, bool userAuthenticationRequired = true, bool checkPageACL = false, NodePermissionsEnum nodePermissionToCheck = NodePermissionsEnum.Read, string resourceAndPermissionNames = null, string customUnauthorizedRedirect = null, string roles = null, string users = null, Type customAuthorization = null, bool cacheAuthenticationResults = true ) { PageBuilderConfiguration = new PageBuilderAuthorizationConfiguration() { TemplateIdentifiersArePrefix = templateIdentifiersArePrefix }; if (!string.IsNullOrWhiteSpace(pageTemplateIdentifiers)) { PageBuilderConfiguration.PageTemplateIdentifiers = ValueToArray(pageTemplateIdentifiers); } if (!string.IsNullOrWhiteSpace(pageClassNames)) { PageBuilderConfiguration.PageClassNames = ValueToArray(pageClassNames); } AuthorizationConfiguration = new AuthorizationConfiguration { UserAuthenticationRequired = userAuthenticationRequired, CheckPageACL = checkPageACL, NodePermissionToCheck = nodePermissionToCheck, CacheAuthenticationResults = cacheAuthenticationResults }; if (!string.IsNullOrWhiteSpace(resourceAndPermissionNames)) { AuthorizationConfiguration.ResourceAndPermissionNames = ValueToArray(resourceAndPermissionNames); } if (!string.IsNullOrWhiteSpace(roles)) { AuthorizationConfiguration.Roles = ValueToArray(roles); } if (!string.IsNullOrWhiteSpace(users)) { AuthorizationConfiguration.Users = ValueToArray(users); } if (!string.IsNullOrWhiteSpace(customUnauthorizedRedirect)) { AuthorizationConfiguration.CustomUnauthorizedRedirect = customUnauthorizedRedirect; } if (customAuthorization != null) { AuthorizationConfiguration.CustomAuthorization = customAuthorization; } }
/// <summary> /// This has all the options available for you to configure. /// </summary> /// <param name="userAuthenticationRequired">If the user is required to be authenticated, true by default.</param> /// <param name="checkPageACL">If the Page's ACL security settings should be checked/enforced. false by default.</param> /// <param name="nodePermissionToCheck">What node permission to check if Page ACL is being used. Default is the Read Permission</param> /// <param name="resourceAndPermissionNames">Resource+Permisssion names, comma or semi-colon separated list (ex: "mymodule.dosomething;mymodule.doanotherthing")</param> /// <param name="customUnauthorizedRedirect">If instead of throwing the general Login or Unauthorized result, you wish to redirect to another location.</param> /// <param name="roles">Roles the user must be part of, comma or semi-colon separated list</param> /// <param name="users">Usernames of the authorized users, comma or semi-colon separated list</param> /// <param name="customAuthorization">Type of the IAuthorization inherited class that you wish to use to authorize this request. Must register this class in the services container BEFORE the services.UseAuthorization().</param> /// <param name="cacheAuthenticationResults">If the authenticated results should be cached to decrease time for re-validating on the same resources, default is true.</param> public ControllerActionAuthorizationAttribute( bool userAuthenticationRequired = true, bool checkPageACL = false, NodePermissionsEnum nodePermissionToCheck = NodePermissionsEnum.Read, string resourceAndPermissionNames = null, string customUnauthorizedRedirect = null, string roles = null, string users = null, Type customAuthorization = null, bool cacheAuthenticationResults = true ) { AuthorizationConfiguration = new AuthorizationConfiguration { UserAuthenticationRequired = userAuthenticationRequired, CheckPageACL = checkPageACL, NodePermissionToCheck = nodePermissionToCheck, CacheAuthenticationResults = cacheAuthenticationResults }; if (!string.IsNullOrWhiteSpace(resourceAndPermissionNames)) { AuthorizationConfiguration.ResourceAndPermissionNames = ValueToArray(resourceAndPermissionNames); } if (!string.IsNullOrWhiteSpace(roles)) { AuthorizationConfiguration.Roles = ValueToArray(roles); } if (!string.IsNullOrWhiteSpace(users)) { AuthorizationConfiguration.Users = ValueToArray(users); } if (!string.IsNullOrWhiteSpace(customUnauthorizedRedirect)) { AuthorizationConfiguration.CustomUnauthorizedRedirect = customUnauthorizedRedirect; } if (customAuthorization != null) { AuthorizationConfiguration.CustomAuthorization = customAuthorization; } }
/// <summary> /// Saves modified image data. /// </summary> /// <param name="name">Image name</param> /// <param name="extension">Image extension</param> /// <param name="mimetype">Image mimetype</param> /// <param name="title">Image title</param> /// <param name="description">Image description</param> /// <param name="binary">Image binary data</param> /// <param name="width">Image width</param> /// <param name="height">Image height</param> private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height) { LoadInfos(); // Save image data depending to image type switch (baseImageEditor.ImageType) { // Process attachment case ImageHelper.ImageTypeEnum.Attachment: if (ai != null) { // Save new data try { // Get the node TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree); // Check Create permission when saving temporary attachment, check Modify permission else NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create; // Check permission if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.ShowError(GetString("attach.actiondenied")); SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.ShowError(GetString("img.namenotunique")); SavingFailed = true; return; } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree); if (node != null) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(node, node.IsPublished, true); VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName); } // If extension changed update CMS.File extension if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension)) { // Update document extensions if no custom are used if (!node.DocumentUseCustomExtensions) { node.DocumentExtensions = extension; } node.SetValue("DocumentType", extension); DocumentHelper.UpdateDocument(node, baseImageEditor.Tree); } } if (ai != null) { // Test all parameters to empty values and update new value if available if (name != "") { if (!name.EndsWithCSafe(extension)) { ai.AttachmentName = name + extension; } else { ai.AttachmentName = name; } } if (extension != "") { ai.AttachmentExtension = extension; } if (mimetype != "") { ai.AttachmentMimeType = mimetype; } ai.AttachmentTitle = title; ai.AttachmentDescription = description; if (binary != null) { ai.AttachmentBinary = binary; ai.AttachmentSize = binary.Length; } if (width > 0) { ai.AttachmentImageWidth = width; } if (height > 0) { ai.AttachmentImageHeight = height; } // Ensure object ai.MakeComplete(true); if (VersionHistoryID > 0) { VersionManager.SaveAttachmentVersion(ai, VersionHistoryID); } else { AttachmentInfoProvider.SetAttachmentInfo(ai); // Log the synchronization and search task for the document if (node != null) { // Update search index for given document if (DocumentHelper.IsSearchTaskCreationAllowed(node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null)) { VersionManager.CheckIn(node, null); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { var currentUser = MembershipContext.AuthenticatedUser; if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { string physicalPath = Server.MapPath(filePath); string newPath = physicalPath; // Write binary data to the disk File.WriteAllBytes(physicalPath, binary); // Handle rename of the file if (!String.IsNullOrEmpty(name)) { newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name); } if (!String.IsNullOrEmpty(extension)) { string oldExt = Path.GetExtension(physicalPath); newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension; } // Move the file if (newPath != physicalPath) { File.Move(physicalPath, newPath); } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser)) { try { // Test all parameters to empty values and update new value if available if (name.CompareToCSafe("") != 0) { if (!name.EndsWithCSafe(extension)) { mf.MetaFileName = name + extension; } else { mf.MetaFileName = name; } } if (extension.CompareToCSafe("") != 0) { mf.MetaFileExtension = extension; } if (mimetype.CompareToCSafe("") != 0) { mf.MetaFileMimeType = mimetype; } mf.MetaFileTitle = title; mf.MetaFileDescription = description; if (binary != null) { mf.MetaFileBinary = binary; mf.MetaFileSize = binary.Length; } if (width > 0) { mf.MetaFileImageWidth = width; } if (height > 0) { mf.MetaFileImageHeight = height; } // Save new data MetaFileInfoProvider.SetMetaFileInfo(mf); if (RefreshAfterAction) { if (String.IsNullOrEmpty(externalControlID)) { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();"); } else { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID)); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; } }
/// <summary> /// Parses permission value and return true if appropriate bit is 1. /// </summary> protected bool IsPermissionTrue(int permissionValue, NodePermissionsEnum permission) { return ((permissionValue >> Convert.ToInt32(permission)) % 2) == 1; }
/// <summary> /// Returns integer value representing permission value of the given checkbox and permission name. /// </summary> protected int GetCheckBoxValue(CheckBox chkBox, NodePermissionsEnum permission) { return (chkBox.Enabled && chkBox.Checked) ? Convert.ToInt32(Math.Pow(2, Convert.ToInt32(permission))) : 0; }
/// <summary> /// Returns integer value representing permission value of the given checkbox and permission name. /// </summary> protected int GetCheckBoxValue(CMSCheckBox chkBox, NodePermissionsEnum permission) { return (chkBox.Enabled && chkBox.Checked) ? DocumentSecurityHelper.GetFlagFromPermission(permission) : 0; }
/// <summary> /// Initializes properties. /// </summary> private void InitializeAttachment() { AttachmentInfo attachmentInfo = null; if (InfoObject != null) { attachmentInfo = InfoObject as AttachmentInfo; } else { // If using workflow then get versioned attachment if (VersionHistoryID != 0) { // Get the versioned attachment with binary data AttachmentHistoryInfo attachmentHistory = VersionManager.GetAttachmentVersion(VersionHistoryID, ObjectGuid, false); if (attachmentHistory == null) { attachmentInfo = null; } else { // Create new attachment object attachmentInfo = new AttachmentInfo(attachmentHistory.Generalized.DataClass); attachmentInfo.AttachmentID = attachmentHistory.AttachmentHistoryID; } } // else get file without binary data else { attachmentInfo = AttachmentManager.GetAttachmentInfoWithoutBinary(ObjectGuid, SiteName); } InfoObject = attachmentInfo; } if (attachmentInfo != null) { // Check permissions if (CheckPermissions) { // If attachment is temporary, check 'Create' permission on parent node. Else check 'Modify' permission. NodePermissionsEnum permission = nodeIsParent ? NodePermissionsEnum.Create : NodePermissionsEnum.Modify; if (Node == null) { RedirectToInformation(GetString("editeddocument.notexists")); } if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, permission) != AuthorizationResultEnum.Allowed) { RedirectToAccessDenied(GetString("metadata.errors.filemodify")); } } // Fire event GetObjectExtension if (GetObjectExtension != null) { GetObjectExtension(attachmentInfo.AttachmentExtension); } } else { RedirectToInformation(GetString("editedobject.notexists")); } }
protected DataSet gridDocuments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { columns = SqlHelperClass.MergeColumns(DocumentHelper.GETDOCUMENTS_REQUIRED_COLUMNS, "NodeAlias, NodeGUID, DocumentName, DocumentCulture, DocumentModifiedWhen, Published, DocumentType, DocumentWorkflowStepID, DocumentCheckedOutByUserID, SiteName, NodeSiteID, NodeOwner, FileAttachment, FileDescription, DocumentName AS PublishedDocumentName, DocumentType AS PublishedDocumentType"); string whereCondition = null; // Filter group documents whereCondition = (GroupID != 0) ? SqlHelperClass.AddWhereCondition(whereCondition, "(NodeGroupID=" + GroupID + ") OR (NodeGroupID IS NULL)") : SqlHelperClass.AddWhereCondition(whereCondition, "NodeGroupID IS NULL"); // Retrieve documents DataSet documentsDataSet = DocumentHelper.GetDocuments(CurrentSite.SiteName, CMSContext.ResolveCurrentPath(LibraryPath) + "/%", null, CombineWithDefaultCulture, CMS_FILE, whereCondition, currentOrder, 1, false, currentTopN, columns, TreeProvider); NodePermissionsEnum[] permissionsToCheck = null; // Filter documents by permissions if (CheckPermissions) { documentsDataSet = TreeSecurityProvider.FilterDataSetByPermissions(documentsDataSet, NodePermissionsEnum.Read, CurrentUser); permissionsToCheck = new NodePermissionsEnum[] { NodePermissionsEnum.Modify, NodePermissionsEnum.ModifyPermissions, NodePermissionsEnum.Delete }; } else { permissionsToCheck = new NodePermissionsEnum[] { NodePermissionsEnum.Modify, NodePermissionsEnum.ModifyPermissions, NodePermissionsEnum.Delete, NodePermissionsEnum.Read }; } string cultures = PreferredCultureCode; if (CombineWithDefaultCulture) { string siteDefaultCulture = CultureHelper.GetDefaultCulture(CMSContext.CurrentSiteName); if (CMSString.Compare(siteDefaultCulture, PreferredCultureCode, true) != 0) { cultures += ";" + siteDefaultCulture; } } // Ensure permissions flags documentsDataSet = TreeSecurityProvider.FilterDataSetByPermissions(documentsDataSet, permissionsToCheck, CurrentUser, false, cultures); // Filter archived documents for users without modify permission if (!DataHelper.DataSourceIsEmpty(documentsDataSet)) { DataTable dt = documentsDataSet.Tables[0]; ArrayList deleteRows = new ArrayList(); foreach (DataRow dr in dt.Rows) { // If the document is not published and user hasn't modify permission, remove it from data set bool isPublished = ValidationHelper.GetBoolean(dr["Published"], true); string documentCulture = ValidationHelper.GetString(dr["DocumentCulture"], null); bool hasModify = TreeSecurityProvider.CheckPermission(dr, NodePermissionsEnum.Modify, documentCulture); if (!isPublished && !hasModify) { deleteRows.Add(dr); } } // Remove archived documents foreach (DataRow dr in deleteRows) { dt.Rows.Remove(dr); } } totalRecords = DataHelper.GetItemsCount(documentsDataSet); return documentsDataSet; }
/// <summary> /// Returns integer value representing permission value of the given checkbox and permission name. /// </summary> protected int GetCheckBoxValue(CheckBox chkBox, NodePermissionsEnum permission) { return((chkBox.Enabled && chkBox.Checked) ? Convert.ToInt32(Math.Pow(2, Convert.ToInt32(permission))) : 0); }
/// <summary> /// Parses permission value and return true if appropriate bit is 1. /// </summary> protected bool IsPermissionTrue(int permissionValue, NodePermissionsEnum permission) { return(((permissionValue >> Convert.ToInt32(permission)) % 2) == 1); }
/// <summary> /// Returns integer value representing permission value of the given checkbox and permission name. /// </summary> protected int GetCheckBoxValue(CMSCheckBox chkBox, NodePermissionsEnum permission) { return((chkBox.Enabled && chkBox.Checked) ? DocumentSecurityHelper.GetFlagFromPermission(permission) : 0); }
protected DataSet gridDocuments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { columns = SqlHelper.MergeColumns(DocumentHelper.GETDOCUMENTS_REQUIRED_COLUMNS, "NodeAlias, NodeGUID, DocumentName, DocumentCulture, DocumentModifiedWhen, Published, DocumentType, DocumentWorkflowStepID, DocumentCheckedOutByUserID, SiteName, NodeSiteID, NodeOwner, FileAttachment, FileDescription, DocumentName AS PublishedDocumentName, DocumentType AS PublishedDocumentType"); if (CheckPermissions) { columns = SqlHelper.MergeColumns(TreeProvider.SECURITYCHECK_REQUIRED_COLUMNS, columns); } string whereCondition = null; // Filter group documents whereCondition = (GroupID != 0) ? SqlHelper.AddWhereCondition(whereCondition, "(NodeGroupID=" + GroupID + ") OR (NodeGroupID IS NULL)") : SqlHelper.AddWhereCondition(whereCondition, "NodeGroupID IS NULL"); // Retrieve documents DataSet documentsDataSet = DocumentHelper.GetDocuments(CurrentSite.SiteName, MacroResolver.ResolveCurrentPath(LibraryPath) + "/%", null, CombineWithDefaultCulture, CMS_FILE, whereCondition, currentOrder, 1, false, currentTopN, columns, TreeProvider); NodePermissionsEnum[] permissionsToCheck = null; // Filter documents by permissions if (CheckPermissions) { documentsDataSet = TreeSecurityProvider.FilterDataSetByPermissions(documentsDataSet, NodePermissionsEnum.Read, CurrentUser); permissionsToCheck = new NodePermissionsEnum[] { NodePermissionsEnum.Modify, NodePermissionsEnum.ModifyPermissions, NodePermissionsEnum.Delete }; } string cultures = PreferredCultureCode; if (CombineWithDefaultCulture) { string siteDefaultCulture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName); if (CMSString.Compare(siteDefaultCulture, PreferredCultureCode, true) != 0) { cultures += ";" + siteDefaultCulture; } } if (CheckPermissions) { // Ensure permissions flags documentsDataSet = TreeSecurityProvider.FilterDataSetByPermissions(documentsDataSet, permissionsToCheck, CurrentUser, false, cultures); } // Filter archived documents for users without modify permission if (!DataHelper.DataSourceIsEmpty(documentsDataSet)) { DataTable dt = documentsDataSet.Tables[0]; ArrayList deleteRows = new ArrayList(); foreach (DataRow dr in dt.Rows) { // If the document is not published and user hasn't modify permission, remove it from data set bool isPublished = ValidationHelper.GetBoolean(dr["Published"], true); string documentCulture = ValidationHelper.GetString(dr["DocumentCulture"], null); bool hasModify = TreeSecurityProvider.CheckPermission(dr, NodePermissionsEnum.Modify, documentCulture); if (!isPublished && !hasModify) { deleteRows.Add(dr); } } // Remove archived documents foreach (DataRow dr in deleteRows) { dt.Rows.Remove(dr); } } totalRecords = DataHelper.GetItemsCount(documentsDataSet); return(documentsDataSet); }