89 lines
2.7 KiB
C#
89 lines
2.7 KiB
C#
using System.Net.Http.Json;
|
|
using System.Text.Json.Serialization;
|
|
using Microsoft.Extensions.Options;
|
|
using RecNet.Application.Common.Interfaces;
|
|
using RecNet.Application.Common.Steam;
|
|
using SteamApi.Models.Steam.Player;
|
|
using SteamApi.Models.Steam.Responses;
|
|
|
|
namespace RecNet.Infrastructure.Services.Steam;
|
|
|
|
public class SteamAuthService(
|
|
HttpClient httpClient,
|
|
IOptions<SteamOptions> options) : ISteamAuthService
|
|
{
|
|
private readonly SteamOptions _options = options.Value;
|
|
|
|
public async Task<SteamAuthResult> AuthorizeAsync(
|
|
string ticket,
|
|
uint appId,
|
|
CancellationToken ct = default)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ticket))
|
|
return SteamAuthResult.Failure();
|
|
|
|
if (appId != _options.AppId)
|
|
return SteamAuthResult.Failure();
|
|
|
|
var steamId = await AuthenticateTicketAsync(ticket, ct);
|
|
if (steamId is null)
|
|
return SteamAuthResult.Failure();
|
|
|
|
var profile = await GetProfileAsync(steamId, ct);
|
|
|
|
return SteamAuthResult.Success(
|
|
steamId,
|
|
profile?.PersonaName);
|
|
}
|
|
|
|
private async Task<string?> AuthenticateTicketAsync(
|
|
string ticket,
|
|
CancellationToken ct)
|
|
{
|
|
var url =
|
|
"ISteamUserAuth/AuthenticateUserTicket/v0001/" +
|
|
$"?key={Uri.EscapeDataString(_options.ApiKey)}" +
|
|
$"&appid={_options.AppId}" +
|
|
$"&ticket={Uri.EscapeDataString(ticket)}";
|
|
|
|
var response = await httpClient.GetAsync(url, ct);
|
|
if (!response.IsSuccessStatusCode)
|
|
return null;
|
|
|
|
var body = await response.Content.ReadFromJsonAsync<SteamResponse<SteamAuthResponse>>(
|
|
cancellationToken: ct);
|
|
|
|
return body?.Response?.Params?.SteamId;
|
|
}
|
|
|
|
private async Task<PlayerSummary?> GetProfileAsync(
|
|
string steamId,
|
|
CancellationToken ct)
|
|
{
|
|
var url =
|
|
"ISteamUser/GetPlayerSummaries/v0002/" +
|
|
$"?key={Uri.EscapeDataString(_options.ApiKey)}" +
|
|
$"&steamids={Uri.EscapeDataString(steamId)}";
|
|
|
|
var response = await httpClient.GetAsync(url, ct);
|
|
if (!response.IsSuccessStatusCode)
|
|
return null;
|
|
|
|
var body = await response.Content.ReadFromJsonAsync<SteamResponse<PlayerSummariesResponse>>(
|
|
cancellationToken: ct);
|
|
|
|
return body?.Response?.Players.FirstOrDefault();
|
|
}
|
|
|
|
private class SteamAuthResponse
|
|
{
|
|
[JsonPropertyName("params")]
|
|
public SteamAuthParamsResponse? Params { get; set; }
|
|
}
|
|
|
|
private class SteamAuthParamsResponse
|
|
{
|
|
[JsonPropertyName("steamid")]
|
|
public required string SteamId { get; set; }
|
|
}
|
|
} |