/* * SPDX-License-Identifier: AGPL-3.0-or-later * Copyright (C) 2025 Sergej Görzen * This file is part of OmiLAXR. */ using System; using System.Text; using OmiLAXR.Utils; using UnityEngine; using UnityEngine.Serialization; namespace OmiLAXR.Endpoints { /// /// Abstract base class for endpoints using Basic Authentication. /// Provides credential management and validation for sending statements. /// public abstract class BasicAuthEndpoint : Endpoint { /// /// Generates a basic authentication header string from the provided credentials. /// /// The username to be used for authentication /// The password to be used for authentication /// A basic authentication header string public static string GetAuth(string username, string password) => "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")); /// /// Stores the basic authentication credentials. /// Uses [FormerlySerializedAs] to maintain compatibility with previous serialization. /// Defaults to a preset LRS endpoint if no credentials are provided. /// [FormerlySerializedAs("_credentials")] [SerializeField] private BasicAuthCredentials credentials = DefaultCredentials; public static BasicAuthCredentials DefaultCredentials => new BasicAuthCredentials( "https://lrs.elearn.rwth-aachen.de/data/xAPI", // Default LRS endpoint "", // Default empty username "" // Default empty password ); /// /// Overrides the base HandleQueue method to first validate credentials. /// Prevents statement sending if credentials are invalid. /// /// /// TransferCode.InvalidCredentials if credentials are not valid, /// otherwise delegates to base class implementation /// protected override TransferCode HandleQueue() { // Check if credentials are valid before processing queue return !credentials.IsValid ? TransferCode.InvalidCredentials : base.HandleQueue(); } /// /// Provides get and set access to the authentication credentials. /// Allows dynamic configuration of endpoint credentials. /// public BasicAuthCredentials Credentials => credentials; /// /// /// /// public void SetAuthConfig(BasicAuthCredentials c) { credentials = c; } /// /// /// /// /// /// public void SetAuthConfig(string endpoint, string username, string password) { credentials = new BasicAuthCredentials(endpoint, username, password); } public override void ConsumeDataMap(DataMap map) { credentials.endpoint = map["endpoint"] as string; credentials.username = map["username"] as string; credentials.password = map["password"] as string; } public override DataMap ProvideDataMap() { return new DataMap() { ["endpoint"] = credentials.endpoint, ["username"] = credentials.username, ["password"] = credentials.password }; } } }