using System.Globalization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Security;
namespace Titano.Server.Api;
/// /api/v1/auth: sign-in (token or admin cookie), sign-out, password change, current account.
public static class AuthEndpoints
{
public static void Map(RouteGroupBuilder api)
{
api.MapPost("/auth/login", LoginAsync).AllowAnonymousCaller();
api.MapPost("/auth/logout", LogoutAsync).AllowDuringPasswordChange();
api.MapPost("/auth/password", ChangePasswordAsync).AllowDuringPasswordChange();
api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange();
}
///
/// Why the Secure session cookie cannot be set for this request, or null when it can (HTTPS, or the machine
/// itself). In TLS mode proxy only a trusted proxy makes a request HTTPS, so the refusal names that setting.
///
internal static string? CookieRefusal(HttpContext context, ServerOptions options)
{
if (SessionCookies.IsSecureTransport(context)) return null;
return options.TlsMode == TlsMode.Proxy ? "proxy_untrusted" : "https_required";
}
private static async Task LoginAsync(HttpContext context, LoginRequest request, TitanoDatabase db, TokenService tokens, LoginGuard guard,
AuditLog audit, TimeProvider time, ServerOptions options)
{
var ct = context.RequestAborted;
if (!guard.TryAttempt(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", out var wait)) return TooMany(context, "rate_limited", wait);
var account = Accounts.Key(request.Username);
if (!Accounts.IsValidUsername(account) || string.IsNullOrEmpty(request.Password))
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
if (guard.IsLocked(account, out wait)) return TooMany(context, "account_locked", wait);
if (request.Cookie && CookieRefusal(context, options) is { } refusal) return ApiErrors.BadRequest(context, refusal);
var user = await db.Users.GetByUsernameAsync(account, ct);
bool valid;
if (user is null)
{
PasswordHasher.VerifyDummy(request.Password);
valid = false;
}
else
{
valid = PasswordHasher.Verify(request.Password, user.PasswordHash) && !user.Disabled;
}
if (!valid)
{
guard.RecordFailure(account);
await audit.WriteAsync(user?.Id, account, context, "login_failed", "user", user?.Id.ToString());
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
}
guard.RecordSuccess(account);
var signedIn = user! with { LastLogin = time.GetUtcNow() };
if (PasswordHasher.NeedsRehash(signedIn.PasswordHash))
{
signedIn = signedIn with { PasswordHash = PasswordHasher.Hash(request.Password) };
await db.Users.UpdateAsync(signedIn, ct);
}
else
{
await db.Users.RecordLoginAsync(signedIn.Id, signedIn.LastLogin.Value, ct);
}
var issued = await tokens.IssueAsync(signedIn, request.ClientName, ct);
await audit.WriteAsync(signedIn.Id, signedIn.Username, context, "login", "user", signedIn.Id.ToString(), issued.Stored.ClientName);
string? secret = issued.Secret;
if (request.Cookie)
{
// The admin panel never sees the token itself; it travels only in the HttpOnly cookie.
SessionCookies.Issue(context, issued);
secret = null;
}
return Results.Json(new LoginResponse(secret, Dto.User(signedIn), signedIn.MustChangePassword, issued.Stored.Expires), ProtocolJson.Default.LoginResponse);
}
private static async Task LogoutAsync(HttpContext context, Caller caller, TitanoDatabase db)
{
await db.Tokens.RevokeAsync(caller.TokenHash, context.RequestAborted);
if (caller.Source == CredentialSource.Cookie) SessionCookies.Clear(context);
return Results.NoContent();
}
private static async Task ChangePasswordAsync(HttpContext context, Caller caller, ChangePasswordRequest request, TitanoDatabase db,
AuditLog audit, ServerOptions options)
{
var ct = context.RequestAborted;
if (string.IsNullOrEmpty(request.CurrentPassword) || !PasswordHasher.Verify(request.CurrentPassword, caller.User.PasswordHash))
return ApiErrors.BadRequest(context, "wrong_password");
if (!PasswordHasher.IsAcceptable(request.NewPassword))
return ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength);
if (request.NewPassword == request.CurrentPassword) return ApiErrors.BadRequest(context, "same_password");
var updated = caller.User with { PasswordHash = PasswordHasher.Hash(request.NewPassword), MustChangePassword = false };
await db.Users.UpdateAsync(updated, ct);
await db.Tokens.RevokeAllExceptAsync(caller.Id, caller.TokenHash, ct);
await audit.WriteAsync(caller, context, "password_changed", "user", caller.Id.ToString());
if (caller.User.Role == UserRole.Admin) AdminBootstrap.ForgetInitialPassword(options);
return Results.NoContent();
}
private static IResult TooMany(HttpContext context, string code, TimeSpan wait)
{
var seconds = Math.Max(1, (int)Math.Ceiling(wait.TotalSeconds));
context.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture);
return ApiErrors.Result(context, StatusCodes.Status429TooManyRequests, code, seconds.ToString(CultureInfo.InvariantCulture));
}
}