Add MedMind recovery and Steam authentication

This commit is contained in:
hz
2026-07-16 00:24:07 -05:00
parent 0ca7a31daa
commit bf6f86b73c
14 changed files with 556 additions and 8 deletions
+37
View File
@@ -0,0 +1,37 @@
using System.Net;
using System.Net.Mail;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace GameAuthApi.Services;
public class EmailService
{
private readonly IConfiguration _config;
public EmailService(IConfiguration config) => _config = config;
public virtual async Task SendPasswordResetCodeAsync(string recipient, string code)
{
var host = _config["Email:SmtpHost"];
var sender = _config["Email:Sender"];
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(sender))
throw new InvalidOperationException("SMTP email delivery is not configured.");
using var message = new MailMessage(sender, recipient)
{
Subject = "Your MedMind password reset code",
Body = $"Your MedMind verification code is {code}. It expires in 15 minutes. If you did not request this, you can ignore this email.",
IsBodyHtml = false
};
using var client = new SmtpClient(host, int.TryParse(_config["Email:SmtpPort"], out var port) ? port : 587)
{
EnableSsl = !bool.TryParse(_config["Email:UseTls"], out var tls) || tls
};
var username = _config["Email:Username"];
if (!string.IsNullOrWhiteSpace(username))
client.Credentials = new NetworkCredential(username, _config["Email:Password"]);
await client.SendMailAsync(message);
}
}
+57
View File
@@ -0,0 +1,57 @@
using System.Security.Cryptography;
using GameAuthApi.Models;
using MongoDB.Driver;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace GameAuthApi.Services;
public class PasswordResetService
{
private readonly IMongoCollection<PasswordResetChallenge> _challenges;
public PasswordResetService(IConfiguration config)
{
var client = new MongoClient(config["MongoDB:ConnectionString"]);
var database = client.GetDatabase(config["MongoDB:DatabaseName"]);
_challenges = database.GetCollection<PasswordResetChallenge>("PasswordResetChallenges");
}
public virtual async Task<string> CreateAsync(string userId)
{
await _challenges.UpdateManyAsync(x => x.UserId == userId && !x.Used,
Builders<PasswordResetChallenge>.Update.Set(x => x.Used, true));
var code = RandomNumberGenerator.GetInt32(0, 1_000_000).ToString("D6");
await _challenges.InsertOneAsync(new PasswordResetChallenge
{
UserId = userId,
CodeHash = BCrypt.Net.BCrypt.HashPassword(code),
CreatedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.AddMinutes(15)
});
return code;
}
public virtual async Task<bool> ConsumeAsync(string userId, string code)
{
var challenge = await _challenges.Find(x => x.UserId == userId && !x.Used && x.ExpiresUtc > DateTime.UtcNow)
.SortByDescending(x => x.CreatedUtc).FirstOrDefaultAsync();
if (challenge == null || challenge.FailedAttempts >= 5)
return false;
if (!BCrypt.Net.BCrypt.Verify(code, challenge.CodeHash))
{
await _challenges.UpdateOneAsync(x => x.Id == challenge.Id,
Builders<PasswordResetChallenge>.Update.Inc(x => x.FailedAttempts, 1));
return false;
}
await _challenges.UpdateOneAsync(x => x.Id == challenge.Id,
Builders<PasswordResetChallenge>.Update.Set(x => x.Used, true));
return true;
}
public async Task EnsureIndexesAsync() => await _challenges.Indexes.CreateOneAsync(
new CreateIndexModel<PasswordResetChallenge>(
Builders<PasswordResetChallenge>.IndexKeys.Ascending(x => x.ExpiresUtc),
new CreateIndexOptions { ExpireAfter = TimeSpan.Zero, Name = "password_reset_ttl" }));
}
+111
View File
@@ -0,0 +1,111 @@
using System.Security.Cryptography;
using GameAuthApi.Models;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
namespace GameAuthApi.Services;
public class SteamAuthService
{
private const string Provider = "steam";
private readonly IMongoCollection<SteamAuthTransaction> _transactions;
private readonly IMongoCollection<ExternalIdentityLink> _links;
private readonly IConfiguration _config;
private readonly HttpClient _http;
public SteamAuthService(IConfiguration config, IHttpClientFactory factory)
{
_config = config;
_http = factory.CreateClient();
var client = new MongoClient(config["MongoDB:ConnectionString"]);
var database = client.GetDatabase(config["MongoDB:DatabaseName"]);
_transactions = database.GetCollection<SteamAuthTransaction>("SteamAuthTransactions");
_links = database.GetCollection<ExternalIdentityLink>("ExternalIdentityLinks");
}
public virtual async Task<(SteamAuthTransaction Transaction, string AuthUrl)> StartAsync()
{
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
var transaction = new SteamAuthTransaction { Id = id, CreatedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(10) };
await _transactions.InsertOneAsync(transaction);
var baseUrl = (_config["Auth:PublicBaseUrl"] ?? "https://pauth.ranaze.com").TrimEnd('/');
var returnTo = $"{baseUrl}/api/Auth/steam/callback?transactionId={Uri.EscapeDataString(id)}";
var realm = baseUrl + "/";
var query = new Dictionary<string, string>
{
["openid.ns"] = "http://specs.openid.net/auth/2.0",
["openid.mode"] = "checkid_setup",
["openid.return_to"] = returnTo,
["openid.realm"] = realm,
["openid.identity"] = "http://specs.openid.net/auth/2.0/identifier_select",
["openid.claimed_id"] = "http://specs.openid.net/auth/2.0/identifier_select"
};
var authUrl = "https://steamcommunity.com/openid/login?" + string.Join("&", query.Select(x => $"{Uri.EscapeDataString(x.Key)}={Uri.EscapeDataString(x.Value)}"));
return (transaction, authUrl);
}
public virtual async Task<SteamAuthTransaction> GetAsync(string id) =>
await _transactions.Find(x => x.Id == id && x.ExpiresUtc > DateTime.UtcNow).FirstOrDefaultAsync();
public virtual async Task<bool> VerifyCallbackAsync(string transactionId, IQueryCollection query)
{
var transaction = await GetAsync(transactionId);
if (transaction == null) return false;
var payload = query.Where(x => x.Key.StartsWith("openid.")).ToDictionary(x => x.Key, x => x.Value.ToString());
payload["openid.mode"] = "check_authentication";
using var response = await _http.PostAsync("https://steamcommunity.com/openid/login", new FormUrlEncodedContent(payload));
var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode || !result.Contains("is_valid:true", StringComparison.Ordinal)) return false;
var claimed = query["openid.claimed_id"].ToString();
const string prefix = "https://steamcommunity.com/openid/id/";
if (!claimed.StartsWith(prefix, StringComparison.Ordinal) || !claimed[prefix.Length..].All(char.IsDigit)) return false;
var steamId = claimed[prefix.Length..];
var link = await _links.Find(x => x.Provider == Provider && x.Subject == steamId).FirstOrDefaultAsync();
await _transactions.UpdateOneAsync(x => x.Id == transactionId,
Builders<SteamAuthTransaction>.Update
.Set(x => x.SteamId, steamId)
.Set(x => x.UserId, link?.UserId)
.Set(x => x.Status, link == null ? "requires_account" : "authenticated"));
return true;
}
public virtual async Task LinkAsync(string transactionId, string userId)
{
var transaction = await GetAsync(transactionId) ?? throw new InvalidOperationException("Steam transaction expired.");
if (transaction.Status != "requires_account" || string.IsNullOrWhiteSpace(transaction.SteamId))
throw new InvalidOperationException("Steam transaction is not ready.");
await _links.InsertOneAsync(new ExternalIdentityLink
{
Provider = Provider, Subject = transaction.SteamId, UserId = userId, CreatedUtc = DateTime.UtcNow
});
await _transactions.UpdateOneAsync(x => x.Id == transactionId,
Builders<SteamAuthTransaction>.Update.Set(x => x.UserId, userId).Set(x => x.Status, "authenticated"));
}
public virtual async Task CompleteAsync(string transactionId, User user, string accessToken, string refreshToken)
{
await _transactions.UpdateOneAsync(x => x.Id == transactionId,
Builders<SteamAuthTransaction>.Update
.Set(x => x.Status, "complete")
.Set(x => x.AccessToken, accessToken)
.Set(x => x.RefreshToken, refreshToken)
.Set(x => x.Username, user.Username)
.Set(x => x.Role, user.Role));
}
public async Task EnsureIndexesAsync()
{
await _transactions.Indexes.CreateOneAsync(new CreateIndexModel<SteamAuthTransaction>(
Builders<SteamAuthTransaction>.IndexKeys.Ascending(x => x.ExpiresUtc),
new CreateIndexOptions { ExpireAfter = TimeSpan.Zero, Name = "steam_transaction_ttl" }));
await _links.Indexes.CreateOneAsync(new CreateIndexModel<ExternalIdentityLink>(
Builders<ExternalIdentityLink>.IndexKeys.Ascending(x => x.Provider).Ascending(x => x.Subject),
new CreateIndexOptions { Unique = true, Name = "external_identity_unique" }));
}
}
+61 -3
View File
@@ -3,6 +3,8 @@ using System.Threading.Tasks;
using GameAuthApi.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using System;
using System.Linq;
namespace GameAuthApi.Services;
@@ -20,6 +22,19 @@ public class UserService
public virtual async Task<User> GetByUsernameAsync(string username) =>
await _users.Find(u => u.Username == username).FirstOrDefaultAsync();
public virtual async Task<User> GetByLoginAsync(string login)
{
var normalized = Normalize(login);
return await _users.Find(u =>
u.NormalizedUsername == normalized ||
u.NormalizedEmail == normalized ||
u.Username == login ||
u.Email == login).FirstOrDefaultAsync();
}
public virtual async Task<User> GetByIdAsync(string id) =>
await _users.Find(u => u.Id == id).FirstOrDefaultAsync();
public virtual async Task<List<User>> GetAllAsync() =>
await _users.Find(_ => true).ToListAsync();
@@ -29,9 +44,52 @@ public class UserService
return result.DeletedCount > 0;
}
public virtual async Task CreateAsync(User user) =>
public virtual async Task CreateAsync(User user)
{
ApplyNormalizedFields(user);
await _users.InsertOneAsync(user);
}
public virtual async Task UpdateAsync(User user) =>
public virtual async Task UpdateAsync(User user)
{
ApplyNormalizedFields(user);
await _users.ReplaceOneAsync(u => u.Id == user.Id, user);
}
}
public virtual async Task EnsureIndexesAsync()
{
var username = new CreateIndexModel<User>(
Builders<User>.IndexKeys.Ascending(u => u.NormalizedUsername),
new CreateIndexOptions { Unique = true, Sparse = true, Name = "normalized_username_unique" });
var email = new CreateIndexModel<User>(
Builders<User>.IndexKeys.Ascending(u => u.NormalizedEmail),
new CreateIndexOptions { Unique = true, Sparse = true, Name = "normalized_email_unique" });
await _users.Indexes.CreateManyAsync(new[] { username, email });
}
public virtual async Task BackfillNormalizedFieldsAsync()
{
var users = await _users.Find(_ => true).ToListAsync();
var duplicateUsername = users.GroupBy(u => Normalize(u.Username)).FirstOrDefault(g => g.Key != string.Empty && g.Count() > 1);
var duplicateEmail = users.Where(u => !string.IsNullOrWhiteSpace(u.Email)).GroupBy(u => Normalize(u.Email)).FirstOrDefault(g => g.Count() > 1);
if (duplicateUsername != null || duplicateEmail != null)
throw new InvalidOperationException("Duplicate normalized usernames or emails must be resolved before starting the authentication service.");
foreach (var user in users)
{
var normalizedUsername = Normalize(user.Username);
var normalizedEmail = string.IsNullOrWhiteSpace(user.Email) ? null : Normalize(user.Email);
if (user.NormalizedUsername == normalizedUsername && user.NormalizedEmail == normalizedEmail) continue;
user.NormalizedUsername = normalizedUsername;
user.NormalizedEmail = normalizedEmail;
await _users.ReplaceOneAsync(u => u.Id == user.Id, user);
}
}
public static string Normalize(string value) => value?.Trim().ToUpperInvariant() ?? string.Empty;
private static void ApplyNormalizedFields(User user)
{
user.NormalizedUsername = Normalize(user.Username);
user.NormalizedEmail = string.IsNullOrWhiteSpace(user.Email) ? null : Normalize(user.Email);
}
}