56 lines
1.9 KiB
C#
56 lines
1.9 KiB
C#
using System.Net.Http;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace UtopiaCanteenSystem.Services;
|
|
|
|
/// <summary>
|
|
/// Admin authentication service via UIND portal API (plain-text response).
|
|
/// </summary>
|
|
public class AuthService : IAuthService
|
|
{
|
|
private static readonly HttpClient HttpClient = new();
|
|
private readonly string _baseUrl;
|
|
|
|
public AuthService(string authenticationUrl)
|
|
{
|
|
_baseUrl = (authenticationUrl ?? string.Empty).Trim();
|
|
if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/"))
|
|
_baseUrl += "/";
|
|
}
|
|
|
|
public async Task<AuthResult> LoginAsync(string username, string password, CancellationToken cancellationToken = default)
|
|
{
|
|
var user = username?.Trim() ?? string.Empty;
|
|
var pass = password ?? string.Empty;
|
|
if (string.IsNullOrWhiteSpace(_baseUrl))
|
|
return new AuthResult(false, string.Empty);
|
|
|
|
if (string.IsNullOrWhiteSpace(user) || string.IsNullOrEmpty(pass))
|
|
return new AuthResult(false, string.Empty);
|
|
|
|
// Build URL:
|
|
// {baseUrl}{username}/{password}
|
|
// Must URL-encode both values.
|
|
var url = $"{_baseUrl}{Uri.EscapeDataString(user)}/{Uri.EscapeDataString(pass)}";
|
|
|
|
try
|
|
{
|
|
using var resp = await HttpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
|
|
var body = (await resp.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false)).Trim();
|
|
|
|
// Portal returns plain text:
|
|
// "NOT FOUND" => failure
|
|
// otherwise => success and body contains EmployeeId (or user identifier)
|
|
if (body.Equals("NOT FOUND", StringComparison.OrdinalIgnoreCase))
|
|
return new AuthResult(false, string.Empty);
|
|
|
|
return new AuthResult(true, body);
|
|
}
|
|
catch
|
|
{
|
|
return new AuthResult(false, string.Empty);
|
|
}
|
|
}
|
|
}
|