Basic token authentication

This commit is contained in:
femsci 2023-11-17 20:18:16 +01:00
parent 70cb740715
commit 9cb901873d
Signed by: femsci
GPG key ID: 08F7911F0E650C67
5 changed files with 100 additions and 1 deletions

View file

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Nyanlabs.Umogen.Core;
public class UmoEngine : IDisposable
{
public UmoEngine(string? apiKey = null, bool isFilePath = true)
{
if (isFilePath)
{
apiKey ??= Umogen.DEFAULT_API_KEY_FILE;
if (!File.Exists(apiKey))
{
throw new ArgumentException($"No such file: {apiKey}");
}
string contents = File.ReadAllText(apiKey).Trim();
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new ArgumentException($"File {apiKey} is empty.");
}
apiKey = contents;
}
else
{
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new ArgumentException("API key cannot be empty", nameof(apiKey));
}
}
apiKey = apiKey.Trim();
_http = new()
{
BaseAddress = new Uri("https://api.openai.com/v1/")
};
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
}
private readonly HttpClient _http;
public async Task<bool> ValidateKey()
{
//Use the 'models' endpoint for auth
var resp = await _http.GetAsync("models", HttpCompletionOption.ResponseHeadersRead);
return resp.IsSuccessStatusCode;
}
public void Dispose()
{
GC.SuppressFinalize(this);
_http.Dispose();
}
}

View file

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nyanlabs.Umogen.Core;
public class Umogen
{
public const string DEFAULT_API_KEY_FILE = "umogenkey.secret";
}