/// <summary> /// Throws a <see cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException" /> if the user belonging to the /// specified <paramref name="roles" /> does not have at least one of the requested permissions for the specified album. /// </summary> /// <param name="securityRequest">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful when the user has permission for at least one of the actions.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated"/>=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies.</param> /// <param name="galleryId">The ID for the gallery the user is requesting permission in. The <paramref name="albumId" /> must exist in /// this gallery. This parameter is not required <paramref name="securityRequest" /> is SecurityActions.AdministerSite (you can specify /// <see cref="int.MinValue" />).</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged in. If true, the /// <paramref name="roles"/> parameter must be given the names of the roles for the current user. If /// <paramref name="isAuthenticated"/>=true and the <paramref name="roles"/> parameter /// is either null or an empty collection, this method thows a <see cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException" /> exception.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <remarks>This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated"/>=true, the <paramref name="isPrivateAlbum"/> parameter is /// ignored. When it is false, the <paramref name="roles"/> parameter is ignored.</remarks> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Throw when the user does not have at least /// one of the requested permissions to the specified album.</exception> public static void ThrowIfUserNotAuthorized(SecurityActions securityRequest, IGalleryServerRoleCollection roles, int albumId, int galleryId, bool isAuthenticated, bool isPrivateAlbum) { if (!(IsUserAuthorized(securityRequest, roles, albumId, galleryId, isAuthenticated, isPrivateAlbum, SecurityActionsOption.RequireOne))) { throw new ErrorHandler.CustomExceptions.GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "You do not have permission '{0}' for album ID {1}.", securityRequest.ToString(), albumId)); } }
public void PurgeCache(int albumId) { IAlbum album = null; try { album = AlbumController.LoadAlbumInstance(albumId, false); // Get a list of all actions that require purging the cache. User must have one of these // permissions in order to purge the cache. const SecurityActions securityActions = SecurityActions.AddChildAlbum | SecurityActions.EditAlbum | SecurityActions.DeleteChildAlbum | SecurityActions.AddMediaObject | SecurityActions.EditMediaObject | SecurityActions.DeleteMediaObject; if (Utils.IsUserAuthorized(securityActions, albumId, album.GalleryId, album.IsPrivate)) { HelperFunctions.PurgeCache(); } } catch (Exception ex) { if (album != null) { AppErrorController.LogError(ex, album.GalleryId); } else { AppErrorController.LogError(ex); } } }
/// <summary> /// Throws a <see cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException" /> if the user does not have the appropriate /// permission for the specified album. /// </summary> /// <param name="securityRequest">The requested permissions.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated"/>=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies.</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged in. If true, the /// <paramref name="roles"/> parameter must be given the names of the roles for the current user. If /// <paramref name="isAuthenticated"/>=true and the <paramref name="roles"/> parameter /// is either null or an empty collection, this method thows a <see cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException" /> exception.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <remarks>This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated"/>=true, the <paramref name="isPrivateAlbum"/> parameter is /// ignored. When it is false, the <paramref name="roles"/> parameter is ignored.</remarks> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Throw when the user does not have /// permission to the requested album.</exception> public static void ThrowIfUserNotAuthorized(SecurityActions securityRequest, IGalleryServerRoleCollection roles, int albumId, bool isAuthenticated, bool isPrivateAlbum) { if (!(IsUserAuthorized(securityRequest, roles, albumId, isAuthenticated, isPrivateAlbum))) { throw new GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "You do not have permission '{0}' for album ID {1}.", securityRequest.ToString(), albumId)); } }
/// <summary> /// Determine if the user has the appropriate permission for the specified album. The user may be anonymous or logged on. /// When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), this method determines whether the user is authorized by /// validating that at least one role has the requested permission to the specified album. When the user is anonymous, /// the <paramref name="roles"/> parameter is ignored and instead the <paramref name="isPrivateAlbum"/> parameter is used. /// Anonymous users do not have any access to private albums. When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), /// the <paramref name="roles"/> parameter must contain the roles belonging to the user. /// </summary> /// <param name="securityRequests">The requested permissions.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated"/>=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies.</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged on. If true, the /// <paramref name="roles"/> parameter should contain the names of the roles for the current user. If <paramref name="isAuthenticated"/>=true /// and the <paramref name="roles"/> parameter is either null or an empty collection, this method returns false.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <returns>Returns true if the user has the requested permission; returns false if not.</returns> /// <remarks>This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated"/>=true, the /// <paramref name="isPrivateAlbum"/> parameter is ignored. When it is false, the roles parameter is ignored.</remarks> public static bool IsUserAuthorized(SecurityActions securityRequests, IGalleryServerRoleCollection roles, int albumId, bool isAuthenticated, bool isPrivateAlbum) { #region Validation if (isAuthenticated && ((roles == null) || (roles.Count == 0))) { return(false); } #endregion // Handle anonymous users. if (!isAuthenticated) { return(IsAnonymousUserAuthorized(securityRequests, isPrivateAlbum)); } // If we get here we are dealing with an authenticated (logged on) user. Authorization for authenticated users is // given if the user is a member of at least one role that provides permission. if (SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests)) { // Iterate through each GalleryServerRole. If at least one allows the action, return true. Note that the // AdministerSite security action, if granted, applies to all albums and allows all actions (except HideWatermark). foreach (IGalleryServerRole role in roles) { if (IsAuthenticatedUserAuthorized(securityRequests, role, albumId)) { return(true); } } return(false); } else { // There are multiple security actions in securityRequest enum. User is authorized only if EVERY security request // is authorized. foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests)) { // Iterate through each GalleryServerRole. If at least role allows the action, return true. Note that the // AdministerSite security action, if granted, applies to all albums and allows all actions (except HideWatermark). bool securityActionIsAuthorized = false; foreach (IGalleryServerRole role in roles) { if (IsAuthenticatedUserAuthorized(securityAction, role, albumId)) { securityActionIsAuthorized = true; break; } } if (!securityActionIsAuthorized) { return(false); } } // If we get to this point then every security request has been authorized, so we can authorize the entire request. return(true); } }
/// <summary> /// Extract information from the query string and assign to our class level variables. Return false if something goes wrong /// and the variables cannot be set. This will happen when the query string is in an unexpected format. /// </summary> /// <param name="queryString">The query string for the current request. Can be populated with HttpContext.Request.Url.Query.</param> /// <returns>Returns true if all relevant variables were assigned from the query string; returns false if there was a problem.</returns> private bool ExtractQueryStringParms(string queryString) { if (String.IsNullOrEmpty(queryString)) { return(false); } if (queryString.StartsWith("?", StringComparison.Ordinal)) { queryString = queryString.Remove(0, 1); } //aid={0}&secaction={1} foreach (string nameValuePair in queryString.Split(new char[] { '&' })) { string[] nameOrValue = nameValuePair.Split(new char[] { '=' }); switch (nameOrValue[0]) { case "aid": { int aid; if (Int32.TryParse(nameOrValue[1], out aid)) { _albumId = aid; } else { return(false); } break; } case "secaction": { int secActionInt; if (Int32.TryParse(nameOrValue[1], out secActionInt)) { if (SecurityActionEnumHelper.IsValidSecurityAction((SecurityActions)secActionInt)) { _securityAction = (SecurityActions)secActionInt; break; } else { return(false); } } else { return(false); } } default: return(false); // Unexpected query string parm. Return false so execution is aborted. } } return(true); }
private void ShowTreeview() { rptr.Visible = false; tvUC.Visible = true; // Find out if the objects we are transferring consist of only media objects, only albums, or both. // We use this knowledge to set the RequiredSecurityPermission property on the treeview user control // so that only albums where the user has permission are available for selection. bool hasAlbums = false; bool hasMediaObjects = false; SecurityActions securityActions = 0; foreach (string id in (string[])ViewState["ids"]) { if (id.StartsWith("a", StringComparison.Ordinal)) { securityActions = (((int)securityActions == 0) ? SecurityActions.AddChildAlbum : securityActions | SecurityActions.AddChildAlbum); hasAlbums = true; } if (id.StartsWith("m", StringComparison.Ordinal)) { securityActions = (((int)securityActions == 0) ? SecurityActions.AddMediaObject : securityActions | SecurityActions.AddMediaObject); hasMediaObjects = true; } if (hasAlbums && hasMediaObjects) { break; } } tvUC.RequiredSecurityPermissions = securityActions; if (UserCanAdministerSite || UserCanAdministerGallery) { // Show all galleries the current user can administer. This allows them to move/copy objects between galleries. tvUC.RootAlbumPrefix = String.Concat(Resources.GalleryServerPro.Site_Gallery_Text, " '{GalleryDescription}': "); tvUC.Galleries = UserController.GetGalleriesCurrentUserCanAdminister(); } IAlbum albumToSelect = this.GetAlbum(); if (!IsUserAuthorized(SecurityActions.AddChildAlbum, albumToSelect)) { albumToSelect = AlbumController.GetHighestLevelAlbumWithAddPermission(hasAlbums, hasMediaObjects, GalleryId); } if (albumToSelect == null) { tvUC.BindTreeView(); } else { tvUC.BindTreeView(albumToSelect); } }
/// <summary> /// Determines if the securityActions parameter is one of the defined enumerations or a valid combination of valid enumeration /// values (since <see cref="SecurityActions" /> is defined with the Flags attribute). <see cref="Enum.IsDefined" /> cannot be used since it does not return /// true when the enumeration contains more than one enum value. This method requires the <see cref="SecurityActions" /> enum to have a member /// All that contains every enum value ORed together. /// </summary> /// <param name="securityActions">A <see cref="SecurityActions" />. It may be a single value or some /// combination of valid enumeration values.</param> /// <returns>Returns true if securityActions is one of the defined items in the enumeration or is a valid combination of /// enumeration values; otherwise returns false.</returns> public static bool IsValidSecurityAction(SecurityActions securityActions) { if ((securityActions != 0) && ((securityActions & SecurityActions.All) == securityActions)) { return(true); } else { return(false); } }
/// <summary> /// Determine if the user has the appropriate permission for the specified album. The user may be anonymous or logged on. /// When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), this method determines whether the user is authorized by /// validating that at least one role has the requested permission to the specified album. When the user is anonymous, /// the <paramref name="roles"/> parameter is ignored and instead the <paramref name="isPrivateAlbum"/> parameter is used. /// Anonymous users do not have any access to private albums. When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), /// the <paramref name="roles"/> parameter must contain the roles belonging to the user. /// </summary> /// <param name="securityRequests">The requested permissions.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated"/>=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies.</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged on. If true, the /// <paramref name="roles"/> parameter should contain the names of the roles for the current user. If <paramref name="isAuthenticated"/>=true /// and the <paramref name="roles"/> parameter is either null or an empty collection, this method returns false.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <returns>Returns true if the user has the requested permission; returns false if not.</returns> /// <remarks>This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated"/>=true, the /// <paramref name="isPrivateAlbum"/> parameter is ignored. When it is false, the roles parameter is ignored.</remarks> public static bool IsUserAuthorized(SecurityActions securityRequests, IGalleryServerRoleCollection roles, int albumId, bool isAuthenticated, bool isPrivateAlbum) { #region Validation if (isAuthenticated && ((roles == null) || (roles.Count == 0))) return false; #endregion // Handle anonymous users. if (!isAuthenticated) { return IsAnonymousUserAuthorized(securityRequests, isPrivateAlbum); } // If we get here we are dealing with an authenticated (logged on) user. Authorization for authenticated users is // given if the user is a member of at least one role that provides permission. if (SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests)) { // Iterate through each GalleryServerRole. If at least one allows the action, return true. Note that the // AdministerSite security action, if granted, applies to all albums and allows all actions (except HideWatermark). foreach (IGalleryServerRole role in roles) { if (IsAuthenticatedUserAuthorized(securityRequests, role, albumId)) return true; } return false; } else { // There are multiple security actions in securityRequest enum. User is authorized only if EVERY security request // is authorized. foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests)) { // Iterate through each GalleryServerRole. If at least role allows the action, return true. Note that the // AdministerSite security action, if granted, applies to all albums and allows all actions (except HideWatermark). bool securityActionIsAuthorized = false; foreach (IGalleryServerRole role in roles) { if (IsAuthenticatedUserAuthorized(securityAction, role, albumId)) { securityActionIsAuthorized = true; break; } } if (!securityActionIsAuthorized) return false; } // If we get to this point then every security request has been authorized, so we can authorize the entire request. return true; } }
/// <summary> /// Parses the security action into one or more <see cref="SecurityActions"/>. Since the <see cref="SecurityActions" /> /// enum has the Flags attribute and may contain a bitwise combination of more than one value, this function is useful /// in creating a list of the values that can be enumerated. /// </summary> /// <param name="securityActionsToParse">A <see cref="SecurityActions" />. It may be a single value or some /// combination of valid enumeration values.</param> /// <returns>Returns a list of <see cref="SecurityActions"/> that can be enumerated.</returns> public static IEnumerable <SecurityActions> ParseSecurityAction(SecurityActions securityActionsToParse) { List <SecurityActions> securityActions = new List <SecurityActions>(2); foreach (SecurityActions securityActionIterator in Enum.GetValues(typeof(SecurityActions))) { if ((securityActionsToParse & securityActionIterator) == securityActionIterator) { securityActions.Add(securityActionIterator); } } return(securityActions); }
private static bool IsAnonymousUserAuthorized(SecurityActions securityRequests, bool isPrivateAlbum, int galleryId, SecurityActionsOption secActionsOption) { // Anonymous user. Return true for viewing-related permission requests on PUBLIC albums; return false for all others. IGallerySettings gallerySettings = Factory.LoadGallerySetting(galleryId); if (SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests)) { return(IsAnonymousUserAuthorizedForSingleSecurityAction(securityRequests, isPrivateAlbum, gallerySettings)); } else { return(IsAnonymousUserAuthorizedForMultipleSecurityActions(securityRequests, isPrivateAlbum, gallerySettings, secActionsOption)); } }
private void ShowTreeview() { rptr.Visible = false; tvUC.Visible = true; // Find out if the objects we are transferring consist of only media objects, only albums, or both. // We use this knowledge to set the RequiredSecurityPermission property on the treeview user control // so that only albums where the user has permission are available for selection. bool hasAlbums = false; bool hasMediaObjects = false; SecurityActions securityActions = 0; foreach (string id in (string[])ViewState["ids"]) { if (id.StartsWith("a", StringComparison.Ordinal)) { securityActions = (((int)securityActions == 0) ? SecurityActions.AddChildAlbum : securityActions | SecurityActions.AddChildAlbum); hasAlbums = true; } if (id.StartsWith("m", StringComparison.Ordinal)) { securityActions = (((int)securityActions == 0) ? SecurityActions.AddMediaObject : securityActions | SecurityActions.AddMediaObject); hasMediaObjects = true; } if (hasAlbums && hasMediaObjects) { break; } } tvUC.RequiredSecurityPermissions = securityActions; IAlbum albumToSelect = this.GetAlbum(); if (!IsUserAuthorized(SecurityActions.AddChildAlbum, albumToSelect)) { albumToSelect = AlbumController.GetHighestLevelAlbumWithAddPermission(hasAlbums, hasMediaObjects); } if (albumToSelect == null) { tvUC.BindTreeView(); } else { tvUC.BindTreeView(albumToSelect); } }
private static bool IsAnonymousUserAuthorizedForSingleSecurityAction(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings) { bool isAuthorized = false; if ((securityRequests == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing) { isAuthorized = true; } if ((securityRequests == SecurityActions.ViewOriginalImage) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing && gallerySettings.AllowAnonymousHiResViewing) { isAuthorized = true; } return(isAuthorized); }
/// <summary> /// Determines if the specified value is a single, valid enumeration value. Since the <see cref="SecurityActions" /> enum has the /// Flags attribute and may contain a bitwise combination of more than one value, this function is useful in /// helping the developer decide if the enum value is just one value or it must be parsed into its constituent /// parts with the GalleryServerPro.Business.SecurityManager.ParseSecurityAction method. /// </summary> /// <param name="securityActions">A <see cref="SecurityActions" />. It may be a single value or some /// combination of valid enumeration values.</param> /// <returns>Returns true if securityAction is a valid, single bit flag; otherwise return false.</returns> public static bool IsSingleSecurityAction(SecurityActions securityActions) { if (IsValidSecurityAction(securityActions) && (securityActions == SecurityActions.ViewAlbumOrMediaObject) || (securityActions == SecurityActions.ViewOriginalImage) || (securityActions == SecurityActions.AddMediaObject) || (securityActions == SecurityActions.AdministerSite) || (securityActions == SecurityActions.DeleteAlbum) || (securityActions == SecurityActions.DeleteChildAlbum) || (securityActions == SecurityActions.DeleteMediaObject) || (securityActions == SecurityActions.EditAlbum) || (securityActions == SecurityActions.EditMediaObject) || (securityActions == SecurityActions.HideWatermark) || (securityActions == SecurityActions.Synchronize) || (securityActions == SecurityActions.AddChildAlbum) || (securityActions == SecurityActions.AdministerGallery)) { return(true); } else { return(false); } }
private bool IsUserAuthorized() { // If no media object is specified, then return true (this happens for empty album thumbnails). if (MediaObject.Id == int.MinValue) { return(true); } SecurityActions requestedPermission = SecurityActions.ViewAlbumOrMediaObject; if ((this._displayType == DisplayObjectType.Original) && (MediaObject.MimeType.TypeCategory == MimeTypeCategory.Image)) { requestedPermission = SecurityActions.ViewOriginalImage; } return(Utils.IsUserAuthorized(requestedPermission, RoleController.GetGalleryServerRolesForUser(), MediaObject.Parent.Id, GalleryId, MediaObject.IsPrivate)); }
private static bool IsAnonymousUserAuthorized(SecurityActions securityAction, bool isPrivateAlbum) { // Anonymous user. Return true for viewing-related permission requests on PUBLIC albums; return false for all others. if (SecurityActionEnumHelper.IsSingleSecurityAction(securityAction)) { if ((securityAction == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum) { return(true); } if ((securityAction == SecurityActions.ViewOriginalImage) && !isPrivateAlbum && ConfigManager.GetGalleryServerProConfigSection().Core.AllowAnonymousHiResViewing) { return(true); } } else { // There are multiple security actions in securityAction enum. User is authorized only if EVERY security request // is authorized. bool isAuthorized = true; foreach (SecurityActions securityRequest in SecurityActionEnumHelper.ParseSecurityAction(securityAction)) { bool securityActionIsAuthorized = false; if ((securityRequest == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum) { securityActionIsAuthorized = true; } if ((securityRequest == SecurityActions.ViewOriginalImage) && !isPrivateAlbum && ConfigManager.GetGalleryServerProConfigSection().Core.AllowAnonymousHiResViewing) { securityActionIsAuthorized = true; } if (!securityActionIsAuthorized) { isAuthorized = false; break; } } return(isAuthorized); } return(false); }
private bool IsUserAuthorized() { // If no media object is specified, then return true (this happens for empty album thumbnails). if ((ResourceType == MediaType.MediaObject) || (ResourceType == MediaType.MediaObjectWithWatermark)) { SecurityActions requestedPermission = SecurityActions.ViewAlbumOrMediaObject; if ((_displayType == DisplayObjectType.Original) && (MediaObject.MimeType.TypeCategory == MimeTypeCategory.Image)) { requestedPermission = SecurityActions.ViewOriginalImage; } return(Utils.IsUserAuthorized(requestedPermission, RoleController.GetGalleryServerRolesForUser(), MediaObject.Parent.Id, GalleryId, MediaObject.IsPrivate)); } else { return(true); // Non-media object requests are always valid (i.e. default album thumbnails) } }
public string PurgeCache(int id) { IAlbum album = null; try { album = AlbumController.LoadAlbumInstance(id, false); // Get a list of all actions that require purging the cache. User must have one of these // permissions in order to purge the cache. const SecurityActions securityActions = SecurityActions.AddChildAlbum | SecurityActions.EditAlbum | SecurityActions.DeleteChildAlbum | SecurityActions.AddMediaObject | SecurityActions.EditMediaObject | SecurityActions.DeleteMediaObject; if (!Utils.IsUserAuthorized(securityActions, id, album.GalleryId, album.IsPrivate, album.IsVirtualAlbum)) { return("Insufficient permission for purging the cache."); } HelperFunctions.PurgeCache(); return("Cache purged..."); } catch (Exception ex) { if (album != null) { AppEventController.LogError(ex, album.GalleryId); } else { AppEventController.LogError(ex); } throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = Utils.GetExStringContent(ex), ReasonPhrase = "Server Error" }); } }
private static bool IsAnonymousUserAuthorizedForMultipleSecurityActions(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings, SecurityActionsOption secActionsOption) { // There are multiple security actions in securityAction enum. Iterate through each one and determine if the user // has permission for it. List <bool> authResults = new List <bool>(); foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests)) { authResults.Add(IsAnonymousUserAuthorizedForSingleSecurityAction(securityAction, isPrivateAlbum, gallerySettings)); } if (secActionsOption == SecurityActionsOption.RequireAll) { return(authResults.Count > 0 ? authResults.TrueForAll(delegate(bool value) { return value; }) : false); } else if (secActionsOption == SecurityActionsOption.RequireOne) { return(authResults.Contains(true)); } else { throw new InvalidEnumArgumentException("secActionsOption", (int)secActionsOption, typeof(SecurityActionsOption)); } }
private bool IsUserAuthorized() { // If no media object is specified, then return true (this happens for empty album thumbnails). if ((ResourceType == MediaType.MediaObject) || (ResourceType == MediaType.MediaObjectWithWatermark)) { SecurityActions requestedPermission = SecurityActions.ViewAlbumOrMediaObject; if ((_displayType == DisplayObjectType.Original)) { var optFileDiffThanOriginal = !MediaObject.Original.FileName.Equals(MediaObject.Optimized.FileName, StringComparison.OrdinalIgnoreCase); if (optFileDiffThanOriginal) { requestedPermission = SecurityActions.ViewOriginalMediaObject; } } return(Utils.IsUserAuthorized(requestedPermission, RoleController.GetGalleryServerRolesForUser(), MediaObject.Parent.Id, GalleryId, MediaObject.IsPrivate, ((IAlbum)MediaObject.Parent).IsVirtualAlbum)); } else { return(true); // Non-media object requests are always valid (i.e. default album thumbnails) } }
/// <summary> /// Extract information from the query string and assign to our class level variables. Return false if something goes wrong /// and the variables cannot be set. This will happen when the query string is in an unexpected format. /// </summary> /// <param name="queryString">The query string for the current request. Can be populated with HttpContext.Request.Url.Query.</param> /// <returns>Returns true if all relevant variables were assigned from the query string; returns false if there was a problem.</returns> private bool ExtractQueryStringParms(string queryString) { if (String.IsNullOrEmpty(queryString)) { return(false); } if (queryString.StartsWith("?", StringComparison.Ordinal)) { queryString = queryString.Remove(0, 1); } //id={0}&secaction={1}&sc={2}&navurl={3} foreach (string nameValuePair in queryString.Split(new char[] { '&' })) { string[] nameOrValue = nameValuePair.Split(new char[] { '=' }); if (nameOrValue.Length < 2) { return(false); } switch (nameOrValue[0]) { case "id": { int aid; if (Int32.TryParse(nameOrValue[1], out aid)) { _albumId = aid; } else { return(false); } break; } case "secaction": { int secActionInt; if (Int32.TryParse(nameOrValue[1], out secActionInt)) { if (SecurityActionEnumHelper.IsValidSecurityAction((SecurityActions)secActionInt)) { _securityAction = (SecurityActions)secActionInt; break; } else { return(false); } } else { return(false); } } case "sc": { bool showCheckbox; if (Boolean.TryParse(nameOrValue[1], out showCheckbox)) { _showCheckbox = showCheckbox; } else { return(false); } break; } case "navurl": { _navigateUrl = Utils.UrlDecode(nameOrValue[1]).Trim(); break; } default: return(false); // Unexpected query string parm. Return false so execution is aborted. } } return(true); }
/// <overloads> /// Determine if a user has permission to perform the requested action. /// </overloads> /// <summary> /// Determine whether the user belonging to the specified <paramref name="roles" /> has permission to perform at least one of the specified security /// actions against the specified <paramref name="albumId" />. The user may be anonymous or logged on. /// When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), this method determines whether the user is authorized by /// validating that at least one role has the requested permission to the specified album. When the user is anonymous, /// the <paramref name="roles"/> parameter is ignored and instead the <paramref name="isPrivateAlbum"/> parameter is used. /// Anonymous users do not have any access to private albums. When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), /// the <paramref name="roles"/> parameter must contain the roles belonging to the user. /// </summary> /// <param name="securityRequests">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful if the user has permission for at least one of the actions. If you require /// that all actions be satisfied to be successful, call one of the overloads that accept a <see cref="SecurityActionsOption" /> and /// specify <see cref="SecurityActionsOption.RequireAll" />.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated"/>=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies. This parameter does not apply when the requested permission /// is <see cref="SecurityActions.AdministerSite" />.</param> /// <param name="galleryId">The ID for the gallery the user is requesting permission in. The <paramref name="albumId" /> must exist in this /// gallery. This parameter is not required <paramref name="securityRequests" /> is SecurityActions.AdministerSite (you can specify /// <see cref="int.MinValue" />).</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged on. If true, the /// <paramref name="roles"/> parameter should contain the names of the roles for the current user. If <paramref name="isAuthenticated"/>=true /// and the <paramref name="roles"/> parameter is either null or an empty collection, this method returns false.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <param name="isVirtualAlbum">if set to <c>true</c> the album is a virtual album.</param> /// /// <returns> /// Returns true if the user has the requested permission; returns false if not. /// </returns> /// <remarks>This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated"/>=true, the /// <paramref name="isPrivateAlbum"/> parameter is ignored. When it is false, the <paramref name="roles" /> parameter is ignored.</remarks> public static bool IsUserAuthorized(SecurityActions securityRequests, IGalleryServerRoleCollection roles, int albumId, int galleryId, bool isAuthenticated, bool isPrivateAlbum, bool isVirtualAlbum) { return IsUserAuthorized(securityRequests, roles, albumId, galleryId, isAuthenticated, isPrivateAlbum, SecurityActionsOption.RequireOne, isVirtualAlbum); }
private static bool IsAnonymousUserAuthorizedForMultipleSecurityActions(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings, SecurityActionsOption secActionsOption) { // There are multiple security actions in securityAction enum. Iterate through each one and determine if the user // has permission for it. List<bool> authResults = new List<bool>(); foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests)) { authResults.Add(IsAnonymousUserAuthorizedForSingleSecurityAction(securityAction, isPrivateAlbum, gallerySettings)); } if (secActionsOption == SecurityActionsOption.RequireAll) { return (authResults.Count > 0 ? authResults.TrueForAll(delegate(bool value) { return value; }) : false); } else if (secActionsOption == SecurityActionsOption.RequireOne) { return authResults.Contains(true); } else { throw new InvalidEnumArgumentException("secActionsOption", (int)secActionsOption, typeof(SecurityActionsOption)); } }
/// <summary> /// Determine whether the user belonging to the specified <paramref name="roles" /> has permission to perform all of the specified security /// actions against the specified <paramref name="albumId" />. The user may be anonymous or logged on. /// When the the user is logged on (i.e. <paramref name="isAuthenticated" /> = true), this method determines whether the user is authorized by /// validating that at least one role has the requested permission to the specified album. When the user is anonymous, /// the <paramref name="roles" /> parameter is ignored and instead the <paramref name="isPrivateAlbum" /> parameter is used. /// Anonymous users do not have any access to private albums. When the the user is logged on (i.e. <paramref name="isAuthenticated" /> = true), /// the <paramref name="roles" /> parameter must contain the roles belonging to the user. /// </summary> /// <param name="securityRequests">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, use <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied /// to be successful or only one item must be satisfied.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated" />=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies. This parameter does not apply when the requested permission /// is <see cref="SecurityActions.AdministerSite" /> or <see cref="SecurityActions.AdministerGallery" />.</param> /// <param name="galleryId">The ID for the gallery the user is requesting permission in. The <paramref name="albumId" /> must exist in this /// gallery. This parameter is not required <paramref name="securityRequests" /> is SecurityActions.AdministerSite (you can specify /// <see cref="int.MinValue" />).</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged on. If true, the /// <paramref name="roles" /> parameter should contain the names of the roles for the current user. If <paramref name="isAuthenticated" />=true /// and the <paramref name="roles" /> parameter is either null or an empty collection, this method returns false.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <param name="secActionsOption">Specifies whether the user must have permission for all items in <paramref name="securityRequests" /> /// to be successful or just one. This parameter defaults to SecurityActionsOption.RequireAll when not specified, and is applicable only /// when <paramref name="securityRequests" /> contains more than one item.</param> /// <param name="isVirtualAlbum">if set to <c>true</c> the album is a virtual album.</param> /// <returns> /// Returns true if the user has the requested permission; returns false if not. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"></exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"></exception> /// <remarks> /// This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated" />=true, the /// <paramref name="isPrivateAlbum" /> parameter is ignored. When it is false, the <paramref name="roles" /> parameter is ignored. /// </remarks> public static bool IsUserAuthorized(SecurityActions securityRequests, IGalleryServerRoleCollection roles, int albumId, int galleryId, bool isAuthenticated, bool isPrivateAlbum, SecurityActionsOption secActionsOption, bool isVirtualAlbum) { #region Validation if (isAuthenticated && !isVirtualAlbum && ((roles == null) || (roles.Count == 0))) return false; var userIsRequestingSysAdminPermission = (securityRequests & SecurityActions.AdministerSite) == SecurityActions.AdministerSite; var userIsRequestingGalleryAdminPermission = (securityRequests & SecurityActions.AdministerGallery) == SecurityActions.AdministerGallery; if (galleryId == int.MinValue) { var isMoreThanOnePermissionRequest = !SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests); if (isMoreThanOnePermissionRequest || !userIsRequestingSysAdminPermission) { throw new ArgumentOutOfRangeException("galleryId", String.Format(CultureInfo.CurrentCulture, "A valid gallery ID must be specified. Instead, the value was {0}.", galleryId)); } } #endregion if (isVirtualAlbum && (!userIsRequestingSysAdminPermission && !userIsRequestingGalleryAdminPermission)) { return true; // Virtual albums are always allowed, but only for non-admin requests. This feels hacky and non-intuitive; should try to improve someday } // Handle anonymous users. if (!isAuthenticated) { return IsAnonymousUserAuthorized(securityRequests, isPrivateAlbum, galleryId, secActionsOption); } // If we get here we are dealing with an authenticated (logged on) user. Authorization for authenticated users is // given if the user is a member of at least one role that provides permission. if (SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests)) { // Iterate through each GalleryServerRole. If at least one allows the action, return true. Note that the // AdministerSite security action, if granted, applies to all albums and allows all actions (except HideWatermark). foreach (IGalleryServerRole role in roles) { if (IsAuthenticatedUserAuthorized(securityRequests, role, albumId, galleryId)) return true; } return false; } else { // There are multiple security actions in securityRequest enum. Iterate through each one and determine if the user // has permission for it. List<bool> authResults = new List<bool>(); foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests)) { // Iterate through each role. If at least one role allows the action, permission is granted. foreach (IGalleryServerRole role in roles) { bool authResult = IsAuthenticatedUserAuthorized(securityAction, role, albumId, galleryId); authResults.Add(authResult); if (authResult) break; // We found a role that provides permission, so no need to check the other roles. Just move on to the next security request. } } // Determine the return value based on what the calling method wanted. if (secActionsOption == SecurityActionsOption.RequireAll) { return (authResults.Count > 0 ? authResults.TrueForAll(delegate(bool value) { return value; }) : false); } else if (secActionsOption == SecurityActionsOption.RequireOne) { return authResults.Contains(true); } else { throw new InvalidEnumArgumentException("secActionsOption", (int)secActionsOption, typeof(SecurityActionsOption)); } } }
/// <summary> /// Determine whether user has permission to perform at least one of the specified security actions. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// <see cref="SecurityActions.ViewAlbumOrMediaObject" /> or <see cref="SecurityActions.ViewOriginalImage" />, /// since Gallery Server is configured by default to allow anonymous viewing access but it does not allow anonymous editing of /// any kind. This method will continue to work correctly if the webmaster configures Gallery Server to require users to log /// in in order to view objects, since at that point there will be no such thing as un-authenticated users, and the standard /// gallery server role functionality applies. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful if the user has permission for at least one of the actions.</param> /// <param name="albumId">The album ID to which the security action applies.</param> /// <param name="galleryId">The ID for the gallery the user is requesting permission in. The <paramref name="albumId" /> must exist /// in this gallery.</param> /// <param name="isPrivate">Indicates whether the specified album is private (hidden from anonymous users). The parameter /// is ignored for logged on users.</param> /// <returns> /// Returns true when the user is authorized to perform the specified security action against the specified album; /// otherwise returns false. /// </returns> internal bool IsUserAuthorized(SecurityActions securityActions, int albumId, int galleryId, bool isPrivate) { return Utils.IsUserAuthorized(securityActions, GetGalleryServerRolesForUser(), albumId, galleryId, isPrivate); }
/// <summary> /// Determine whether user has permission to perform the specified security action against the specified album. If no album /// is specified, then the current album (as returned by GetAlbum()) is used. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// ViewAlbumOrMediaObject or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. This method behaves similarly to CheckUserSecurity() /// except that it returns true or false instead of throwing an exception when the user is not authorized. /// </summary> /// <param name="securityAction">The security action represents the action being carried out by the web page.</param> /// <returns>Returns true when the user is authorized to perform the specified security action; otherwise returns false.</returns> public bool IsUserAuthorized(SecurityActions securityAction) { return Util.IsUserAuthorized(securityAction, GetGalleryServerRolesForUser(), this.AlbumId, this.GetAlbum().IsPrivate); }
/// <summary> /// Determine whether user has permission to perform the specified security action. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// ViewAlbumOrMediaObject or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. This method will continue to work correctly if the webmaster configures /// Gallery Server to require users to log in in order to view objects, since at that point there will be no such thing as /// un-authenticated users, and the standard gallery server role functionality applies. This method behaves similarly to CheckUserSecurity() /// except that it returns true or false instead of throwing an exception when the user is not authorized. /// </summary> /// <param name="securityActions">The security action represents the action being carried out by the web page.</param> /// <param name="albumId">The album ID to which the security action applies.</param> /// <param name="isPrivate">Indicates whether the specified album is private (hidden from anonymous users). The parameter /// is ignored for logged on users.</param> /// <returns>Returns true when the user is authorized to perform the specified security action against the specified album; /// otherwise returns false.</returns> internal static bool IsUserAuthorized(SecurityActions securityActions, int albumId, bool isPrivate) { return IsUserAuthorized(securityActions, RoleController.GetGalleryServerRolesForUser(), albumId, isPrivate); }
/// <summary> /// Extract information from the query string and assign to our class level variables. Return false if something goes wrong /// and the variables cannot be set. This will happen when the query string is in an unexpected format. /// </summary> /// <param name="queryString">The query string for the current request. Can be populated with HttpContext.Request.Url.Query.</param> /// <returns>Returns true if all relevant variables were assigned from the query string; returns false if there was a problem.</returns> private bool ExtractQueryStringParms(string queryString) { if (String.IsNullOrEmpty(queryString)) { return(false); } if (queryString.StartsWith("?", StringComparison.Ordinal)) { queryString = queryString.Remove(0, 1); } // id=0&gid=all&secaction=6&sc=false&navurl=&levels=2&includealbum=true&idtoselect%5B%5D=220&idtoselect%5B%5D=99 foreach (string nameValuePair in queryString.Split(new char[] { '&' })) { string[] nameOrValue = nameValuePair.Split(new char[] { '=' }); if (nameOrValue.Length < 2) { return(false); } switch (Utils.UrlDecode(nameOrValue[0])) { case "id": { int aid; if (Int32.TryParse(nameOrValue[1], out aid)) { _albumId = aid; } else { return(false); } break; } case "gid": { int gid; if (Int32.TryParse(nameOrValue[1], out gid)) { _galleries = new GalleryCollection() { Factory.LoadGallery(gid) }; } else if (Utils.UrlDecode(nameOrValue[1]).Trim() == "all") { _galleries = UserController.GetGalleriesCurrentUserCanAdminister(); } else { return(false); } break; } case "secaction": { int secActionInt; if (Int32.TryParse(nameOrValue[1], out secActionInt)) { if (SecurityActionEnumHelper.IsValidSecurityAction((SecurityActions)secActionInt)) { _securityAction = (SecurityActions)secActionInt; break; } else { return(false); } } else { return(false); } } case "sc": { bool showCheckbox; if (Boolean.TryParse(nameOrValue[1], out showCheckbox)) { _showCheckbox = showCheckbox; } else { return(false); } break; } case "navurl": { _navigateUrl = Utils.UrlDecode(nameOrValue[1]).Trim(); break; } case "levels": { int numLevels; if (Int32.TryParse(nameOrValue[1], out numLevels)) { _numberOfLevels = numLevels; } else { return(false); } break; } case "includealbum": { bool includeAlbum; if (Boolean.TryParse(nameOrValue[1], out includeAlbum)) { _includeAlbum = includeAlbum; } else { return(false); } break; } case "idtoselect": case "idtoselect[]": { int idToSelect; if (Int32.TryParse(nameOrValue[1], out idToSelect)) { _albumIdsToSelect.Add(idToSelect); } else { return(false); } break; } default: return(false); // Unexpected query string parm. Return false so execution is aborted. } } return(true); }
/// <summary> /// Check to ensure user has permission to perform the specified security actions against the current album (identified in /// <see cref="GetAlbumId()" />). Throw a <see cref="GallerySecurityException"/> /// if the permission isn't granted to the logged on user. When multiple security actions are passed, use /// <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied to be successful or only one item /// must be satisfied. Un-authenticated users (anonymous users) are always considered NOT authorized (that is, this method /// returns false) except when the requested security action is <see cref="SecurityActions.ViewAlbumOrMediaObject"/> or /// <see cref="SecurityActions.ViewOriginalMediaObject"/>, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. This method behaves similarly to /// <see cref="IsUserAuthorized(SecurityActions, SecurityActionsOption)"/> except that /// it throws an exception instead of returning false when the user is not authorized. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, use <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied /// to be successful or only one item must be satisfied.</param> /// <param name="secActionsOption">Specifies whether the user must have permission for all items in <paramref name="securityActions" /> /// to be successful or just one. This parameter is applicable only when <paramref name="securityActions" /> contains more than one item.</param> /// <exception cref="GalleryServerPro.Events.CustomExceptions.GallerySecurityException">Thrown when the logged on user /// does not belong to a role that authorizes the specified security action, or if an anonymous user is requesting any permission /// other than a viewing-related permission (i.e., <see cref="SecurityActions.ViewAlbumOrMediaObject"/> or /// <see cref="SecurityActions.ViewOriginalMediaObject"/>).</exception> public void CheckUserSecurity(SecurityActions securityActions, SecurityActionsOption secActionsOption) { if (!Utils.IsUserAuthorized(securityActions, GetGalleryServerRolesForUser(), this.GetAlbumId(), this.GalleryId, this.GetAlbum().IsPrivate, secActionsOption, this.GetAlbum().IsVirtualAlbum)) { if (this.IsAnonymousUser) { throw new GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "Anonymous user does not have permission '{0}' for album ID {1}.", securityActions.ToString(), this.GetAlbumId())); } else { throw new GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "User '{0}' does not have permission '{1}' for album ID {2}.", Utils.UserName, securityActions.ToString(), this.GetAlbumId())); } } }
/// <summary> /// Determine whether the user belonging to the specified <paramref name="roles" /> has permission to perform all of the specified security /// actions against the specified <paramref name="albumId" />. The user may be anonymous or logged on. /// When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), this method determines whether the user is authorized by /// validating that at least one role has the requested permission to the specified album. When the user is anonymous, /// the <paramref name="roles"/> parameter is ignored and instead the <paramref name="isPrivateAlbum"/> parameter is used. /// Anonymous users do not have any access to private albums. When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), /// the <paramref name="roles"/> parameter must contain the roles belonging to the user. /// </summary> /// <param name="securityRequests">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, use <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied /// to be successful or only one item must be satisfied.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated"/>=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies. This parameter does not apply when the requested permission /// is <see cref="SecurityActions.AdministerSite" /> or <see cref="SecurityActions.AdministerGallery" />.</param> /// <param name="galleryId">The ID for the gallery the user is requesting permission in. The <paramref name="albumId" /> must exist in this /// gallery. This parameter is not required <paramref name="securityRequests" /> is SecurityActions.AdministerSite (you can specify /// <see cref="int.MinValue" />).</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged on. If true, the /// <paramref name="roles"/> parameter should contain the names of the roles for the current user. If <paramref name="isAuthenticated"/>=true /// and the <paramref name="roles"/> parameter is either null or an empty collection, this method returns false.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <param name="secActionsOption">Specifies whether the user must have permission for all items in <paramref name="securityRequests" /> /// to be successful or just one. This parameter defaults to SecurityActionsOption.RequireAll when not specified, and is applicable only /// when <paramref name="securityRequests" /> contains more than one item.</param> /// <returns> /// Returns true if the user has the requested permission; returns false if not. /// </returns> /// <remarks>This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated"/>=true, the /// <paramref name="isPrivateAlbum"/> parameter is ignored. When it is false, the <paramref name="roles" /> parameter is ignored.</remarks> public static bool IsUserAuthorized(SecurityActions securityRequests, IGalleryServerRoleCollection roles, int albumId, int galleryId, bool isAuthenticated, bool isPrivateAlbum, SecurityActionsOption secActionsOption) { #region Validation if (isAuthenticated && ((roles == null) || (roles.Count == 0))) { return(false); } if (galleryId == int.MinValue) { bool isMoreThanOnePermissionRequest = !SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests); bool userIsRequestingSysAdminPermission = (securityRequests == SecurityActions.AdministerSite); if (isMoreThanOnePermissionRequest || !userIsRequestingSysAdminPermission) { throw new ArgumentOutOfRangeException("galleryId", String.Format(CultureInfo.CurrentCulture, "A valid gallery ID must be specified. Instead, the value was {0}.", galleryId)); } } #endregion // Handle anonymous users. if (!isAuthenticated) { return(IsAnonymousUserAuthorized(securityRequests, isPrivateAlbum, galleryId, secActionsOption)); } // If we get here we are dealing with an authenticated (logged on) user. Authorization for authenticated users is // given if the user is a member of at least one role that provides permission. if (SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests)) { // Iterate through each GalleryServerRole. If at least one allows the action, return true. Note that the // AdministerSite security action, if granted, applies to all albums and allows all actions (except HideWatermark). foreach (IGalleryServerRole role in roles) { if (IsAuthenticatedUserAuthorized(securityRequests, role, albumId, galleryId)) { return(true); } } return(false); } else { // There are multiple security actions in securityRequest enum. Iterate through each one and determine if the user // has permission for it. List <bool> authResults = new List <bool>(); foreach (SecurityActions securityAction in SecurityActionEnumHelper.ParseSecurityAction(securityRequests)) { // Iterate through each role. If at least one role allows the action, permission is granted. foreach (IGalleryServerRole role in roles) { bool authResult = IsAuthenticatedUserAuthorized(securityAction, role, albumId, galleryId); authResults.Add(authResult); if (authResult) { break; // We found a role that provides permission, so no need to check the other roles. Just move on to the next security request. } } } // Determine the return value based on what the calling method wanted. if (secActionsOption == SecurityActionsOption.RequireAll) { return(authResults.Count > 0 ? authResults.TrueForAll(delegate(bool value) { return value; }) : false); } else if (secActionsOption == SecurityActionsOption.RequireOne) { return(authResults.Contains(true)); } else { throw new InvalidEnumArgumentException("secActionsOption", (int)secActionsOption, typeof(SecurityActionsOption)); } } }
private static bool IsAnonymousUserAuthorizedForSingleSecurityAction(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings) { return((securityRequests == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing || (securityRequests == SecurityActions.ViewOriginalMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing && gallerySettings.EnableAnonymousOriginalMediaObjectDownload); }
/// <summary> /// Determine whether user has permission to perform the specified security action against the specified album. If no album /// is specified, then the current album (as returned by GetAlbum()) is used. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// ViewAlbumOrMediaObject or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. This method behaves similarly to CheckUserSecurity() /// except that it returns true or false instead of throwing an exception when the user is not authorized. /// </summary> /// <param name="securityAction">The security action represents the action being carried out by the web page.</param> /// <param name="album">The album for which the security check is to be applied.</param> /// <returns>Returns true when the user is authorized to perform the specified security action; otherwise returns false.</returns> public bool IsUserAuthorized(SecurityActions securityAction, IAlbum album) { return Util.IsUserAuthorized(securityAction, GetGalleryServerRolesForUser(), album.Id, album.IsPrivate); }
private static bool IsAnonymousUserAuthorized(SecurityActions securityAction, bool isPrivateAlbum) { // Anonymous user. Return true for viewing-related permission requests on PUBLIC albums; return false for all others. if (SecurityActionEnumHelper.IsSingleSecurityAction(securityAction)) { if ((securityAction == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum) return true; if ((securityAction == SecurityActions.ViewOriginalImage) && !isPrivateAlbum && ConfigManager.GetGalleryServerProConfigSection().Core.AllowAnonymousHiResViewing) return true; } else { // There are multiple security actions in securityAction enum. User is authorized only if EVERY security request // is authorized. bool isAuthorized = true; foreach (SecurityActions securityRequest in SecurityActionEnumHelper.ParseSecurityAction(securityAction)) { bool securityActionIsAuthorized = false; if ((securityRequest == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum) securityActionIsAuthorized = true; if ((securityRequest == SecurityActions.ViewOriginalImage) && !isPrivateAlbum && ConfigManager.GetGalleryServerProConfigSection().Core.AllowAnonymousHiResViewing) securityActionIsAuthorized = true; if (!securityActionIsAuthorized) { isAuthorized = false; break; } } return isAuthorized; } return false; }
/// <summary> /// Determine whether user has permission to perform the specified security actions against the current album (identified in /// <see cref="GetAlbumId()" />). When multiple security actions are passed, use /// <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied to be successful or only one item /// must be satisfied. Un-authenticated users (anonymous users) are always considered NOT authorized (that /// is, this method returns false) except when the requested security action is <see cref="SecurityActions.ViewAlbumOrMediaObject" /> /// or <see cref="SecurityActions.ViewOriginalImage" />, since Gallery Server is configured by default to allow anonymous viewing /// access but it does not allow anonymous editing of any kind. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, use <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied /// to be successful or only one item must be satisfied. This parameter is applicable only when <paramref name="securityActions" /> /// contains more than one item.</param> /// <param name="secActionsOption">Specifies whether the user must have permission for all items in <paramref name="securityActions" /> /// to be successful or just one.</param> /// <returns>Returns true when the user is authorized to perform the specified security action; otherwise returns false.</returns> public bool IsUserAuthorized(SecurityActions securityActions, SecurityActionsOption secActionsOption) { return Utils.IsUserAuthorized(securityActions, GetGalleryServerRolesForUser(), this.GetAlbumId(), this.GalleryId, this.GetAlbum().IsPrivate, secActionsOption); }
/// <summary> /// Determine whether user has permission to perform the specified security action. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// ViewAlbumOrMediaObject or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. This method will continue to work correctly if the webmaster configures /// Gallery Server to require users to log in in order to view objects, since at that point there will be no such thing as /// un-authenticated users, and the standard gallery server role functionality applies. This method behaves similarly to CheckUserSecurity() /// except that it returns true or false instead of throwing an exception when the user is not authorized. /// </summary> /// <param name="securityActions">The security action represents the action being carried out by the web page.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs.</param> /// <param name="albumId">The album ID to which the security action applies.</param> /// <param name="isPrivate">Indicates whether the specified album is private (hidden from anonymous users). The parameter /// is ignored for logged on users.</param> /// <returns>Returns true when the user is authorized to perform the specified security action against the specified album; /// otherwise returns false.</returns> internal static bool IsUserAuthorized(SecurityActions securityActions, IGalleryServerRoleCollection roles, int albumId, bool isPrivate) { return Util.IsUserAuthorized(securityActions, roles, albumId, isPrivate); }
/// <summary> /// Determine whether user has permission to perform the specified security action against the specified album. If no album /// is specified, then the current album (as returned by GetAlbum()) is used. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// ViewAlbumOrMediaObject or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, use <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied /// to be successful or only one item must be satisfied.</param> /// <param name="album">The album for which the security check is to be applied.</param> /// <param name="secActionsOption">Specifies whether the user must have permission for all items in <paramref name="securityActions" /> /// to be successful or just one. This parameter is applicable only when <paramref name="securityActions" /> contains more than one item.</param> /// <returns>Returns true when the user is authorized to perform the specified security action; otherwise returns false.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> is null.</exception> public bool IsUserAuthorized(SecurityActions securityActions, IAlbum album, SecurityActionsOption secActionsOption) { if (album == null) throw new ArgumentNullException("album"); return Utils.IsUserAuthorized(securityActions, GetGalleryServerRolesForUser(), album.Id, album.GalleryId, album.IsPrivate, secActionsOption); }
/// <summary> /// Check to ensure user has permission to perform the specified security actions for the specified <paramref name="album" />. /// Throw a <see cref="GallerySecurityException" /> if the permission isn't granted to the logged on user. When multiple /// security actions are passed, use <paramref name="secActionsOption" /> to specify whether all of the actions must be /// satisfied to be successful or only one item must be satisfied. Un-authenticated users (anonymous users) are always /// considered NOT authorized (that is, this method returns false) except when the requested security action is /// <see cref="SecurityActions.ViewAlbumOrMediaObject"/> or <see cref="SecurityActions.ViewOriginalImage"/>, since Gallery /// Server is configured by default to allow anonymous viewing access but it does not allow anonymous editing of any kind. /// This method behaves similarly to <see cref="IsUserAuthorized(SecurityActions, IAlbum, SecurityActionsOption)"/> except /// that it throws an exception instead of returning false when the user is not authorized. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, use <paramref name="secActionsOption" /> to specify whether all of the actions must be satisfied /// to be successful or only one item must be satisfied.</param> /// <param name="album">The album for which the security check is to be applied.</param> /// <param name="secActionsOption">Specifies whether the user must have permission for all items in <paramref name="securityActions" /> /// to be successful or just one. This parameter is applicable only when <paramref name="securityActions" /> contains more than one item.</param> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Thrown when the logged on user /// does not belong to a role that authorizes the specified security action, or if an anonymous user is requesting any permission /// other than a viewing-related permission (i.e., <see cref="SecurityActions.ViewAlbumOrMediaObject"/> or /// <see cref="SecurityActions.ViewOriginalImage"/>).</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> is null.</exception> public void CheckUserSecurity(SecurityActions securityActions, IAlbum album, SecurityActionsOption secActionsOption) { if (album == null) throw new ArgumentNullException("album"); if (!Utils.IsUserAuthorized(securityActions, GetGalleryServerRolesForUser(), album.Id, album.GalleryId, album.IsPrivate, secActionsOption)) { if (this.IsAnonymousUser) { throw new GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "Anonymous user does not have permission '{0}' for album ID {1}.", securityActions.ToString(), album.Id)); } else { throw new GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "User '{0}' does not have permission '{1}' for album ID {2}.", Utils.UserName, securityActions.ToString(), album.Id)); } } }
/// <summary> /// Check to ensure user has permission to perform the specified security action. Throw a /// GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException if the /// permission isn't granted to the logged on user. Un-authenticated users (anonymous users) are always considered /// NOT authorized (that is, this method returns false) except when the requested security action is ViewAlbumOrMediaObject /// or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access but it does /// not allow anonymous editing of any kind. This method behaves similarly to IsUserAuthorized() except that it throws an /// exception instead of returning false when the user is not authorized. /// </summary> /// <param name="securityActions">The security action represents the action being carried out by the web page.</param> /// <param name="album">The album for which the security check is to be applied.</param> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Thrown when the logged on user /// does not belong to a role that authorizes the specified security action, or if an anonymous user is requesting any permission /// other than a viewing-related permission (i.e., SecurityActions.ViewAlbumOrMediaObject or SecurityActions.ViewOriginalImage).</exception> public void CheckUserSecurity(SecurityActions securityActions, IAlbum album) { if (!Util.IsUserAuthorized(securityActions, GetGalleryServerRolesForUser(), album.Id, album.IsPrivate)) { if (this.IsAnonymousUser) { throw new GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "Anonymous user does not have permission '{0}' for album ID {1}.", securityActions.ToString(), album.Id)); } else { throw new GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "User '{0}' does not have permission '{1}' for album ID {2}.", Util.UserName, securityActions.ToString(), album.Id)); } } }
/// <summary> /// Determine whether user has permission to perform at least one of the specified security actions against the specified <paramref name="album" />. /// Un-authenticated users (anonymous users) are always considered NOT authorized (that is, this method returns false) except /// when the requested security action is <see cref="SecurityActions.ViewAlbumOrMediaObject" /> or /// <see cref="SecurityActions.ViewOriginalImage" />, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful if the user has permission for at least one of the actions. If you require /// that all actions be satisfied to be successful, call one of the overloads that accept a <see cref="SecurityActionsOption" /> and /// specify <see cref="SecurityActionsOption.RequireAll" />.</param> /// <param name="album">The album for which the security check is to be applied.</param> /// <returns>Returns true when the user is authorized to perform the specified security action; otherwise returns false.</returns> public bool IsUserAuthorized(SecurityActions securityActions, IAlbum album) { return IsUserAuthorized(securityActions, album, SecurityActionsOption.RequireOne); }
/// <summary> /// Parses the security action into one or more <see cref="SecurityActions"/>. Since the <see cref="SecurityActions" /> /// enum has the Flags attribute and may contain a bitwise combination of more than one value, this function is useful /// in creating a list of the values that can be enumerated. /// </summary> /// <param name="securityActionsToParse">A <see cref="SecurityActions" />. It may be a single value or some /// combination of valid enumeration values.</param> /// <returns>Returns a list of <see cref="SecurityActions"/> that can be enumerated.</returns> public static System.Collections.Generic.List <SecurityActions> ParseSecurityAction(SecurityActions securityActionsToParse) { System.Collections.Generic.List <SecurityActions> securityActions = new System.Collections.Generic.List <SecurityActions>(2); foreach (SecurityActions securityActionIterator in Enum.GetValues(typeof(SecurityActions))) { if ((securityActionsToParse & securityActionIterator) == securityActionIterator) { securityActions.Add(securityActionIterator); } } return(securityActions); }
/// <summary> /// Determine whether user has permission to perform at least one of the specified security actions. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// <see cref="SecurityActions.ViewAlbumOrMediaObject" /> or <see cref="SecurityActions.ViewOriginalImage" />, /// since Gallery Server is configured by default to allow anonymous viewing access but it does not allow anonymous editing of /// any kind. This method will continue to work correctly if the webmaster configures Gallery Server to require users to log /// in in order to view objects, since at that point there will be no such thing as un-authenticated users, and the standard /// gallery server role functionality applies. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful if the user has permission for at least one of the actions.</param> /// <param name="albumId">The album ID to which the security action applies.</param> /// <param name="galleryId">The ID for the gallery the user is requesting permission in. The <paramref name="albumId" /> must exist /// in this gallery.</param> /// <returns> /// Returns true when the user is authorized to perform the specified security action against the specified album; /// otherwise returns false. /// </returns> /// <exception cref="NotSupportedException">Thrown when <paramref name="securityActions" /> is <see cref="SecurityActions.ViewAlbumOrMediaObject" /> /// or <see cref="SecurityActions.ViewOriginalImage" /> and the user is anonymous (not logged on).</exception> internal bool IsUserAuthorized(SecurityActions securityActions, int albumId, int galleryId) { if (((securityActions == SecurityActions.ViewAlbumOrMediaObject) || (securityActions == SecurityActions.ViewOriginalImage)) && (!Utils.IsAuthenticated)) throw new NotSupportedException("Wrong method call: You must call the overload of GalleryPage.IsUserAuthorized that has the isPrivate parameter when the security action is ViewAlbumOrMediaObject or ViewOriginalImage and the user is anonymous (not logged on)."); return IsUserAuthorized(securityActions, albumId, galleryId, false); }
private static IAlbum LoadRootAlbumForLoggedOnUser(int galleryId, SecurityActions permissions, IEnumerable<IGalleryServerRole> roles) { // Step 1: Compile a list of album IDs having the requested permissions. List<int> allAlbumIds = GetAlbumIdsHavingRequestedPermissionsInRoles(galleryId, permissions, roles); // Step 2: Convert previous list to contain ONLY top-level albums. List<int> rootAlbumIds = RemoveNestedAlbumIds(allAlbumIds); // Step 3: Package results into an album container. If there is only one viewable root album, then just create an instance of that album. // Otherwise, create a virtual root album to contain the multiple viewable albums. IAlbum rootAlbum = null; try { if (rootAlbumIds.Count == 1) { rootAlbum = LoadAlbumInstance(rootAlbumIds[0], true); } else { // Create virtual album to serve as a container for the child albums the user has permission to view. rootAlbum = CreateEmptyAlbumInstance(galleryId); rootAlbum.IsVirtualAlbum = true; rootAlbum.Title = Resources.Virtual_Album_Title; foreach (int albumId in rootAlbumIds) { rootAlbum.Add(LoadAlbumInstance(albumId, false)); } } } catch { if (rootAlbum != null) rootAlbum.Dispose(); throw; } return rootAlbum; }
private static bool IsAnonymousUserAuthorizedForSingleSecurityAction(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings) { bool isAuthorized = false; if ((securityRequests == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing) isAuthorized = true; if ((securityRequests == SecurityActions.ViewOriginalImage) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing && gallerySettings.AllowAnonymousHiResViewing) isAuthorized = true; return isAuthorized; }
/// <overloads> /// Determine if a user has permission to perform the requested action. /// </overloads> /// <summary> /// Determine whether the user belonging to the specified <paramref name="roles" /> has permission to perform at least one of the specified security /// actions against the specified <paramref name="albumId" />. The user may be anonymous or logged on. /// When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), this method determines whether the user is authorized by /// validating that at least one role has the requested permission to the specified album. When the user is anonymous, /// the <paramref name="roles"/> parameter is ignored and instead the <paramref name="isPrivateAlbum"/> parameter is used. /// Anonymous users do not have any access to private albums. When the the user is logged on (i.e. <paramref name="isAuthenticated"/> = true), /// the <paramref name="roles"/> parameter must contain the roles belonging to the user. /// </summary> /// <param name="securityRequests">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful if the user has permission for at least one of the actions. If you require /// that all actions be satisfied to be successful, call one of the overloads that accept a <see cref="SecurityActionsOption" /> and /// specify <see cref="SecurityActionsOption.RequireAll" />.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users (i.e. <paramref name="isAuthenticated"/>=false). The parameter may be null.</param> /// <param name="albumId">The album for which the requested permission applies. This parameter does not apply when the requested permission /// is <see cref="SecurityActions.AdministerSite" />.</param> /// <param name="galleryId">The ID for the gallery the user is requesting permission in. The <paramref name="albumId" /> must exist in this /// gallery. This parameter is not required <paramref name="securityRequests" /> is SecurityActions.AdministerSite (you can specify /// <see cref="int.MinValue" />).</param> /// <param name="isAuthenticated">A value indicating whether the current user is logged on. If true, the /// <paramref name="roles"/> parameter should contain the names of the roles for the current user. If <paramref name="isAuthenticated"/>=true /// and the <paramref name="roles"/> parameter is either null or an empty collection, this method returns false.</param> /// <param name="isPrivateAlbum">A value indicating whether the album is hidden from anonymous users. This parameter is ignored for /// logged-on users.</param> /// <returns> /// Returns true if the user has the requested permission; returns false if not. /// </returns> /// <remarks>This method handles both anonymous and logged on users. Note that when <paramref name="isAuthenticated"/>=true, the /// <paramref name="isPrivateAlbum"/> parameter is ignored. When it is false, the <paramref name="roles" /> parameter is ignored.</remarks> public static bool IsUserAuthorized(SecurityActions securityRequests, IGalleryServerRoleCollection roles, int albumId, int galleryId, bool isAuthenticated, bool isPrivateAlbum) { return(IsUserAuthorized(securityRequests, roles, albumId, galleryId, isAuthenticated, isPrivateAlbum, SecurityActionsOption.RequireOne)); }
private static bool IsAnonymousUserAuthorized(SecurityActions securityRequests, bool isPrivateAlbum, int galleryId, SecurityActionsOption secActionsOption) { // Anonymous user. Return true for viewing-related permission requests on PUBLIC albums; return false for all others. IGallerySettings gallerySettings = Factory.LoadGallerySetting(galleryId); if (SecurityActionEnumHelper.IsSingleSecurityAction(securityRequests)) { return IsAnonymousUserAuthorizedForSingleSecurityAction(securityRequests, isPrivateAlbum, gallerySettings); } else { return IsAnonymousUserAuthorizedForMultipleSecurityActions(securityRequests, isPrivateAlbum, gallerySettings, secActionsOption); } }
private static IAlbum LoadRootAlbumForAnonymousUser(int galleryId, SecurityActions permissions) { IAlbum rootAlbum = null; // Anonymous user, not logged on. Get root album as long as it is public. IAlbum tmpRootAlbum = Factory.LoadRootAlbumInstance(galleryId); if (SecurityManager.IsUserAuthorized(permissions, null, tmpRootAlbum.Id, galleryId, false, tmpRootAlbum.IsPrivate, SecurityActionsOption.RequireOne)) { rootAlbum = tmpRootAlbum; } if (rootAlbum == null) { try { // The user is not logged on and the root album is private or does not have the required permission, so create an empty album. rootAlbum = Factory.CreateEmptyAlbumInstance(galleryId); rootAlbum.IsVirtualAlbum = true; rootAlbum.Title = Resources.Virtual_Album_Title; } catch { if (rootAlbum != null) rootAlbum.Dispose(); throw; } return rootAlbum; } return rootAlbum; }
private static bool IsAnonymousUserAuthorizedForSingleSecurityAction(SecurityActions securityRequests, bool isPrivateAlbum, IGallerySettings gallerySettings) { return (securityRequests == SecurityActions.ViewAlbumOrMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing || (securityRequests == SecurityActions.ViewOriginalMediaObject) && !isPrivateAlbum && gallerySettings.AllowAnonymousBrowsing && gallerySettings.EnableAnonymousOriginalMediaObjectDownload; }
/// <summary> /// Throw exception if user does not have permission to move the specified gallery object out of the current album. /// Moving an album or media object means we are essentially deleting it from the source album, so make sure user has /// the appropriate delete permission for the current album. Does not validate user has permission to add objects to /// destination album. Assumes each gallery object is contained in the current album as retrieved by GspPage.GetAlbum(). /// No validation is performed if we are copying since no special permissions are needed for copying (except a check /// on the destination album, which we do elsewhere). /// </summary> /// <param name="galleryObjectToMoveOrCopy">The album or media object to move or copy.</param> /// <param name="securityActions">The security permission to validate.</param> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Thrown when the logged on /// user does not belong to a role that authorizes the specified security action.</exception> private void ValidateSecurityForAlbumOrMediaObject(IGalleryObject galleryObjectToMoveOrCopy, SecurityActions securityActions) { if (this.TransType == TransferType.Move) { if (!IsUserAuthorized(securityActions, galleryObjectToMoveOrCopy.Id)) { throw new GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "User '{0}' does not have permission '{1}' for album ID {2}.", Util.UserName, securityActions.ToString(), galleryObjectToMoveOrCopy.Id)); } } }
/// <summary> /// Determine whether user has permission to perform the specified security action. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// ViewAlbumOrMediaObject or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. This method will continue to work correctly if the webmaster configures /// Gallery Server to require users to log in in order to view objects, since at that point there will be no such thing as /// un-authenticated users, and the standard gallery server role functionality applies. This method behaves similarly to CheckUserSecurity() /// except that it returns true or false instead of throwing an exception when the user is not authorized. /// </summary> /// <param name="securityActions">The security action represents the action being carried out by the web page.</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. This parameter is ignored /// for anonymous users. The parameter may be null.</param> /// <param name="albumId">The album ID to which the security action applies.</param> /// <param name="isPrivate">Indicates whether the specified album is private (hidden from anonymous users). The parameter /// is ignored for logged on users.</param> /// <returns>Returns true when the user is authorized to perform the specified security action against the specified album; /// otherwise returns false.</returns> public static bool IsUserAuthorized(SecurityActions securityActions, IGalleryServerRoleCollection roles, int albumId, bool isPrivate) { return SecurityManager.IsUserAuthorized(securityActions, roles, albumId, Util.IsAuthenticated, isPrivate); }
/// <summary> /// Throw exception if user does not have permission to move the specified gallery object out of the current album. /// Moving an album or media object means we are essentially deleting it from the source album, so make sure user has /// the appropriate delete permission for the current album. Does not validate user has permission to add objects to /// destination album. Assumes each gallery object is contained in the current album as retrieved by GspPage.GetAlbum(). /// No validation is performed if we are copying since no special permissions are needed for copying (except a check /// on the destination album, which we do elsewhere). /// </summary> /// <param name="galleryObjectToMoveOrCopy">The album or media object to move or copy.</param> /// <param name="securityActions">The security permission to validate.</param> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Thrown when the logged on /// user does not belong to a role that authorizes the specified security action.</exception> private void ValidateSecurityForAlbumOrMediaObject(IGalleryObject galleryObjectToMoveOrCopy, SecurityActions securityActions) { if (this.TransType == TransferType.Move) { if (!IsUserAuthorized(securityActions, galleryObjectToMoveOrCopy.Id, this.GalleryId)) { throw new GallerySecurityException(String.Format(CultureInfo.CurrentCulture, "User '{0}' does not have permission '{1}' for album ID {2}.", Utils.UserName, securityActions, galleryObjectToMoveOrCopy.Id)); } } }
/// <summary> /// Extract information from the query string and assign to our class level variables. Return false if something goes wrong /// and the variables cannot be set. This will happen when the query string is in an unexpected format. /// </summary> /// <param name="queryString">The query string for the current request. Can be populated with HttpContext.Request.Url.Query.</param> /// <returns>Returns true if all relevant variables were assigned from the query string; returns false if there was a problem.</returns> private bool ExtractQueryStringParms(string queryString) { if (String.IsNullOrEmpty(queryString)) return false; if (queryString.StartsWith("?", StringComparison.Ordinal)) queryString = queryString.Remove(0, 1); //id={0}&secaction={1}&sc={2}&navurl={3} foreach (string nameValuePair in queryString.Split(new char[] { '&' })) { string[] nameOrValue = nameValuePair.Split(new char[] { '=' }); if (nameOrValue.Length < 2) { return false; } switch (nameOrValue[0]) { case "id": { int aid; if (Int32.TryParse(nameOrValue[1], out aid)) _albumId = aid; else return false; break; } case "secaction": { int secActionInt; if (Int32.TryParse(nameOrValue[1], out secActionInt)) { if (SecurityActionEnumHelper.IsValidSecurityAction((SecurityActions)secActionInt)) { _securityAction = (SecurityActions)secActionInt; break; } else return false; } else return false; } case "sc": { bool showCheckbox; if (Boolean.TryParse(nameOrValue[1], out showCheckbox)) _showCheckbox = showCheckbox; else return false; break; } case "navurl": { _navigateUrl = Utils.UrlDecode(nameOrValue[1]).Trim(); break; } default: return false; // Unexpected query string parm. Return false so execution is aborted. } } return true; }
/// <overloads> /// Throw a <see cref="GallerySecurityException" /> if the current user does not have the permission to perform the requested action. /// </overloads> /// <summary> /// Check to ensure user has permission to perform at least one of the specified security actions against the current album /// (identified in <see cref="GetAlbumId()" />). Throw a <see cref="GallerySecurityException" /> /// if the permission isn't granted to the logged on user. Un-authenticated users (anonymous users) are always considered /// NOT authorized (that is, this method returns false) except when the requested security action is <see cref="SecurityActions.ViewAlbumOrMediaObject" /> /// or <see cref="SecurityActions.ViewOriginalImage" />, since Gallery Server is configured by default to allow anonymous viewing access but it does /// not allow anonymous editing of any kind. This method behaves similarly to <see cref="IsUserAuthorized(SecurityActions)" /> except that it throws an /// exception instead of returning false when the user is not authorized. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful if the user has permission for at least one of the actions. If you require /// that all actions be satisfied to be successful, call one of the overloads that accept a <see cref="SecurityActionsOption" /> and /// specify <see cref="SecurityActionsOption.RequireAll" />.</param> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Thrown when the logged on user /// does not belong to a role that authorizes the specified security action, or if an anonymous user is requesting any permission /// other than a viewing-related permission (i.e., <see cref="SecurityActions.ViewAlbumOrMediaObject" /> or /// <see cref="SecurityActions.ViewOriginalImage" />).</exception> public void CheckUserSecurity(SecurityActions securityActions) { CheckUserSecurity(securityActions, SecurityActionsOption.RequireOne); }
private static bool IsAuthenticatedUserAuthorized(SecurityActions securityRequest, IGalleryServerRole role, int albumId) { if ((role.AllowAdministerSite) && (securityRequest != SecurityActions.HideWatermark)) { // Administer permissions imply permissions to carry out all other actions, except for hide watermark, which is more of // a preference assigned to the user. return true; } switch (securityRequest) { case SecurityActions.AdministerSite: if (role.AllowAdministerSite) return true; break; case SecurityActions.ViewAlbumOrMediaObject: if (role.AllowViewAlbumOrMediaObject && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.ViewOriginalImage: if (role.AllowViewOriginalImage && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.AddChildAlbum: if (role.AllowAddChildAlbum && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.AddMediaObject: if (role.AllowAddMediaObject && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.DeleteAlbum: { // It is OK to delete the album if the AllowDeleteChildAlbum permission is true and one of the following is true: // 1. The album is the root album and its ID is in the list of targeted albums (Note that we never actually delete the root album. // Instead, we delete all objects within the album. But the idea of deleting the top level album to clear out all objects in the // gallery is useful to the user.) // 2. The album is not the root album and its parent album's ID is in the list of targeted albums. if (role.AllowDeleteChildAlbum) { IAlbum album = Factory.LoadAlbumInstance(albumId, false); if (album.IsRootAlbum) { if (role.AllAlbumIds.Contains(album.Id)) return true; break; } else { if (role.AllAlbumIds.Contains(album.Parent.Id)) return true; break; } } break; } case SecurityActions.DeleteChildAlbum: if (role.AllowDeleteChildAlbum && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.DeleteMediaObject: if (role.AllowDeleteMediaObject && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.EditAlbum: if (role.AllowEditAlbum && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.EditMediaObject: if (role.AllowEditMediaObject && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.HideWatermark: if (role.HideWatermark && role.AllAlbumIds.Contains(albumId)) return true; break; case SecurityActions.Synchronize: if (role.AllowSynchronize && role.AllAlbumIds.Contains(albumId)) return true; break; default: throw new GalleryServerPro.ErrorHandler.CustomExceptions.BusinessException(string.Format(CultureInfo.CurrentCulture, "The IsUserAuthorized function is not designed to handle the {0} SecurityActions. It must be updated by a developer.", securityRequest.ToString())); } return false; }
/// <summary> /// Check to ensure user has permission to perform at least one of the specified security actions for the specified <paramref name="album" />. /// Throw a <see cref="GallerySecurityException" /> if the permission isn't granted to the logged on user. Un-authenticated users /// (anonymous users) are always considered NOT authorized (that is, this method returns false) except when the requested security /// action is <see cref="SecurityActions.ViewAlbumOrMediaObject" /> or <see cref="SecurityActions.ViewOriginalImage" />, since /// Gallery Server is configured by default to allow anonymous viewing access but it does not allow anonymous editing of any kind. /// This method behaves similarly to <see cref="IsUserAuthorized(SecurityActions, IAlbum)" /> except that it throws an exception /// instead of returning false when the user is not authorized. /// </summary> /// <param name="securityActions">Represents the permission or permissions being requested. Multiple actions can be specified by using /// a bitwise OR between them (example: <see cref="SecurityActions.AdministerSite" /> | <see cref="SecurityActions.AdministerGallery" />). /// If multiple actions are specified, the method is successful if the user has permission for at least one of the actions. If you require /// that all actions be satisfied to be successful, call one of the overloads that accept a <see cref="SecurityActionsOption" /> and /// specify <see cref="SecurityActionsOption.RequireAll" />.</param> /// <param name="album">The album for which the security check is to be applied.</param> /// <exception cref="GalleryServerPro.ErrorHandler.CustomExceptions.GallerySecurityException">Thrown when the logged on user /// does not belong to a role that authorizes the specified security action, or if an anonymous user is requesting any permission /// other than a viewing-related permission (i.e., <see cref="SecurityActions.ViewAlbumOrMediaObject"/> or /// <see cref="SecurityActions.ViewOriginalImage"/>).</exception> public void CheckUserSecurity(SecurityActions securityActions, IAlbum album) { CheckUserSecurity(securityActions, album, SecurityActionsOption.RequireOne); }
private static bool IsAuthenticatedUserAuthorized(SecurityActions securityRequest, IGalleryServerRole role, int albumId, int galleryId) { if (role.AllowAdministerSite && (securityRequest != SecurityActions.HideWatermark)) { // Administer permissions imply permissions to carry out all other actions, except for hide watermark, which is more of // a preference assigned to the user. return(true); } switch (securityRequest) { case SecurityActions.AdministerSite: if (role.AllowAdministerSite) { return(true); } break; case SecurityActions.AdministerGallery: if (role.AllowAdministerGallery && (role.Galleries.FindById(galleryId) != null)) { return(true); } break; case SecurityActions.ViewAlbumOrMediaObject: if (role.AllowViewAlbumOrMediaObject && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.ViewOriginalImage: if (role.AllowViewOriginalImage && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.AddChildAlbum: if (role.AllowAddChildAlbum && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.AddMediaObject: if (role.AllowAddMediaObject && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.DeleteAlbum: { // It is OK to delete the album if the AllowDeleteChildAlbum permission is true and one of the following is true: // 1. The album is the root album and its ID is in the list of targeted albums (Note that we never actually delete the root album. // Instead, we delete all objects within the album. But the idea of deleting the top level album to clear out all objects in the // gallery is useful to the user.) // 2. The album is not the root album and its parent album's ID is in the list of targeted albums. if (role.AllowDeleteChildAlbum) { IAlbum album = Factory.LoadAlbumInstance(albumId, false); if (album.IsRootAlbum) { if (role.AllAlbumIds.Contains(album.Id)) { return(true); } break; } else { if (role.AllAlbumIds.Contains(album.Parent.Id)) { return(true); } break; } } break; } case SecurityActions.DeleteChildAlbum: if (role.AllowDeleteChildAlbum && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.DeleteMediaObject: if (role.AllowDeleteMediaObject && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.EditAlbum: if (role.AllowEditAlbum && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.EditMediaObject: if (role.AllowEditMediaObject && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.HideWatermark: if (role.HideWatermark && role.AllAlbumIds.Contains(albumId)) { return(true); } break; case SecurityActions.Synchronize: if (role.AllowSynchronize && role.AllAlbumIds.Contains(albumId)) { return(true); } break; default: throw new GalleryServerPro.ErrorHandler.CustomExceptions.BusinessException(String.Format(CultureInfo.CurrentCulture, "The IsUserAuthorized function is not designed to handle the {0} SecurityActions. It must be updated by a developer.", securityRequest.ToString())); } return(false); }
/// <summary> /// Determine whether user has permission to perform the specified security action. Un-authenticated users (anonymous users) are /// always considered NOT authorized (that is, this method returns false) except when the requested security action is /// ViewAlbumOrMediaObject or ViewOriginalImage, since Gallery Server is configured by default to allow anonymous viewing access /// but it does not allow anonymous editing of any kind. This method will continue to work correctly if the webmaster configures /// Gallery Server to require users to log in in order to view objects, since at that point there will be no such thing as /// un-authenticated users, and the standard gallery server role functionality applies. This method behaves similarly to CheckUserSecurity() /// except that it returns true or false instead of throwing an exception when the user is not authorized. /// </summary> /// <param name="securityActions">The security action represents the action being carried out by the web page.</param> /// <param name="albumId">The album ID to which the security action applies.</param> /// <returns>Returns true when the user is authorized to perform the specified security action against the specified album; /// otherwise returns false.</returns> internal static bool IsUserAuthorized(SecurityActions securityActions, int albumId) { if (((securityActions == SecurityActions.ViewAlbumOrMediaObject) || (securityActions == SecurityActions.ViewOriginalImage)) && (!Util.IsAuthenticated)) throw new System.NotSupportedException("Wrong method call: You must call the overload of GspPage.IsUserAuthorized that has the isPrivate parameter when the security action is ViewAlbumOrMediaObject or ViewOriginalImage and the user is anonymous (not logged on)."); return IsUserAuthorized(securityActions, RoleController.GetGalleryServerRolesForUser(), albumId, false); }