/// <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)); } }
private bool IsUserAuthorized() { // Show the media object if one of the following is true: // 1. The user is not authenticated. If we get to this point and the user is not authenticated, that means forms // authenticated has been configured to allow anonymous access to this handler. So go ahead and show media object. // 2. The user is authenticated, AND the user is authorized to view media objects within the specified album. // 3. The user is authenticated, the user is requesting a hi-res image, AND the user is authorized to view // hi-res images. bool userCanViewRegularImage = false; bool userCanViewHiResImage = false; if (this._isUserAuthenticated) { IGalleryServerRoleCollection roles = RoleController.GetGalleryServerRolesForUser(); userCanViewRegularImage = Util.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, roles, this._albumId, this._isPrivate); if (this._displayType == DisplayObjectType.Original) { userCanViewHiResImage = Util.IsUserAuthorized(SecurityActions.ViewOriginalImage, roles, this._albumId, this._isPrivate); } } bool isUserAuthorized = ((!this._isUserAuthenticated) || ((this._displayType != DisplayObjectType.Original) && userCanViewRegularImage) || ((this._displayType == DisplayObjectType.Original) && userCanViewHiResImage)); return(isUserAuthorized); }
/// <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)); } }
protected string GetRoleNames() { List <Role> roles = new List <Role>(); IGalleryServerRoleCollection gspRoles = GetRolesCurrentUserCanView(); const int maxNRolesPerformanceLimit = 30; // We don't include a list of members when the roles count exceeds this value because it is processor intensive bool includeMembers = (gspRoles.Count <= maxNRolesPerformanceLimit); roles.Add(new Role { Name = Resources.GalleryServerPro.Admin_Manage_Roles_Create_Role_Lbl, IsNew = true }); foreach (IGalleryServerRole r in gspRoles) { Role role = new Role() { Name = r.RoleName, IsOwner = RoleController.IsRoleAnAlbumOwnerRole(r.RoleName) || RoleController.IsRoleAnAlbumOwnerTemplateRole(r.RoleName) }; if (includeMembers) { role.Members = RoleController.GetUsersInRole(r.RoleName); } roles.Add(role); } return(roles.ToArray().ToJson().JsEncode()); }
/// <summary> /// Create a <see cref="ZipUtility" /> instance with the specified parameters. /// </summary> /// <param name="userName">The user name of the logged on user. May be null or empty, although some functions, /// such as <see cref="ExtractZipFile"/>, require a valid user and will throw an exception if not present.</param> /// <param name="roles">The gallery server roles the logged on user belongs to.</param> public ZipUtility(string userName, IGalleryServerRoleCollection roles) { userName = userName ?? String.Empty; this._userName = userName; this._roles = roles; this._isAuthenticated = !String.IsNullOrEmpty(this._userName); }
/// <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> /// 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> /// Make sure the list of ASP.NET roles is synchronized with the Gallery Server roles. If any are missing from /// either, add it. /// </summary> public static void ValidateRoles() { List <IGalleryServerRole> validatedRoles = new List <IGalleryServerRole>(); IGalleryServerRoleCollection galleryRoles = Factory.LoadGalleryServerRoles(); bool needToPurgeCache = false; foreach (string roleName in GetAllRoles()) { IGalleryServerRole galleryRole = galleryRoles.GetRoleByRoleName(roleName); if (galleryRole == null) { // This is an ASP.NET role that doesn't exist in our list of gallery server roles. Add it with minimum permissions // applied to zero albums. IGalleryServerRole newRole = Factory.CreateGalleryServerRoleInstance(roleName, false, false, false, false, false, false, false, false, false, false, false); newRole.Save(); needToPurgeCache = true; } validatedRoles.Add(galleryRole); } // Now check to see if there are gallery roles that are not ASP.NET roles. Add if necessary. foreach (IGalleryServerRole galleryRole in galleryRoles) { if (!validatedRoles.Contains(galleryRole)) { // Need to create an ASP.NET role for this gallery role. CreateRole(galleryRole.RoleName); needToPurgeCache = true; } } if (needToPurgeCache) { HelperFunctions.PurgeCache(); } }
public IGalleryServerRoleCollection GetGalleryServerRolesForUser() { if (this._roles == null) { this._roles = RoleController.GetGalleryServerRolesForUser(); } return this._roles; }
/// <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(Gsp.SecurityActions securityActions, IGalleryServerRoleCollection roles, int albumId, bool isPrivate) { return Gsp.SecurityManager.IsUserAuthorized(securityActions, roles, albumId, HttpContext.Current.User.Identity.IsAuthenticated, isPrivate); }
/// <summary> /// Determine whether the user belonging to the specified <paramref name="roles" /> is a site administrator. The user is considered a site /// administrator if at least one role has Allow Administer Site permission. /// </summary> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. The parameter may be null.</param> /// <returns> /// <c>true</c> if the user is a site administrator; otherwise, <c>false</c>. /// </returns> public static bool IsUserSiteAdministrator(IGalleryServerRoleCollection roles) { return(IsUserAuthorized(SecurityActions.AdministerSite, roles, int.MinValue, int.MinValue, true, false)); }
/// <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)); }
/// <summary> /// Return gallery objects that match the specified search string and for which the specified user has authorization /// to view. A gallery object is considered a match when all search terms are found in the relevant fields. /// For albums, the title and summary fields are searched. For media objects, the title, original filename, /// and metadata are searched. The contents of documents are not searched (e.g. the text of a Word or PDF file). /// If no matches are found, an empty collection is returned. If the userIsAuthenticated parameter is true, only those /// objects for which the user has authorization are returned. If userIsAuthenticated=false (i.e. the user is anonymous), /// only non-private matching objects are returned. /// </summary> /// <param name="galleryId">The ID for the gallery containing the objects to search.</param> /// <param name="searchText">A space or comma-delimited string of search terms. Double quotes (") may be used /// to combine more than one word into a single search term. Example: cat "0 step" Mom will search for all /// objects that contain the strings "cat", "0 step", and "Mom".</param> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. /// This parameter is ignored when userIsAuthenticated=false.</param> /// <param name="userIsAuthenticated">A value indicating whether the current user is logged on. If true, the /// roles parameter should contain the names of the roles for the current user. If userIsAuthenticated=true and /// the roles parameter is either null or an empty collection, this method returns an empty collection.</param> /// <returns> /// Returns a GalleryObjectCollection containing the matching items. This may include albums and media /// objects from different albums. /// </returns> public static IGalleryObjectCollection SearchGallery(int galleryId, string searchText, IGalleryServerRoleCollection roles, bool userIsAuthenticated) { string[] searchTerms = ParseSearchText(searchText); List<int> matchingAlbumIds; List<int> matchingMediaObjectIds; Factory.GetDataProvider().SearchGallery(galleryId, searchTerms, out matchingAlbumIds, out matchingMediaObjectIds); IGalleryObjectCollection galleryObjects = new GalleryObjectCollection(); matchingAlbumIds.ForEach(delegate(int albumId) { IGalleryObject album = Factory.LoadAlbumInstance(albumId, false); if (SecurityManager.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, roles, albumId, galleryId, userIsAuthenticated, album.IsPrivate)) { galleryObjects.Add(album); // All security checks OK. Add to collection. } }); matchingMediaObjectIds.ForEach(delegate(int mediaObjectId) { IGalleryObject mediaObject = Factory.LoadMediaObjectInstance(mediaObjectId); if (SecurityManager.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, roles, mediaObject.Parent.Id, galleryId, userIsAuthenticated, mediaObject.IsPrivate)) { galleryObjects.Add(mediaObject); // User is authorized to view this media object. } }); return galleryObjects; }
private string BuildMenuString() { if (!this.GalleryPage.ShowAlbumBreadCrumb) { return(String.Empty); } string menuString = string.Empty; bool renderLinks = GalleryPage.GalleryControl.AllowUrlOverride; IAlbum album = GalleryPage.GetAlbum(); IGalleryServerRoleCollection roles = this.GalleryPage.GetGalleryServerRolesForUser(); string dividerText = Resources.GalleryServerPro.UC_Album_Menu_Album_Divider_Text; bool foundTopAlbum = false; bool foundBottomAlbum = false; while (!foundTopAlbum) { // Iterate through each album and it's parents, working the way toward the top. For each album, build up a breadcrumb menu item. // Eventually we will reach one of three situations: (1) a virtual album that contains the child albums, (2) an album the current // user does not have permission to view, or (3) the actual top-level album. if (album.IsVirtualAlbum) { menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} <a href=\"{1}\">{2}</a>", dividerText, AlbumController.GetUrl(album), album.Title)); var searchVirtualAlbumTypes = new[] { VirtualAlbumType.Tag, VirtualAlbumType.People, VirtualAlbumType.Search, VirtualAlbumType.TitleOrCaption, VirtualAlbumType.MostRecentlyAdded, VirtualAlbumType.Rated }; var isAlbumSearchResult = searchVirtualAlbumTypes.Contains(album.VirtualAlbumType); if (isAlbumSearchResult) { // Add one more link to represent the root album. menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} <a href=\"{1}\">{2}</a>", dividerText, Utils.GetCurrentPageUrl(), Resources.GalleryServerPro.Site_Virtual_Album_Title)); } foundTopAlbum = true; } else if (!Utils.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, roles, album.Id, album.GalleryId, album.IsPrivate, album.IsVirtualAlbum)) { // User is not authorized to view this album. If the user has permission to view more than one top-level album, then we want // to display an "All albums" link. To determine this, load the root album. If a virtual album is returned, then we know the // user has access to more than one top-level album. If it is an actual album (with a real ID and persisted in the data store), // that means that album is the only top-level album the user can view, and thus we do not need to create a link that is one // "higher" than that album. IAlbum rootAlbum = Factory.LoadRootAlbum(this.GalleryPage.GalleryId, GalleryPage.GetGalleryServerRolesForUser(), Utils.IsAuthenticated); if (rootAlbum.IsVirtualAlbum) { menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} <a href=\"{1}\">{2}</a>", dividerText, Utils.GetCurrentPageUrl(), Resources.GalleryServerPro.Site_Virtual_Album_Title)); } foundTopAlbum = true; } else { // Regular album somewhere in the hierarchy. Create a breadcrumb link. string hyperlinkIdString = String.Empty; if (!foundBottomAlbum) { hyperlinkIdString = " id=\"currentAlbumLink\""; // ID is referenced when inline editing an album's title foundBottomAlbum = true; } if (renderLinks) { menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} <a{1} href=\"{2}\">{3}</a>", dividerText, hyperlinkIdString, AlbumController.GetUrl(album), Utils.RemoveHtmlTags(album.Title))); } else { menuString = menuString.Insert(0, String.Format(CultureInfo.CurrentCulture, " {0} {1}", dividerText, Utils.RemoveHtmlTags(album.Title))); } } if (album.Parent is GalleryServerPro.Business.NullObjects.NullGalleryObject) { foundTopAlbum = true; } else { album = (IAlbum)album.Parent; } } if (menuString.Length > (dividerText.Length + 2)) { menuString = menuString.Substring(dividerText.Length + 2); // Remove the first divider character } return(menuString); }
/// <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); }
/// <summary> /// Verify the specified roles conform to business rules. Specificially, if any of the roles have administrative permissions /// (AllowAdministerSite = true): /// 1. Make sure there is a single root album ID set to the root album. /// 2. Make sure all role permissions - except HideWatermark - are set to true. /// If anything needs updating, update the object and persist the changes to the data store. This helps keep the data store /// valid in cases where the user is directly editing the tables (for example, deleting records from the gs_Role_Album table). /// </summary> /// <param name="roles">A collection of gallery server roles for the current gallery.</param> private static void ValidateRoleIntegrity(IGalleryServerRoleCollection roles) { foreach (IGalleryServerRole role in roles) { if (role.AllowAdministerSite) { bool hasChanges = false; if (!role.AllowAddChildAlbum) { role.AllowAddChildAlbum = true; hasChanges = true; } if (!role.AllowAddMediaObject) { role.AllowAddMediaObject = true; hasChanges = true; } if (!role.AllowDeleteChildAlbum) { role.AllowDeleteChildAlbum = true; hasChanges = true; } if (!role.AllowDeleteMediaObject) { role.AllowDeleteMediaObject = true; hasChanges = true; } if (!role.AllowEditAlbum) { role.AllowEditAlbum = true; hasChanges = true; } if (!role.AllowEditMediaObject) { role.AllowEditMediaObject = true; hasChanges = true; } if (!role.AllowSynchronize) { role.AllowSynchronize = true; hasChanges = true; } if (!role.AllowViewAlbumOrMediaObject) { role.AllowViewAlbumOrMediaObject = true; hasChanges = true; } if (!role.AllowViewOriginalImage) { role.AllowViewOriginalImage = true; hasChanges = true; } // Don't change role.HideWatermark; administrator may prefer to see watermark. int rootAlbumId = Factory.LoadRootAlbumInstance().Id; if ((role.RootAlbumIds.Count != 1) || ((role.RootAlbumIds.Count == 1) && (!role.RootAlbumIds.Contains(rootAlbumId)))) { // User is an administrator but the root album has not been specified as the sole root album ID. Since admins always // have complete access to all albums, let's update the data store to give the user permission to the root album. role.RootAlbumIds.Clear(); role.RootAlbumIds.Add(rootAlbumId); hasChanges = true; } if (hasChanges) { role.Save(); } } } }
/// <summary> /// Return all top-level albums in the specified <paramref name = "galleryId">gallery</paramref> where the <paramref name = "roles" /> /// provide view permission to the album. If more than one album is found, they are wrapped in a virtual container /// album where the <see cref="IAlbum.IsVirtualAlbum" /> property is set to true. If the roles do not provide permission to any /// objects in the gallery, then a virtual album is returned where <see cref="IAlbum.IsVirtualAlbum" />=<c>true</c> and /// <see cref="IGalleryObject.Id" />=<see cref="Int32.MinValue" />. Returns null if no matching albums are found. /// </summary> /// <param name="galleryId">The gallery ID.</param> /// <param name="roles">The roles belonging to a user.</param> /// <param name="isAuthenticated">Indicates whether the user belonging to the <paramref name="roles" /> is authenticated.</param> /// <returns> /// Returns an <see cref="IAlbum" /> that is or contains the top-level album(s) that the <paramref name = "roles" /> /// provide view permission for. Returns null if no matching albums are found. /// </returns> public static IAlbum LoadRootAlbum(int galleryId, IGalleryServerRoleCollection roles, bool isAuthenticated) { var galleryObjectSearcher = new GalleryObjectSearcher(new GalleryObjectSearchOptions() { GalleryId = galleryId, SearchType = GalleryObjectSearchType.HighestAlbumUserCanView, Roles = roles, IsUserAuthenticated = isAuthenticated, Filter = GalleryObjectType.Album }); return galleryObjectSearcher.FindOne() as IAlbum; }
/// <summary> /// Determines whether the user has permission to edit the specified role. Determines this by checking /// whether the logged on user is a site administrator or a gallery administrator for every /// gallery associated with the role. If the role is not assigned to any albums, it verifies the user is /// a gallery admin to at least one gallery (doesn't matter which one). /// </summary> /// <param name="roleToSave">The role to save. It's role name must match the role name of <paramref name="existingRole" />.</param> /// <param name="existingRole">The existing role, as it is stored in the database. It's role name must match the role name of /// <paramref name="roleToSave" />.</param> /// <param name="rolesForCurrentUser">The roles for current user.</param> /// <exception cref="GallerySecurityException">Thrown when the role cannot be saved because doing so would violate a business rule.</exception> private static void ValidateUserCanEditRole(IGalleryServerRole roleToSave, IGalleryServerRole existingRole, IGalleryServerRoleCollection rolesForCurrentUser) { if (Utils.IsCurrentUserSiteAdministrator()) { return; } if (roleToSave.Galleries.Count == 0) { // The role isn't assigned to any albums, so let's make sure the user is a gallery admin to at // least one gallery. if (GalleryController.GetGalleriesCurrentUserCanAdminister().Count == 0) { throw new GallerySecurityException("Your account does not have permission to make changes to roles."); } } if (existingRole.Galleries.Any(gallery => !Utils.IsUserGalleryAdministrator(rolesForCurrentUser, gallery.GalleryId))) { throw new GallerySecurityException(Resources.GalleryServerPro.Admin_Manage_Roles_Cannot_Delete_Role_Insufficient_Permission_Msg2); } }
private string buildMenuString() { string menuString = string.Empty; string appPath = Util.GetCurrentPageUrl(); IAlbum album = GalleryPage.GetAlbum(); IGalleryServerRoleCollection roles = this.GalleryPage.GetGalleryServerRolesForUser(); string dividerText = Resources.GalleryServerPro.UC_Album_Menu_Album_Divider_Text; bool foundTopAlbum = false; bool foundBottomAlbum = false; while (!foundTopAlbum) { // Iterate through each album and it's parents, working the way toward the top. For each album, build up a breadcrumb menu item. // Eventually we will reach one of three situations: (1) a virtual album that contains the child albums, (2) an album the current // user does not have permission to view, or (3) the actual top-level album. if (album.IsVirtualAlbum) { menuString = menuString.Insert(0, string.Format(CultureInfo.CurrentCulture, " {0} <a href=\"{1}\">{2}</a>", dividerText, appPath, Resources.GalleryServerPro.Site_Virtual_Album_Title)); foundTopAlbum = true; } else if (!Util.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, roles, album.Id, album.IsPrivate)) { // User is not authorized to view this album. If the user has permission to view more than one top-level album, then we want // to display an "All albums" link. To determine this, load the root album. If a virtual album is returned, then we know the // user has access to more than one top-level album. If it is an actual album (with a real ID and persisted in the data store), // that means that album is the only top-level album the user can view, and thus we do not need to create a link that is one // "higher" than that album. IAlbum rootAlbum = Factory.LoadRootAlbum(SecurityActions.ViewAlbumOrMediaObject | SecurityActions.ViewOriginalImage, GalleryPage.GetGalleryServerRolesForUser()); if (rootAlbum.IsVirtualAlbum) { menuString = menuString.Insert(0, string.Format(CultureInfo.CurrentCulture, " {0} <a href=\"{1}\">{2}</a>", dividerText, appPath, Resources.GalleryServerPro.Site_Virtual_Album_Title)); } foundTopAlbum = true; } else { // Regular album somewhere in the hierarchy. Create a breadcrumb link. string hyperlinkIdString = String.Empty; if (!foundBottomAlbum) { hyperlinkIdString = " id=\"currentAlbumLink\""; // ID is referenced when inline editing an album's title foundBottomAlbum = true; } menuString = menuString.Insert(0, string.Format(CultureInfo.CurrentCulture, " {0} <a{1} href=\"{2}?aid={3}\">{4}</a>", dividerText, hyperlinkIdString, appPath, album.Id, Util.RemoveHtmlTags(album.Title))); } if (album.Parent is GalleryServerPro.Business.NullObjects.NullGalleryObject) { foundTopAlbum = true; } else { album = (IAlbum)album.Parent; } } menuString = menuString.Substring(dividerText.Length + 2); // Remove the first divider character return(menuString); }
/// <summary> /// Determine whether the user belonging to the specified <paramref name="roles" /> is a site administrator. The user is considered a site /// administrator if at least one role has Allow Administer Site permission. /// </summary> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. The parameter may be null.</param> /// <returns> /// <c>true</c> if the user is a site administrator; otherwise, <c>false</c>. /// </returns> public static bool IsUserSiteAdministrator(IGalleryServerRoleCollection roles) { return SecurityManager.IsUserSiteAdministrator(roles); }
/// <summary> /// Determine whether the user belonging to the specified <paramref name="roles"/> is a gallery administrator for the specified /// <paramref name="galleryId"/>. The user is considered a gallery administrator if at least one role has Allow Administer Gallery permission. /// </summary> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. The parameter may be null.</param> /// <param name="galleryId">The gallery ID.</param> /// <returns> /// <c>true</c> if the user is a gallery administrator; otherwise, <c>false</c>. /// </returns> public static bool IsUserGalleryAdministrator(IGalleryServerRoleCollection roles, int galleryId) { return SecurityManager.IsUserGalleryAdministrator(roles, galleryId); }
/// <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: SecurityActions.AdministerSite | 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 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. The parameter may be null.</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. This parameter is not required <paramref name="securityActions" /> is SecurityActions.AdministerSite (you can specify /// <see cref="int.MinValue" />).</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, int galleryId, bool isPrivate) { return IsUserAuthorized(securityActions, roles, albumId, galleryId, isPrivate, SecurityActionsOption.RequireOne); }
/// <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 the user belonging to the specified <paramref name="roles" /> is a site administrator. The user is considered a site /// administrator if at least one role has Allow Administer Site permission. /// </summary> /// <param name="roles">A collection of Gallery Server roles to which the currently logged-on user belongs. The parameter may be null.</param> /// <returns> /// <c>true</c> if the user is a site administrator; otherwise, <c>false</c>. /// </returns> public static bool IsUserSiteAdministrator(IGalleryServerRoleCollection roles) { return IsUserAuthorized(SecurityActions.AdministerSite, roles, int.MinValue, int.MinValue, true, false, 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="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. 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> /// 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)); } } }
/// <summary> /// Gets the roles belonging to the current user. /// </summary> private async Task <IGalleryServerRoleCollection> GetRoles() { return(_roles ?? (_roles = await Options.UserController.GetGalleryServerRolesForUser())); }
/// <summary> /// Gets a value indicating whether a user can view the specified <paramref name="album" />. /// </summary> /// <returns><c>true</c> if the user can view the album; otherwise, <c>false</c>.</returns> public static bool CanUserViewAlbum(IAlbum album, IGalleryServerRoleCollection roles, bool isUserAuthenticated) { return SecurityManager.IsUserAuthorized(SecurityActions.ViewAlbumOrMediaObject, roles, album.Id, album.GalleryId, isUserAuthenticated, album.IsPrivate, SecurityActionsOption.RequireOne, album.IsVirtualAlbum); }
/// <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> /// <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) { 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, roles, albumId, false); }
/// <summary> /// Return all top-level albums where the <paramref name="roles"/> provide the requested <paramref name="permissions"/>. /// If more than one album is found, they are wrapped in a virtual container album where the IsVirtualAlbum property is /// set to true. Returns null if no matching albums are found. /// </summary> /// <param name="permissions">The permissions that must be provided by the roles.</param> /// <param name="roles">The roles belonging to a user.</param> /// <returns>Returns an <see cref="IAlbum"/> that is or contains the top-lvel album(s) that the <paramref name="roles"/> /// provide the requested <paramref name="permissions"/>. Returns null if no matching albums are found.</returns> public static IAlbum LoadRootAlbum(SecurityActions permissions, IGalleryServerRoleCollection roles) { #region Step 1: Compile a list of album IDs having the requested permissions List<int> allAlbumIds = new List<int>(); foreach (IGalleryServerRole role in roles) { foreach (SecurityActions permission in SecurityActionEnumHelper.ParseSecurityAction(permissions)) { switch (permission) { case SecurityActions.ViewAlbumOrMediaObject: if (role.AllowViewAlbumOrMediaObject) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.ViewOriginalImage: if (role.AllowViewOriginalImage) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.AddChildAlbum: if (role.AllowAddChildAlbum) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.AddMediaObject: if (role.AllowAddMediaObject) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.AdministerSite: if (role.AllowAdministerSite) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); 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) { foreach (int albumId in role.RootAlbumIds) { IAlbum album = LoadAlbumInstance(albumId, false); if (album.IsRootAlbum) { if (!role.AllAlbumIds.Contains(album.Id)) allAlbumIds.Add(albumId); break; } else if (!role.AllAlbumIds.Contains(album.Parent.Id)) allAlbumIds.Add(albumId); break; } } break; case SecurityActions.DeleteChildAlbum: if (role.AllowDeleteChildAlbum) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.DeleteMediaObject: if (role.AllowDeleteMediaObject) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.EditAlbum: if (role.AllowEditAlbum) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.EditMediaObject: if (role.AllowEditMediaObject) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.HideWatermark: if (role.HideWatermark) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; case SecurityActions.Synchronize: if (role.AllowSynchronize) AddRoleAlbumsToListIfNotPresent(role, allAlbumIds); break; } } } #endregion #region Step 2: Convert previous list to contain ONLY top-level albums // Step 2: Loop through our list of albums. If any album has an ancestor that is also in the list, then remove it. // We only want a list of top level albums. List<int> rootAlbumIds = new List<int>(allAlbumIds); List<int> albumIdsToRemove = new List<int>(rootAlbumIds.Count); foreach (int viewableAlbumId in allAlbumIds) { IGalleryObject album = LoadAlbumInstance(viewableAlbumId, false); while (true) { album = album.Parent as IAlbum; if (album == null) break; if (allAlbumIds.Contains(album.Id)) { albumIdsToRemove.Add(viewableAlbumId); break; } } } foreach (int albumId in albumIdsToRemove) { rootAlbumIds.Remove(albumId); } #endregion #region Step 3: Package results into an album container // Step 3: 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; 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 = CreateAlbumInstance(); rootAlbum.IsVirtualAlbum = true; rootAlbum.Title = Resources.Virtual_Album_Title; foreach (int albumId in rootAlbumIds) { rootAlbum.Add(LoadAlbumInstance(albumId, false)); } } #endregion return rootAlbum; }