Make extension method for authentication errors

This commit is contained in:
Jordan Dominion
2024-09-24 18:14:48 -04:00
parent 89770a6121
commit 4ccc773e1b
2 changed files with 31 additions and 16 deletions
@@ -1,6 +1,5 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
@@ -73,20 +72,6 @@ namespace Tgstation.Server.Client.GraphQL
static void ThrowOtherCallerFailedAuthException()
=> throw new AuthenticationException("Another caller failed to authenticate!");
/// <summary>
/// Checks if a given <paramref name="operationResult"/> errored out with authentication errors.
/// </summary>
/// <param name="operationResult">The <see cref="IOperationResult"/>.</param>
/// <returns><see langword="true"/> if <paramref name="operationResult"/> errored due to authentication issues, <see langword="false"/> otherwise.</returns>
static bool IsAuthenticationError(IOperationResult operationResult)
=> operationResult.Data == null
&& operationResult.Errors.Any(
error => error.Extensions?.TryGetValue(
"code",
out object? codeExtension) == true
&& codeExtension is string codeExtensionString
&& codeExtensionString == "AUTH_NOT_AUTHENTICATED");
/// <summary>
/// Initializes a new instance of the <see cref="GraphQLServerClient"/> class.
/// </summary>
@@ -243,7 +228,7 @@ namespace Tgstation.Server.Client.GraphQL
var operationResult = await operationExecutor(graphQLClient);
if (IsAuthenticationError(operationResult))
if (operationResult.IsAuthenticationError())
{
currentAuthHeader = await Reauthenticate(currentAuthHeader, cancellationToken).ConfigureAwait(false);
setAuthenticationHeader(currentAuthHeader);
@@ -0,0 +1,30 @@
using System;
using System.Linq;
using StrawberryShake;
namespace Tgstation.Server.Client.GraphQL
{
/// <summary>
/// Extension methods for the <see cref="IOperationResult"/> interface.
/// </summary>
public static class OperationResultExtensions
{
/// <summary>
/// Checks if a given <paramref name="operationResult"/> errored out with authentication errors.
/// </summary>
/// <param name="operationResult">The <see cref="IOperationResult"/>.</param>
/// <returns><see langword="true"/> if <paramref name="operationResult"/> errored due to authentication issues, <see langword="false"/> otherwise.</returns>
public static bool IsAuthenticationError(this IOperationResult operationResult)
{
ArgumentNullException.ThrowIfNull(operationResult);
return operationResult.Errors.Any(
error => error.Extensions?.TryGetValue(
"code",
out object? codeExtension) == true
&& codeExtension is string codeExtensionString
&& codeExtensionString == "AUTH_NOT_AUTHENTICATED");
}
}
}