Ejemplo n.º 1
0
        /// <summary>
        /// <para> Checks if a user is authorized for the given song and activity. </para>
        /// This security check is intended to be used only to extend the default built-in
        /// checks of the .NET framework. For exmaple, if the activity of creating a new song
        /// is permitted to all logged-in users, then the built-in authorization check via
        /// the <see cref="AuthorizeAttribute"/> gets the job done without the need to use
        /// any additional checks. This method is relevant for cutomizing and fine-tunning
        /// the standard default checks, such as comparing the user id of the requested
        /// resource records and the current logged-in user id.
        /// </summary>
        /// <param name="song"> The requested song the user is trying to access. </param>
        /// <param name="authActivity"> The requested activity on the song (update/delete, etc.).</param>
        /// <param name="user"> The user to check against. </param>
        /// <returns> True if user is authorized, false otherwise. </returns>
        public static bool IsUserAuthorized(Song song, AuthorizationActivity authActivity, IPrincipal user)
        {
            // assure there is a concrete song to check
            if (song == null)
            {
                return(false);
            }

            // if current user is logged-in fetch it's id
            string userId = user?.Identity?.GetUserId();

            // check authorization for the requested activity
            switch (authActivity)
            {
            // Create - any logged in user can upload new songs for himself
            case AuthorizationActivity.Create:
                return(user?.Identity?.IsAuthenticated ?? false);

            // Display - either song is public or user is song owner or admin
            case AuthorizationActivity.Display:
                return(song.IsPublic || song.UserId.Equals(userId) || user.IsInRole(RoleName.Admin));

            // Update & Delete - only admins and song owners
            case AuthorizationActivity.Update:
            case AuthorizationActivity.Cancel:
            case AuthorizationActivity.Delete:
                return(user.IsInRole(RoleName.Admin) || song.UserId.Equals(userId));
            }

            // if we got here we missed some test, default the security check to deny the access
            return(false);
        }
Ejemplo n.º 2
0
 /// <inheritdoc cref="IsUserAuthorized(Song, AuthorizationActivity, IPrincipal)"/>
 public bool IsUserAuthorized(Song song, AuthorizationActivity authActivity)
 {
     // delegate authorization check to the static method with current user
     return(IsUserAuthorized(song, authActivity, User));
 }