tgstation-server 6.19.0
The /tg/station 13 server suite
Loading...
Searching...
No Matches
AuthorizationHelper.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6
7using HotChocolate;
8
9using Microsoft.AspNetCore.Authorization;
10
12
14{
19 {
25 public static GraphQLException ForbiddenGraphQLException(this AuthorizationFailure authorizationFailure)
26 {
27 ArgumentNullException.ThrowIfNull(authorizationFailure);
28
29 var messageBuilder = new StringBuilder("The current user is not authorized to access this resource.");
30
31 foreach (var failureReason in authorizationFailure.FailureReasons)
32 {
33 messageBuilder.AppendLine();
34 messageBuilder.Append("\t- ");
35 messageBuilder.Append(failureReason.Message);
36 }
37
38 return new(ErrorBuilder.New()
39 .SetMessage(messageBuilder.ToString()) // Copied from graphql-platform: AuthorizeMiddleware.cs
40 .SetCode(ErrorCodes.Authentication.NotAuthorized)
41 .Build());
42 }
43
51 public static async ValueTask CheckGraphQLAuthorized(
52 this Security.IAuthorizationService authorizationService,
53 IEnumerable<IAuthorizationRequirement>? authorizationRequirements,
54 bool excludeUserSessionValidRequirement = false)
55 {
56 ArgumentNullException.ThrowIfNull(authorizationService);
57 ArgumentNullException.ThrowIfNull(authorizationRequirements);
58
59 if (!excludeUserSessionValidRequirement)
60 authorizationRequirements = UserSessionValidRequirement.InstanceAsEnumerable.Concat(authorizationRequirements);
61
62 var result = await authorizationService.AuthorizeAsync(authorizationRequirements);
63 if (!result.Succeeded)
64 throw result.Failure.ForbiddenGraphQLException();
65 }
66 }
67}
Helper for authorization functionality related to GraphQL.
static GraphQLException ForbiddenGraphQLException(this AuthorizationFailure authorizationFailure)
Create a new GraphQLException to be thrown when a forbidden error occurs.
static async ValueTask CheckGraphQLAuthorized(this Security.IAuthorizationService authorizationService, IEnumerable< IAuthorizationRequirement >? authorizationRequirements, bool excludeUserSessionValidRequirement=false)
Evaluate a given set of authorizationRequirements , throwing the approriate GraphQLException on failu...
IAuthorizationRequirement for testing if a user is enabled and their session is valid.
static IEnumerable< UserSessionValidRequirement > InstanceAsEnumerable
The singleton instance of this class.