Files
Govor/Govor.API/Program.cs
T
Artemy 29cc51ee0c Add reactions, reliable push & session checks
Implements message reactions and reaction packs (domain models, services, admin HTTP API, media processing via ImageSharp and limits) and adds reliable push delivery (ChatPushNotification, ChatPushDispatcher, ChatPushWorker, improved ChatNotificationService). Enhances message reading (ReadChat API, unread counts, concurrency-safe receipts) and tightens session security (access-token session validation in JWT, hub filter, SessionAuthorization). Improves SignalR behavior (session groups, reaction/channel events, hub/error mappings). Adds EF migrations, many controller fixes (Forbid handling, password API), tests (Govor.Server.Tests), docs, CI and tooling updates (Dockerfile → .NET 10, GH Actions matrix for sqlite/postgres, Govor.Server.slnx, global.json), and small infra changes (AutoMapper bump, NullPushProvider, storage/token handling).
2026-10-03 17:42:24 +07:00

160 lines
4.7 KiB
C#

using System.Text;
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
using Govor.API.Common.Extensions;
using Govor.API.Hubs;
using Govor.Application.Authentication.JWT;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using Govor.Domain;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var services = builder.Services;
builder.AddLogger();// Serilog
builder.Configuration.AddJsonFile("configs/ban_usernames.json", optional: false, reloadOnChange: true);
if (configuration.GetValue("Firebase:Enabled", true))
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("secrets/firebase-adminsdk.json")
});
}
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
var origins = configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
if (origins.Length > 0)
policy.WithOrigins(origins);
policy
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services.Configure<JwtAccessOption>(configuration.GetSection(nameof(JwtAccessOption)));
// Add services
builder.Services.AddSignalRConf();// signalR
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["JwtAccessOption:SecretKey"]!))
};
options.Events = new JwtBearerEvents
{
OnTokenValidated = async context =>
{
var db = context.HttpContext.RequestServices.GetRequiredService<GovorDbContext>();
if (!await db.HasActiveSessionAsync(context.Principal))
context.Fail("The access session is invalid or revoked.");
},
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
// Init DI
builder.Services.AddServices();
builder.Services.AddOptionsConfiguration(configuration);
builder.Services.AddGovorDbContext(configuration); // GovorDbContext init
builder.Services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
{
const string schemeId = "Bearer";
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Govor API", Version = "v1" });
options.AddSecurityDefinition(schemeId, new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
In = ParameterLocation.Header,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'"
});
options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference("Bearer", document)] = new List<string>(0)
});
});
//builder.Services.AddOpenApi();
if (!builder.Environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["urls"]) &&
string.IsNullOrWhiteSpace(configuration["HTTP_PORTS"]))
{
builder.WebHost.UseUrls("http://0.0.0.0:8080");
}
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowFrontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapGet("/server/ping",
() => Results.Ok());
app.MapHub<ChatsHub>("/hubs/chats", options => options.CloseOnAuthenticationExpiration = true);
app.MapHub<FriendsHub>("/hubs/friends", options => options.CloseOnAuthenticationExpiration = true);
app.MapHub<ProfileHub>("/hubs/profiles", options => options.CloseOnAuthenticationExpiration = true);
app.MapHub<PresenceHub>("/hubs/presence", options => options.CloseOnAuthenticationExpiration = true);
app.MapSwagger()
.RequireAuthorization();
app.Map("/", () => "Not for browsers");
app.Run();
public partial class Program { }