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

1
.gitignore vendored
View file

@ -2,3 +2,4 @@
**/obj/
**/target/
/build
/umogenkey.secret

View file

@ -1,4 +1,6 @@
# umogen
# Silly Integrated Unified System for Accounting and Contract Handling
**Working name:** umogen
An AI powered document generator.

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";
}

View file

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nyanlabs.Umogen.Core;
namespace Nyanlabs.Umogen.CoreTests;
public class AuthTests
{
[Fact]
public async Task TestTokenVerification()
{
// Given
var rootDir = Environment.CurrentDirectory.Replace("test/Nyanlabs.Umogen.CoreTests/bin/Debug/net8.0", "");
UmoEngine eng = new(Path.Combine(rootDir, Core.Umogen.DEFAULT_API_KEY_FILE));
// When
var result = await eng.ValidateKey();
// Then
Assert.True(result);
}
}