// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the MIT license.
using System;
using System.Text;
using NuGet.Common;
using ILogger = NuGetCredentialProvider.Logging.ILogger;
namespace NuGetCredentialProvider.Util
{
///
/// Represents the set of extension methods used by this project.
///
internal static class ExtensionMethods
{
///
/// Writes a event message to the using the specified message.
///
/// A instance to write the message to.
/// The level to log at.
/// The message.
public static void Log(this ILogger logger, LogLevel logLevel, string message)
{
logger.Log(logLevel, true, message);
}
///
/// Writes a event message to the using the specified message.
///
/// A instance to write the message to.
/// The message.
public static void Error(this ILogger logger, string message)
{
logger.Log(LogLevel.Error, message);
}
///
/// Writes a event message to the using the specified message.
///
/// A instance to write the message to.
/// The message.
public static void Warning(this ILogger logger, string message)
{
logger.Log(LogLevel.Warning, message);
}
///
/// Writes a event message to the using the specified message.
///
/// A instance to write the message to.
/// The message.
public static void Minimal(this ILogger logger, string message)
{
logger.Log(LogLevel.Minimal, message);
}
///
/// Writes a event message to the using the specified message.
///
/// A instance to write the message to.
/// The message.
public static void Info(this ILogger logger, string message)
{
logger.Log(LogLevel.Information, message);
}
///
/// Writes a event message to the using the specified message.
///
/// A instance to write the message to.
/// The message.
public static void Verbose(this ILogger logger, string message)
{
logger.Log(LogLevel.Verbose, message);
}
///
/// Converts the current with just the host by discarding the other parts like path and querystrings.
///
/// The current to convert.
/// A with only the host.
public static Uri ToHostOnly(this Uri uri)
{
return uri.Segments.Length > 1
? new Uri($"{uri.Scheme}://{uri.Host}")
: uri;
}
///
/// Converts the current string to a JSON web access token (JWT) as a string.
///
/// The current access token as a string.
/// A JWT as a JSON string.
public static string ToJsonWebTokenString(this string accessToken)
{
// Effictively this splits by '.' and converts from a base-64 encoded string. Splitting creates new strings so this just calculates
// a substring instead to reduce memory overhead.
int start = accessToken.IndexOf(".", StringComparison.Ordinal) + 1;
if (start < 0)
{
return null;
}
int length = accessToken.IndexOf(".", start, StringComparison.Ordinal) - start;
return start > 0 && length < accessToken.Length
? Encoding.UTF8.GetString(
Convert.FromBase64String(
accessToken.Substring(start, length)
.PadRight(length + (length % 4), '=')))
: null;
}
}
}