Move API authentication logic into DatabaseContext partial class (#906)

Move API authentication method into DatabaseContext partial class
This commit is contained in:
Molly Phillips 2023-09-28 15:37:48 -04:00 committed by GitHub
parent 19ce2e5662
commit c186715a3f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 8 deletions

View file

@ -1,4 +1,3 @@
#nullable enable
using LBPUnion.ProjectLighthouse.Database; using LBPUnion.ProjectLighthouse.Database;
using LBPUnion.ProjectLighthouse.Extensions; using LBPUnion.ProjectLighthouse.Extensions;
using LBPUnion.ProjectLighthouse.Helpers; using LBPUnion.ProjectLighthouse.Helpers;
@ -66,7 +65,7 @@ public class UserEndpoints : ApiEndpointController
{ {
List<ApiUser> users = (await this.database.Users List<ApiUser> users = (await this.database.Users
.Where(u => u.PermissionLevel != PermissionLevel.Banned && u.Username.Contains(query)) .Where(u => u.PermissionLevel != PermissionLevel.Banned && u.Username.Contains(query))
.Where(u => u.ProfileVisibility == PrivacyType.All) // TODO: change check for when user is logged in .Where(u => u.ProfileVisibility == PrivacyType.All)
.OrderByDescending(b => b.UserId) .OrderByDescending(b => b.UserId)
.Take(20) .Take(20)
.ToListAsync()).ToSerializableList(ApiUser.CreateFromEntity); .ToListAsync()).ToSerializableList(ApiUser.CreateFromEntity);
@ -99,12 +98,7 @@ public class UserEndpoints : ApiEndpointController
if (!Configuration.ServerConfiguration.Instance.Authentication.RegistrationEnabled) if (!Configuration.ServerConfiguration.Instance.Authentication.RegistrationEnabled)
return this.NotFound(); return this.NotFound();
string? authHeader = this.Request.Headers["Authorization"]; ApiKeyEntity? apiKey = this.database.ApiKeyFromWebRequest(this.Request);
if (string.IsNullOrWhiteSpace(authHeader)) return this.NotFound();
string authToken = authHeader[(authHeader.IndexOf(' ') + 1)..];
ApiKeyEntity? apiKey = await this.database.APIKeys.FirstOrDefaultAsync(k => k.Key == authToken);
if (apiKey == null) return this.StatusCode(403); if (apiKey == null) return this.StatusCode(403);
if (!string.IsNullOrWhiteSpace(username)) if (!string.IsNullOrWhiteSpace(username))

View file

@ -0,0 +1,20 @@
#nullable enable
using System.Linq;
using LBPUnion.ProjectLighthouse.Types.Entities.Token;
using Microsoft.AspNetCore.Http;
namespace LBPUnion.ProjectLighthouse.Database;
public partial class DatabaseContext
{
public ApiKeyEntity? ApiKeyFromWebRequest(HttpRequest request)
{
string? authHeader = request.Headers["Authorization"];
if (string.IsNullOrWhiteSpace(authHeader)) return null;
string authToken = authHeader[(authHeader.IndexOf(' ') + 1)..];
ApiKeyEntity? apiKey = this.APIKeys.FirstOrDefault(k => k.Key == authToken);
return apiKey ?? null;
}
}