feat: auth
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using MemeVault.Api.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace MemeVault.Api.Auth;
|
||||
|
||||
public sealed class JwtTokenService(IOptions<JwtOptions> options)
|
||||
{
|
||||
public string IssueToken(long telegramUserId, string? username)
|
||||
{
|
||||
var opt = options.Value;
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(opt.SecretKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(JwtRegisteredClaimNames.Sub, telegramUserId.ToString()),
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
claims.Add(new Claim(JwtRegisteredClaimNames.Name, username));
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: opt.Issuer,
|
||||
audience: opt.Audience,
|
||||
claims: claims,
|
||||
notBefore: DateTime.UtcNow,
|
||||
expires: DateTime.UtcNow.AddHours(opt.ExpiryHours),
|
||||
signingCredentials: creds);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using MemeVault.Api.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MemeVault.Api.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Валидирует initData, которую Telegram передаёт в Mini App.
|
||||
/// Алгоритм: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
|
||||
/// </summary>
|
||||
public sealed class TelegramInitDataValidator(IOptions<TelegramOptions> options)
|
||||
{
|
||||
// Максимальный возраст initData. Telegram рекомендует проверять свежесть.
|
||||
private static readonly TimeSpan MaxAge = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет подпись initData и извлекает Telegram userId и username.
|
||||
/// Возвращает false если подпись не верна или данные устарели.
|
||||
/// </summary>
|
||||
public bool TryValidate(string initData, out long userId, out string? username)
|
||||
{
|
||||
userId = 0;
|
||||
username = null;
|
||||
|
||||
var pairs = ParseQueryString(initData);
|
||||
|
||||
if (!pairs.TryGetValue("hash", out var receivedHash))
|
||||
return false;
|
||||
|
||||
// Строка для проверки: все поля кроме hash, отсортированные по ключу
|
||||
var dataCheckString = string.Join('\n',
|
||||
pairs
|
||||
.Where(p => p.Key != "hash")
|
||||
.OrderBy(p => p.Key)
|
||||
.Select(p => $"{p.Key}={p.Value}"));
|
||||
|
||||
// secret_key = HMAC-SHA256("WebAppData", botToken)
|
||||
var secretKey = HMACSHA256.HashData(
|
||||
Encoding.UTF8.GetBytes("WebAppData"),
|
||||
Encoding.UTF8.GetBytes(options.Value.BotToken));
|
||||
|
||||
// expected_hash = HMAC-SHA256(secret_key, dataCheckString)
|
||||
var expectedHash = HMACSHA256.HashData(
|
||||
secretKey,
|
||||
Encoding.UTF8.GetBytes(dataCheckString));
|
||||
|
||||
var expectedHex = Convert.ToHexString(expectedHash).ToLowerInvariant();
|
||||
|
||||
// Constant-time сравнение
|
||||
if (!CryptographicOperations.FixedTimeEquals(
|
||||
Encoding.UTF8.GetBytes(expectedHex),
|
||||
Encoding.UTF8.GetBytes(receivedHash)))
|
||||
return false;
|
||||
|
||||
// Проверка свежести
|
||||
if (!pairs.TryGetValue("auth_date", out var authDateStr) ||
|
||||
!long.TryParse(authDateStr, out var authDateUnix))
|
||||
return false;
|
||||
|
||||
var authDate = DateTimeOffset.FromUnixTimeSeconds(authDateUnix);
|
||||
if (DateTimeOffset.UtcNow - authDate > MaxAge)
|
||||
return false;
|
||||
|
||||
// Извлекаем user JSON
|
||||
if (!pairs.TryGetValue("user", out var userJson))
|
||||
return false;
|
||||
|
||||
using var doc = JsonDocument.Parse(userJson);
|
||||
var root = doc.RootElement;
|
||||
|
||||
if (!root.TryGetProperty("id", out var idProp))
|
||||
return false;
|
||||
|
||||
userId = idProp.GetInt64();
|
||||
username = root.TryGetProperty("username", out var uProp)
|
||||
? uProp.GetString()
|
||||
: null;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> ParseQueryString(string query)
|
||||
{
|
||||
var result = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var part in query.Split('&'))
|
||||
{
|
||||
var eq = part.IndexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
var key = Uri.UnescapeDataString(part[..eq]);
|
||||
var val = Uri.UnescapeDataString(part[(eq + 1)..]);
|
||||
result[key] = val;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using MemeVault.Api.Auth;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace MemeVault.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public sealed class AuthController(
|
||||
TelegramInitDataValidator validator,
|
||||
JwtTokenService jwt) : ControllerBase
|
||||
{
|
||||
[AllowAnonymous]
|
||||
[HttpPost("telegram")]
|
||||
public IActionResult Telegram([FromBody] TelegramAuthRequest request)
|
||||
{
|
||||
if (!validator.TryValidate(request.InitData, out var userId, out var username))
|
||||
return Unauthorized();
|
||||
|
||||
var token = jwt.IssueToken(userId, username);
|
||||
return Ok(new { token });
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record TelegramAuthRequest(string InitData);
|
||||
@@ -23,4 +23,9 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.4.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace MemeVault.Api.Options;
|
||||
|
||||
public sealed class JwtOptions
|
||||
{
|
||||
public const string Section = "Jwt";
|
||||
|
||||
public string SecretKey { get; set; } = string.Empty;
|
||||
public string Issuer { get; set; } = "memevault-api";
|
||||
public string Audience { get; set; } = "memevault-miniapp";
|
||||
public int ExpiryHours { get; set; } = 24;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace MemeVault.Api.Options;
|
||||
|
||||
public sealed class TelegramOptions
|
||||
{
|
||||
public const string Section = "Telegram";
|
||||
|
||||
/// <summary>Bot token — нужен для валидации HMAC подписи initData.</summary>
|
||||
public string BotToken { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -1,28 +1,70 @@
|
||||
using Prometheus;
|
||||
using MemeVault.Api.Auth;
|
||||
using System.Text;
|
||||
using MemeVault.Api.Options;
|
||||
using MemeVault.Infrastructure;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Prometheus;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// ── Application ───────────────────────────────────────────────────────────────
|
||||
builder.Services.AddMediatR(cfg =>
|
||||
cfg.RegisterServicesFromAssembly(
|
||||
typeof(MemeVault.Application.Commands.SaveMedia.SaveMediaCommand).Assembly));
|
||||
|
||||
// ── Infrastructure (DB + Redis) ───────────────────────────────────────────────
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
|
||||
// ── MediatR ───────────────────────────────────────────────────────────────────
|
||||
builder.Services.AddMediatR(cfg =>
|
||||
cfg.RegisterServicesFromAssembly(
|
||||
typeof(MemeVault.Application.Commands.SaveMedia.SaveMediaCommand).Assembly));
|
||||
|
||||
// ── Telegram initData + JWT ───────────────────────────────────────────────────
|
||||
builder.Services.Configure<TelegramOptions>(
|
||||
builder.Configuration.GetSection(TelegramOptions.Section));
|
||||
builder.Services.Configure<JwtOptions>(
|
||||
builder.Configuration.GetSection(JwtOptions.Section));
|
||||
|
||||
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
||||
builder.Services.AddSingleton<JwtTokenService>();
|
||||
|
||||
var jwtOpts = builder.Configuration.GetSection(JwtOptions.Section).Get<JwtOptions>()!;
|
||||
|
||||
builder.Services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(o =>
|
||||
{
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtOpts.Issuer,
|
||||
ValidAudience = jwtOpts.Audience,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(jwtOpts.SecretKey)),
|
||||
ClockSkew = TimeSpan.FromSeconds(30),
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// ── OpenAPI ───────────────────────────────────────────────────────────────────
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseHttpMetrics();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
|
||||
|
||||
// TODO: /api/media GET — список медиа пользователя
|
||||
// TODO: /api/media POST — загрузить новое медиа (файл или текст)
|
||||
// TODO: /api/media/{id} PATCH — обновить caption / теги
|
||||
// TODO: /api/media/{id} DELETE
|
||||
// TODO: /api/tags GET — теги пользователя
|
||||
// TODO: /api/collections GET/POST — коллекции
|
||||
|
||||
app.MapControllers();
|
||||
app.MapMetrics();
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
{
|
||||
"Bot": {
|
||||
"Token": "YOUR_BOT_TOKEN_HERE",
|
||||
"WebhookHost": "https://your-domain.com"
|
||||
"Telegram": {
|
||||
"BotToken": ""
|
||||
},
|
||||
"Jwt": {
|
||||
"SecretKey": "",
|
||||
"Issuer": "memevault-api",
|
||||
"Audience": "memevault-miniapp",
|
||||
"ExpiryHours": 24
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"Postgres": "Host=db;Port=5432;Database=memevault;Username=memevault;Password=changeme"
|
||||
"Postgres": "Host=localhost;Database=memevault;Username=memevault;Password=changeme",
|
||||
"Redis": "localhost:6379"
|
||||
},
|
||||
"Redis": "redis:6379",
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,8 +83,8 @@ public sealed class MessageHandler
|
||||
var entry = new MediaGroupEntry(
|
||||
message.From.Id,
|
||||
message.Chat.Id,
|
||||
source.Origin.ToString(),
|
||||
source.Reference,
|
||||
source.Origin?.ToString() ?? string.Empty,
|
||||
source.Reference ?? string.Empty,
|
||||
mediaType.ToString(),
|
||||
message.Caption);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user