Basic token authentication
This commit is contained in:
parent
70cb740715
commit
9cb901873d
5 changed files with 100 additions and 1 deletions
59
src/Nyanlabs.Umogen.Core/UmoEngine.cs
Normal file
59
src/Nyanlabs.Umogen.Core/UmoEngine.cs
Normal 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();
|
||||
}
|
||||
}
|
11
src/Nyanlabs.Umogen.Core/Umogen.cs
Normal file
11
src/Nyanlabs.Umogen.Core/Umogen.cs
Normal 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";
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue