JJ Colocate

This commit is contained in:
2025-06-30 14:23:20 -04:00
parent 360fa53439
commit 24abf5607f
77 changed files with 5700 additions and 5700 deletions

View File

@@ -1 +1 @@
wwwroot
wwwroot

View File

@@ -1 +1 @@
wwwroot/*
wwwroot/*

View File

@@ -1,39 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>9ffcc706-7f1b-48e3-bf30-eab69a90fded</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.71.0" />
<PackageReference Include="Grpc.AspNetCore.Web" Version="2.71.0" />
<PackageReference Include="Grpc.Tools" Version="2.72.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.6" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.12.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.2" />
<PackageReference Include="MimeTypesMap" Version="1.0.9" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.9.0-beta.2" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.12.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AobaCore\AobaCore.csproj" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="Proto\Aoba.proto"></Protobuf>
<Protobuf Include="Proto\Auth.proto"></Protobuf>
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>9ffcc706-7f1b-48e3-bf30-eab69a90fded</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.71.0" />
<PackageReference Include="Grpc.AspNetCore.Web" Version="2.71.0" />
<PackageReference Include="Grpc.Tools" Version="2.72.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.6" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.12.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.2" />
<PackageReference Include="MimeTypesMap" Version="1.0.9" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.9.0-beta.2" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.12.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AobaCore\AobaCore.csproj" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="Proto\Aoba.proto"></Protobuf>
<Protobuf Include="Proto\Auth.proto"></Protobuf>
</ItemGroup>
</Project>

View File

@@ -1,28 +1,28 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;
namespace AobaServer.Auth;
internal class AobaAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
throw new NotImplementedException();
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status401Unauthorized;
Response.BodyWriter.Complete();
return Task.CompletedTask;
}
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status403Forbidden;
Response.BodyWriter.Complete();
return Task.CompletedTask;
}
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;
namespace AobaServer.Auth;
internal class AobaAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
throw new NotImplementedException();
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status401Unauthorized;
Response.BodyWriter.Complete();
return Task.CompletedTask;
}
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status403Forbidden;
Response.BodyWriter.Complete();
return Task.CompletedTask;
}
}

View File

@@ -1,44 +1,44 @@
using AobaServer.Models;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace AobaServer.Auth;
public class MetricsTokenValidator(AuthInfo authInfo) : JwtSecurityTokenHandler
{
private readonly JwtSecurityTokenHandler _handler = new();
public override Task<TokenValidationResult> ValidateTokenAsync(string token, TokenValidationParameters validationParameters)
{
try
{
var principal = _handler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(authInfo.SecureKey),
ValidateIssuer = true,
ValidIssuer = authInfo.Issuer,
ValidateAudience = true,
ValidAudience = "metrics",
ValidateLifetime = false,
ClockSkew = TimeSpan.FromMinutes(1)
}, out var validatedToken);
return Task.FromResult(new TokenValidationResult
{
IsValid = true,
SecurityToken = validatedToken,
ClaimsIdentity = new ClaimsIdentity(principal.Identity),
});
}
catch (Exception e)
{
return Task.FromResult(new TokenValidationResult
{
IsValid = false,
Exception = e
});
}
}
}
using AobaServer.Models;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace AobaServer.Auth;
public class MetricsTokenValidator(AuthInfo authInfo) : JwtSecurityTokenHandler
{
private readonly JwtSecurityTokenHandler _handler = new();
public override Task<TokenValidationResult> ValidateTokenAsync(string token, TokenValidationParameters validationParameters)
{
try
{
var principal = _handler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(authInfo.SecureKey),
ValidateIssuer = true,
ValidIssuer = authInfo.Issuer,
ValidateAudience = true,
ValidAudience = "metrics",
ValidateLifetime = false,
ClockSkew = TimeSpan.FromMinutes(1)
}, out var validatedToken);
return Task.FromResult(new TokenValidationResult
{
IsValid = true,
SecurityToken = validatedToken,
ClaimsIdentity = new ClaimsIdentity(principal.Identity),
});
}
catch (Exception e)
{
return Task.FromResult(new TokenValidationResult
{
IsValid = false,
Exception = e
});
}
}
}

View File

@@ -1,19 +1,19 @@
using Microsoft.AspNetCore.Mvc;
namespace AobaServer.Controllers.Api;
[Route("/api/auth")]
public class AuthApi : ControllerBase
{
[HttpGet("login")]
public Task<IActionResult> LoginAsync()
{
throw new NotImplementedException();
}
[HttpGet("register")]
public Task<IActionResult> RegisterAsync()
{
throw new NotImplementedException();
}
}
using Microsoft.AspNetCore.Mvc;
namespace AobaServer.Controllers.Api;
[Route("/api/auth")]
public class AuthApi : ControllerBase
{
[HttpGet("login")]
public Task<IActionResult> LoginAsync()
{
throw new NotImplementedException();
}
[HttpGet("register")]
public Task<IActionResult> RegisterAsync()
{
throw new NotImplementedException();
}
}

View File

@@ -1,38 +1,38 @@
using AobaCore.Models;
using AobaCore.Services;
using AobaServer.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
namespace AobaServer.Controllers.Api;
[ApiController, Authorize]
[Route("/api/media")]
public class MediaApi(AobaService aoba) : ControllerBase
{
[HttpPost("upload")]
public async Task<IActionResult> UploadAsync([FromForm] IFormFile file, CancellationToken cancellationToken)
{
var media = await aoba.UploadFileAsync(file.OpenReadStream(), file.FileName, User.GetId(), cancellationToken);
if (media.HasError)
return Problem(detail: media.Error.Message, statusCode: StatusCodes.Status400BadRequest);
return Ok(new
{
media = media.Value,
url = media.Value.GetMediaUrl()
});
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(ObjectId id, CancellationToken cancellationToken)
{
await aoba.DeleteFileAsync(id, cancellationToken);
return Ok();
}
}
using AobaCore.Models;
using AobaCore.Services;
using AobaServer.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
namespace AobaServer.Controllers.Api;
[ApiController, Authorize]
[Route("/api/media")]
public class MediaApi(AobaService aoba) : ControllerBase
{
[HttpPost("upload")]
public async Task<IActionResult> UploadAsync([FromForm] IFormFile file, CancellationToken cancellationToken)
{
var media = await aoba.UploadFileAsync(file.OpenReadStream(), file.FileName, User.GetId(), cancellationToken);
if (media.HasError)
return Problem(detail: media.Error.Message, statusCode: StatusCodes.Status400BadRequest);
return Ok(new
{
media = media.Value,
url = media.Value.GetMediaUrl()
});
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(ObjectId id, CancellationToken cancellationToken)
{
await aoba.DeleteFileAsync(id, cancellationToken);
return Ok();
}
}

View File

@@ -1,37 +1,37 @@
using AobaCore.Services;
using AobaServer.Models;
using AobaServer.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace AobaServer.Controllers;
//allow login via http during debug testing
#if DEBUG
[AllowAnonymous]
[Route("auth")]
public class AuthController(AccountsService accountsService, AuthInfo authInfo) : Controller
{
[HttpPost("login")]
public async Task<IActionResult> Login([FromForm] string username, [FromForm] string password, CancellationToken cancellationToken)
{
var user = await accountsService.VerifyLoginAsync(username, password, cancellationToken);
if (user == null)
return Problem("Invalid login Credentials", statusCode: StatusCodes.Status400BadRequest);
Response.Cookies.Append("token", user.GetToken(authInfo), new CookieOptions
{
IsEssential = true,
SameSite = SameSiteMode.Strict,
Secure = true,
});
return Ok();
}
}
using AobaCore.Services;
using AobaServer.Models;
using AobaServer.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace AobaServer.Controllers;
//allow login via http during debug testing
#if DEBUG
[AllowAnonymous]
[Route("auth")]
public class AuthController(AccountsService accountsService, AuthInfo authInfo) : Controller
{
[HttpPost("login")]
public async Task<IActionResult> Login([FromForm] string username, [FromForm] string password, CancellationToken cancellationToken)
{
var user = await accountsService.VerifyLoginAsync(username, password, cancellationToken);
if (user == null)
return Problem("Invalid login Credentials", statusCode: StatusCodes.Status400BadRequest);
Response.Cookies.Append("token", user.GetToken(authInfo), new CookieOptions
{
IsEssential = true,
SameSite = SameSiteMode.Strict,
Secure = true,
});
return Ok();
}
}
#endif

View File

@@ -1,65 +1,65 @@
using AobaCore.Models;
using AobaCore.Services;
using HeyRed.Mime;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
namespace AobaServer.Controllers;
[Route("/m")]
public class MediaController(AobaService aobaService, ILogger<MediaController> logger) : Controller
{
[HttpGet("{id}")]
[ResponseCache(Duration = int.MaxValue)]
public async Task<IActionResult> MediaAsync(ObjectId id, [FromServices] MongoClient client, CancellationToken cancellationToken)
{
var file = await aobaService.GetFileStreamAsync(id, cancellationToken: cancellationToken);
if (file.HasError)
{
logger.LogError(file.Error.Exception, "Failed to load media stream");
return NotFound();
}
var mime = MimeTypesMap.GetMimeType(file.Value.FileInfo.Filename);
_ = aobaService.IncrementFileViewCountAsync(id, cancellationToken);
return File(file, mime, true);
}
/// <summary>
/// Redirect legacy media urls to the new url
/// </summary>
/// <param name="id"></param>
/// <param name="rest"></param>
/// <param name="aoba"></param>
/// <returns></returns>
[HttpGet("/i/{id}/{*rest}")]
public async Task<IActionResult> LegacyRedirectAsync(ObjectId id, string rest, CancellationToken cancellationToken)
{
var media = await aobaService.GetMediaAsync(id, cancellationToken);
if (media == null)
return NotFound();
return LocalRedirectPermanent($"/m/{media.MediaId}/{rest}");
}
[HttpGet("thumb/{id}")]
[ResponseCache(Duration = int.MaxValue)]
public async Task<IActionResult> ThumbAsync(ObjectId id, [FromServices] ThumbnailService thumbnailService, [FromQuery] ThumbnailSize size = ThumbnailSize.Medium, CancellationToken cancellationToken = default)
{
var thumb = await thumbnailService.GetOrCreateThumbnailAsync(id, size, cancellationToken);
if (thumb.HasError)
{
logger.LogError("Failed to generate thumbnail: {}", thumb.Error);
return DefaultThumbnailAsync();
}
return File(thumb, "image/webp", true);
}
[NonAction]
private IActionResult DefaultThumbnailAsync()
{
return NoContent();
}
}
using AobaCore.Models;
using AobaCore.Services;
using HeyRed.Mime;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
namespace AobaServer.Controllers;
[Route("/m")]
public class MediaController(AobaService aobaService, ILogger<MediaController> logger) : Controller
{
[HttpGet("{id}")]
[ResponseCache(Duration = int.MaxValue)]
public async Task<IActionResult> MediaAsync(ObjectId id, [FromServices] MongoClient client, CancellationToken cancellationToken)
{
var file = await aobaService.GetFileStreamAsync(id, cancellationToken: cancellationToken);
if (file.HasError)
{
logger.LogError(file.Error.Exception, "Failed to load media stream");
return NotFound();
}
var mime = MimeTypesMap.GetMimeType(file.Value.FileInfo.Filename);
_ = aobaService.IncrementFileViewCountAsync(id, cancellationToken);
return File(file, mime, true);
}
/// <summary>
/// Redirect legacy media urls to the new url
/// </summary>
/// <param name="id"></param>
/// <param name="rest"></param>
/// <param name="aoba"></param>
/// <returns></returns>
[HttpGet("/i/{id}/{*rest}")]
public async Task<IActionResult> LegacyRedirectAsync(ObjectId id, string rest, CancellationToken cancellationToken)
{
var media = await aobaService.GetMediaAsync(id, cancellationToken);
if (media == null)
return NotFound();
return LocalRedirectPermanent($"/m/{media.MediaId}/{rest}");
}
[HttpGet("thumb/{id}")]
[ResponseCache(Duration = int.MaxValue)]
public async Task<IActionResult> ThumbAsync(ObjectId id, [FromServices] ThumbnailService thumbnailService, [FromQuery] ThumbnailSize size = ThumbnailSize.Medium, CancellationToken cancellationToken = default)
{
var thumb = await thumbnailService.GetOrCreateThumbnailAsync(id, size, cancellationToken);
if (thumb.HasError)
{
logger.LogError("Failed to generate thumbnail: {}", thumb.Error);
return DefaultThumbnailAsync();
}
return File(thumb, "image/webp", true);
}
[NonAction]
private IActionResult DefaultThumbnailAsync()
{
return NoContent();
}
}

View File

@@ -1,61 +1,61 @@
# Client Side build - prep deps
FROM rust:1 AS chef
RUN rustup target add wasm32-unknown-unknown
RUN cargo install cargo-chef
WORKDIR /app
FROM chef AS planner
COPY . .
WORKDIR /app/AobaClient
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS client-builder
WORKDIR /app/AobaClient
COPY --from=planner /app/AobaClient/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY /AobaClient /app/AobaClient
COPY /AobaServer/Proto /app/AobaServer/Proto
# Install Protobuf
RUN apt update
RUN apt install -y protobuf-compiler libprotobuf-dev
# Install `dx`
RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash
RUN cargo binstall dioxus-cli --root /.cargo -y --force
ENV PATH="/.cargo/bin:$PATH"
# Create the final bundle folder. Bundle always executes in release mode with optimizations enabled
RUN dx bundle --platform web
# Server Build
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["AobaServer/AobaServer.csproj", "AobaServer/"]
RUN dotnet restore "./AobaServer/AobaServer.csproj"
COPY . .
# Copy Built bundle from client builder
COPY --from=client-builder /app/AobaClient/target/dx/aoba-client/release/web/public /src/AobaServer/wwwroot
WORKDIR "/src/AobaServer"
RUN dotnet build "./AobaServer.csproj" -c $BUILD_CONFIGURATION -o /app/build
# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./AobaServer.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
RUN sudo apt-get install -y ffmpeg libgdiplus
ENTRYPOINT ["dotnet", "AobaServer.dll"]
# Client Side build - prep deps
FROM rust:1 AS chef
RUN rustup target add wasm32-unknown-unknown
RUN cargo install cargo-chef
WORKDIR /app
FROM chef AS planner
COPY . .
WORKDIR /app/AobaClient
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS client-builder
WORKDIR /app/AobaClient
COPY --from=planner /app/AobaClient/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY /AobaClient /app/AobaClient
COPY /AobaServer/Proto /app/AobaServer/Proto
# Install Protobuf
RUN apt update
RUN apt install -y protobuf-compiler libprotobuf-dev
# Install `dx`
RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash
RUN cargo binstall dioxus-cli --root /.cargo -y --force
ENV PATH="/.cargo/bin:$PATH"
# Create the final bundle folder. Bundle always executes in release mode with optimizations enabled
RUN dx bundle --platform web
# Server Build
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["AobaServer/AobaServer.csproj", "AobaServer/"]
RUN dotnet restore "./AobaServer/AobaServer.csproj"
COPY . .
# Copy Built bundle from client builder
COPY --from=client-builder /app/AobaClient/target/dx/aoba-client/release/web/public /src/AobaServer/wwwroot
WORKDIR "/src/AobaServer"
RUN dotnet build "./AobaServer.csproj" -c $BUILD_CONFIGURATION -o /app/build
# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./AobaServer.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
RUN sudo apt-get install -y ffmpeg libgdiplus
ENTRYPOINT ["dotnet", "AobaServer.dll"]

View File

@@ -1,73 +1,73 @@
#nullable enable
using AobaServer.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
namespace AobaServer.Middleware;
public static class OpenTelemetry
{
public static void AddObersability(this IServiceCollection services, IConfiguration configuration)
{
var otel = services.AddOpenTelemetry();
otel.ConfigureResource(res =>
{
res.AddService(serviceName: $"Breeze: {Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}");
});
// Add Metrics for ASP.NET Core and our custom metrics and export to Prometheus
otel.WithMetrics(metrics => metrics
// Metrics provider from OpenTelemetry
.AddAspNetCoreInstrumentation()
.AddCustomMetrics()
// Metrics provides by ASP.NET Core in .NET 8
.AddMeter("Microsoft.AspNetCore.Hosting")
.AddMeter("Microsoft.AspNetCore.Server.Kestrel")
// Metrics provided by System.Net libraries
.AddMeter("System.Net.Http")
.AddMeter("System.Net.NameResolution")
.AddPrometheusExporter());
// Add Tracing for ASP.NET Core and our custom ActivitySource and export to Jaeger
var tracingOtlpEndpoint = configuration["OTLP_ENDPOINT_URL"];
otel.WithTracing(tracing =>
{
tracing.AddSource("MongoDB.Driver.Core.Extensions.DiagnosticSources");
tracing.AddAspNetCoreInstrumentation();
tracing.AddHttpClientInstrumentation();
if (!string.IsNullOrWhiteSpace(tracingOtlpEndpoint))
{
tracing.AddOtlpExporter(otlpOptions =>
{
otlpOptions.Endpoint = new Uri(tracingOtlpEndpoint);
});
}
});
}
public static MeterProviderBuilder AddCustomMetrics(this MeterProviderBuilder builder)
{
return builder;
}
public static IEndpointRouteBuilder MapObserability(this IEndpointRouteBuilder endpoints)
{
endpoints.MapPrometheusScrapingEndpoint().RequireAuthorization();
return endpoints;
}
}
#nullable enable
using AobaServer.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
namespace AobaServer.Middleware;
public static class OpenTelemetry
{
public static void AddObersability(this IServiceCollection services, IConfiguration configuration)
{
var otel = services.AddOpenTelemetry();
otel.ConfigureResource(res =>
{
res.AddService(serviceName: $"Breeze: {Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}");
});
// Add Metrics for ASP.NET Core and our custom metrics and export to Prometheus
otel.WithMetrics(metrics => metrics
// Metrics provider from OpenTelemetry
.AddAspNetCoreInstrumentation()
.AddCustomMetrics()
// Metrics provides by ASP.NET Core in .NET 8
.AddMeter("Microsoft.AspNetCore.Hosting")
.AddMeter("Microsoft.AspNetCore.Server.Kestrel")
// Metrics provided by System.Net libraries
.AddMeter("System.Net.Http")
.AddMeter("System.Net.NameResolution")
.AddPrometheusExporter());
// Add Tracing for ASP.NET Core and our custom ActivitySource and export to Jaeger
var tracingOtlpEndpoint = configuration["OTLP_ENDPOINT_URL"];
otel.WithTracing(tracing =>
{
tracing.AddSource("MongoDB.Driver.Core.Extensions.DiagnosticSources");
tracing.AddAspNetCoreInstrumentation();
tracing.AddHttpClientInstrumentation();
if (!string.IsNullOrWhiteSpace(tracingOtlpEndpoint))
{
tracing.AddOtlpExporter(otlpOptions =>
{
otlpOptions.Endpoint = new Uri(tracingOtlpEndpoint);
});
}
});
}
public static MeterProviderBuilder AddCustomMetrics(this MeterProviderBuilder builder)
{
return builder;
}
public static IEndpointRouteBuilder MapObserability(this IEndpointRouteBuilder endpoints)
{
endpoints.MapPrometheusScrapingEndpoint().RequireAuthorization();
return endpoints;
}
}

View File

@@ -1,75 +1,75 @@
using MongoDB.Bson.IO;
using System.Security.Cryptography;
using System.Text.Json;
namespace AobaServer.Models;
public class AuthInfo
{
public required string Issuer { get; set; }
public required string Audience { get; set; }
public required byte[] SecureKey { get; set; }
/// <summary>
/// Save this auth into in a json format to the sepcified file
/// </summary>
/// <param name="path">File path</param>
/// <returns></returns>
public AuthInfo Save(string path)
{
File.WriteAllText(path, JsonSerializer.Serialize(this));
return this;
}
/// <summary>
/// Generate a new Auth Info with newly generated keys
/// </summary>
/// <param name="issuer"></param>
/// <param name="audience"></param>
/// <returns></returns>
public static AuthInfo Create(string issuer, string audience)
{
var auth = new AuthInfo
{
Issuer = issuer,
Audience = audience,
SecureKey = GenetateJWTKey()
};
return auth;
}
/// <summary>
/// Load auth info from a json file
/// </summary>
/// <param name="path">File path</param>
/// <returns></returns>
internal static AuthInfo? Load(string path)
{
return JsonSerializer.Deserialize<AuthInfo>(File.ReadAllText(path));
}
internal static AuthInfo LoadOrCreate(string path, string issuer, string audience)
{
if (File.Exists(path))
{
var loaded = Load(path);
if (loaded != null)
return loaded;
}
var info = Create(issuer, audience);
info.Save(path);
return info;
}
/// <summary>
/// Generate a new key for use by JWT
/// </summary>
/// <returns></returns>
public static byte[] GenetateJWTKey(int size = 64)
{
var key = new byte[size];
RandomNumberGenerator.Fill(key);
return key;
}
using MongoDB.Bson.IO;
using System.Security.Cryptography;
using System.Text.Json;
namespace AobaServer.Models;
public class AuthInfo
{
public required string Issuer { get; set; }
public required string Audience { get; set; }
public required byte[] SecureKey { get; set; }
/// <summary>
/// Save this auth into in a json format to the sepcified file
/// </summary>
/// <param name="path">File path</param>
/// <returns></returns>
public AuthInfo Save(string path)
{
File.WriteAllText(path, JsonSerializer.Serialize(this));
return this;
}
/// <summary>
/// Generate a new Auth Info with newly generated keys
/// </summary>
/// <param name="issuer"></param>
/// <param name="audience"></param>
/// <returns></returns>
public static AuthInfo Create(string issuer, string audience)
{
var auth = new AuthInfo
{
Issuer = issuer,
Audience = audience,
SecureKey = GenetateJWTKey()
};
return auth;
}
/// <summary>
/// Load auth info from a json file
/// </summary>
/// <param name="path">File path</param>
/// <returns></returns>
internal static AuthInfo? Load(string path)
{
return JsonSerializer.Deserialize<AuthInfo>(File.ReadAllText(path));
}
internal static AuthInfo LoadOrCreate(string path, string issuer, string audience)
{
if (File.Exists(path))
{
var loaded = Load(path);
if (loaded != null)
return loaded;
}
var info = Create(issuer, audience);
info.Save(path);
return info;
}
/// <summary>
/// Generate a new key for use by JWT
/// </summary>
/// <returns></returns>
public static byte[] GenetateJWTKey(int size = 64)
{
var key = new byte[size];
RandomNumberGenerator.Fill(key);
return key;
}
}

View File

@@ -1,31 +1,31 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using MongoDB.Bson;
namespace AobaServer.Models;
public class BsonIdModelBinderProvider : IModelBinderProvider
{
public IModelBinder? GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(ObjectId))
return new BsonIdModelBinder();
return default;
}
}
public class BsonIdModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == ValueProviderResult.None)
return Task.CompletedTask;
if (ObjectId.TryParse(value.FirstValue, out var id))
bindingContext.Result = ModelBindingResult.Success(id);
else
bindingContext.Result = ModelBindingResult.Failed();
return Task.CompletedTask;
}
}
using Microsoft.AspNetCore.Mvc.ModelBinding;
using MongoDB.Bson;
namespace AobaServer.Models;
public class BsonIdModelBinderProvider : IModelBinderProvider
{
public IModelBinder? GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(ObjectId))
return new BsonIdModelBinder();
return default;
}
}
public class BsonIdModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == ValueProviderResult.None)
return Task.CompletedTask;
if (ObjectId.TryParse(value.FirstValue, out var id))
bindingContext.Result = ModelBindingResult.Success(id);
else
bindingContext.Result = ModelBindingResult.Failed();
return Task.CompletedTask;
}
}

View File

@@ -1,18 +1,18 @@
namespace AobaServer.Models;
public class ShareXDestination
{
public string Version { get; set; } = "14.0.1";
public string Name { get; set; } = "Aoba";
public string DestinationType { get; set; } = "ImageUploader, TextUploader, FileUploader";
public string RequestMethod { get; set; } = "POST";
public string RequestURL { get; set; } = "https://aoba.app/api/media/upload";
public Dictionary<string, string> Headers { get; set; } = [];
public string Body { get; set; } = "MultipartFormData";
public Dictionary<string, string> Arguments { get; set; } = new() { { "name", "$filename$" } };
public string FileFormName { get; set; } = "file";
public string[] RegexList { get; set; } = ["([^/]+)/?$"];
public string URL { get; set; } = "https://aoba.app{json:url}";
public string? ThumbnailURL { get; set; }
public string? DeletionURL { get; set; }
namespace AobaServer.Models;
public class ShareXDestination
{
public string Version { get; set; } = "14.0.1";
public string Name { get; set; } = "Aoba";
public string DestinationType { get; set; } = "ImageUploader, TextUploader, FileUploader";
public string RequestMethod { get; set; } = "POST";
public string RequestURL { get; set; } = "https://aoba.app/api/media/upload";
public Dictionary<string, string> Headers { get; set; } = [];
public string Body { get; set; } = "MultipartFormData";
public Dictionary<string, string> Arguments { get; set; } = new() { { "name", "$filename$" } };
public string FileFormName { get; set; } = "file";
public string[] RegexList { get; set; } = ["([^/]+)/?$"];
public string URL { get; set; } = "https://aoba.app{json:url}";
public string? ThumbnailURL { get; set; }
public string? DeletionURL { get; set; }
}

View File

@@ -1,144 +1,144 @@
using AobaCore;
using AobaServer.Auth;
using AobaServer.Middleware;
using AobaServer.Models;
using AobaServer.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(o =>
{
o.Limits.MaxRequestBodySize = null;
#if !DEBUG
o.ListenAnyIP(8081, lo =>
{
lo.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
});
o.ListenAnyIP(8080, lo =>
{
lo.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
});
#endif
});
var config = builder.Configuration;
// Add services to the container.
builder.Services.AddControllers(opt => opt.ModelBinderProviders.Add(new BsonIdModelBinderProvider()));
builder.Services.AddObersability(builder.Configuration);
builder.Services.AddGrpc();
var authInfo = AuthInfo.LoadOrCreate("Auth.json", "aobaV2", "aoba");
builder.Services.AddSingleton(authInfo);
var signingKey = new SymmetricSecurityKey(authInfo.SecureKey);
var validationParams = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = authInfo.Issuer,
ValidateAudience = true,
ValidAudience = authInfo.Audience,
ValidateLifetime = false,
ClockSkew = TimeSpan.FromMinutes(1),
};
builder.Services.AddCors(o =>
{
o.AddPolicy("AllowAll", p =>
{
p.AllowAnyOrigin();
p.AllowAnyMethod();
p.AllowAnyHeader();
});
o.AddPolicy("RPC", p =>
{
p.AllowAnyMethod();
p.AllowAnyHeader();
p.WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
p.AllowAnyOrigin();
});
});
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "Aoba";
}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => //Bearer auth
{
options.TokenValidationParameters = validationParams;
options.TokenHandlers.Add(new MetricsTokenValidator(authInfo));
options.Events = new JwtBearerEvents
{
OnMessageReceived = ctx => //Retreive token from cookie if not found in headers
{
if (string.IsNullOrWhiteSpace(ctx.Token))
ctx.Token = ctx.Request.Headers.Authorization.FirstOrDefault()?.Replace("Bearer ", "");
#if DEBUG //allow cookie based auth when in debug mode
if (string.IsNullOrWhiteSpace(ctx.Token))
ctx.Token = ctx.Request.Cookies.FirstOrDefault(c => c.Key == "token").Value;
#endif
return Task.CompletedTask;
},
OnAuthenticationFailed = ctx =>
{
ctx.Response.Cookies.Append("token", "", new CookieOptions
{
MaxAge = TimeSpan.Zero,
Expires = DateTime.Now
});
ctx.Options.ForwardChallenge = "Aoba";
return Task.CompletedTask;
}
};
}).AddScheme<AuthenticationSchemeOptions, AobaAuthenticationHandler>("Aoba", null);
var dbString = config["DB_STRING"];
builder.Services.AddAoba(dbString ?? "mongodb://localhost:27017");
builder.Services.Configure<FormOptions>(opt =>
{
opt.ValueLengthLimit = int.MaxValue;
opt.MultipartBodyLengthLimit = int.MaxValue;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapObserability();
app.MapGrpcService<AobaRpcService>()
.RequireAuthorization()
.RequireCors("RPC");
app.MapGrpcService<AobaAuthService>()
.AllowAnonymous()
.RequireCors("RPC");
app.MapFallbackToFile("index.html");
app.Run();
using AobaCore;
using AobaServer.Auth;
using AobaServer.Middleware;
using AobaServer.Models;
using AobaServer.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(o =>
{
o.Limits.MaxRequestBodySize = null;
#if !DEBUG
o.ListenAnyIP(8081, lo =>
{
lo.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
});
o.ListenAnyIP(8080, lo =>
{
lo.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
});
#endif
});
var config = builder.Configuration;
// Add services to the container.
builder.Services.AddControllers(opt => opt.ModelBinderProviders.Add(new BsonIdModelBinderProvider()));
builder.Services.AddObersability(builder.Configuration);
builder.Services.AddGrpc();
var authInfo = AuthInfo.LoadOrCreate("Auth.json", "aobaV2", "aoba");
builder.Services.AddSingleton(authInfo);
var signingKey = new SymmetricSecurityKey(authInfo.SecureKey);
var validationParams = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = authInfo.Issuer,
ValidateAudience = true,
ValidAudience = authInfo.Audience,
ValidateLifetime = false,
ClockSkew = TimeSpan.FromMinutes(1),
};
builder.Services.AddCors(o =>
{
o.AddPolicy("AllowAll", p =>
{
p.AllowAnyOrigin();
p.AllowAnyMethod();
p.AllowAnyHeader();
});
o.AddPolicy("RPC", p =>
{
p.AllowAnyMethod();
p.AllowAnyHeader();
p.WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
p.AllowAnyOrigin();
});
});
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "Aoba";
}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => //Bearer auth
{
options.TokenValidationParameters = validationParams;
options.TokenHandlers.Add(new MetricsTokenValidator(authInfo));
options.Events = new JwtBearerEvents
{
OnMessageReceived = ctx => //Retreive token from cookie if not found in headers
{
if (string.IsNullOrWhiteSpace(ctx.Token))
ctx.Token = ctx.Request.Headers.Authorization.FirstOrDefault()?.Replace("Bearer ", "");
#if DEBUG //allow cookie based auth when in debug mode
if (string.IsNullOrWhiteSpace(ctx.Token))
ctx.Token = ctx.Request.Cookies.FirstOrDefault(c => c.Key == "token").Value;
#endif
return Task.CompletedTask;
},
OnAuthenticationFailed = ctx =>
{
ctx.Response.Cookies.Append("token", "", new CookieOptions
{
MaxAge = TimeSpan.Zero,
Expires = DateTime.Now
});
ctx.Options.ForwardChallenge = "Aoba";
return Task.CompletedTask;
}
};
}).AddScheme<AuthenticationSchemeOptions, AobaAuthenticationHandler>("Aoba", null);
var dbString = config["DB_STRING"];
builder.Services.AddAoba(dbString ?? "mongodb://localhost:27017");
builder.Services.Configure<FormOptions>(opt =>
{
opt.ValueLengthLimit = int.MaxValue;
opt.MultipartBodyLengthLimit = int.MaxValue;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapObserability();
app.MapGrpcService<AobaRpcService>()
.RequireAuthorization()
.RequireCors("RPC");
app.MapGrpcService<AobaAuthService>()
.AllowAnonymous()
.RequireCors("RPC");
app.MapFallbackToFile("index.html");
app.Run();

View File

@@ -1,30 +1,30 @@
{
"profiles": {
"http": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:8081"
},
"https": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:8081"
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_HTTP_PORTS": "8081"
},
"publishAllPorts": true,
"useSSL": false
}
},
"$schema": "https://json.schemastore.org/launchsettings.json"
{
"profiles": {
"http": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:8081"
},
"https": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:8081"
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_HTTP_PORTS": "8081"
},
"publishAllPorts": true,
"useSSL": false
}
},
"$schema": "https://json.schemastore.org/launchsettings.json"
}

View File

@@ -1,85 +1,85 @@
syntax = "proto3";
import "google/protobuf/empty.proto";
option csharp_namespace = "Aoba.RPC";
package aoba;
service AobaRpc {
rpc GetMedia (Id) returns (MediaResponse);
rpc DeleteMedia (Id) returns (google.protobuf.Empty);
rpc UpdateMedia (google.protobuf.Empty) returns (google.protobuf.Empty);
rpc ListMedia(PageFilter) returns (ListResponse);
rpc GetUser(Id) returns (UserResponse);
rpc GetShareXDestination(google.protobuf.Empty) returns (ShareXResponse);
}
message PageFilter {
optional int32 page = 1;
optional int32 pageSize = 2;
optional string query = 3;
}
message Id {
string value = 1;
}
message MediaResponse {
oneof result {
MediaModel value = 1;
google.protobuf.Empty empty = 2;
}
}
message ListResponse {
repeated MediaModel items = 1;
Pagination pagination = 2;
}
message Pagination {
int32 page = 1;
int32 pageSize = 2;
int64 totalPages = 3;
int64 totalItems = 4;
optional string query = 5;
}
message UserResponse {
oneof userResult {
UserModel user = 1;
google.protobuf.Empty empty = 2;
}
}
message UserModel {
Id id = 1;
string username = 2;
string email = 3;
bool isAdmin = 4;
}
message MediaModel {
Id id = 1;
Id mediaId = 2;
string fileName = 3;
MediaType mediaType = 4;
string ext = 5;
int32 viewCount = 6;
Id owner = 7;
}
enum MediaType {
Image = 0;
Audio = 1;
Video = 2;
Text = 3;
Code = 4;
Raw = 5;
}
message ShareXResponse {
oneof dstResult {
string destination = 1;
string error = 2;
}
}
syntax = "proto3";
import "google/protobuf/empty.proto";
option csharp_namespace = "Aoba.RPC";
package aoba;
service AobaRpc {
rpc GetMedia (Id) returns (MediaResponse);
rpc DeleteMedia (Id) returns (google.protobuf.Empty);
rpc UpdateMedia (google.protobuf.Empty) returns (google.protobuf.Empty);
rpc ListMedia(PageFilter) returns (ListResponse);
rpc GetUser(Id) returns (UserResponse);
rpc GetShareXDestination(google.protobuf.Empty) returns (ShareXResponse);
}
message PageFilter {
optional int32 page = 1;
optional int32 pageSize = 2;
optional string query = 3;
}
message Id {
string value = 1;
}
message MediaResponse {
oneof result {
MediaModel value = 1;
google.protobuf.Empty empty = 2;
}
}
message ListResponse {
repeated MediaModel items = 1;
Pagination pagination = 2;
}
message Pagination {
int32 page = 1;
int32 pageSize = 2;
int64 totalPages = 3;
int64 totalItems = 4;
optional string query = 5;
}
message UserResponse {
oneof userResult {
UserModel user = 1;
google.protobuf.Empty empty = 2;
}
}
message UserModel {
Id id = 1;
string username = 2;
string email = 3;
bool isAdmin = 4;
}
message MediaModel {
Id id = 1;
Id mediaId = 2;
string fileName = 3;
MediaType mediaType = 4;
string ext = 5;
int32 viewCount = 6;
Id owner = 7;
}
enum MediaType {
Image = 0;
Audio = 1;
Video = 2;
Text = 3;
Code = 4;
Raw = 5;
}
message ShareXResponse {
oneof dstResult {
string destination = 1;
string error = 2;
}
}

View File

@@ -1,33 +1,33 @@
syntax = "proto3";
option csharp_namespace = "Aoba.RPC.Auth";
package aoba.Auth;
service AuthRpc {
rpc Login(Credentials) returns (LoginResponse);
rpc LoginPasskey(PassKeyPayload) returns (LoginResponse);
}
message Credentials{
string user = 1;
string password = 2;
}
message PassKeyPayload {
}
message Jwt{
string token = 1;
}
message LoginResponse{
oneof result {
Jwt jwt = 1;
LoginError error = 2;
}
}
message LoginError{
string message = 1;
syntax = "proto3";
option csharp_namespace = "Aoba.RPC.Auth";
package aoba.Auth;
service AuthRpc {
rpc Login(Credentials) returns (LoginResponse);
rpc LoginPasskey(PassKeyPayload) returns (LoginResponse);
}
message Credentials{
string user = 1;
string password = 2;
}
message PassKeyPayload {
}
message Jwt{
string token = 1;
}
message LoginResponse{
oneof result {
Jwt jwt = 1;
LoginError error = 2;
}
}
message LoginError{
string message = 1;
}

View File

@@ -1,43 +1,43 @@
using Aoba.RPC.Auth;
using AobaCore.Models;
using AobaCore.Services;
using AobaServer.Models;
using AobaServer.Utils;
using Grpc.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace AobaServer.Services;
public class AobaAuthService(AccountsService accountsService, AuthInfo authInfo) : Aoba.RPC.Auth.AuthRpc.AuthRpcBase
{
[AllowAnonymous]
public override async Task<LoginResponse> Login(Credentials request, ServerCallContext context)
{
var user = await accountsService.VerifyLoginAsync(request.User, request.Password, context.CancellationToken);
if (user == null)
return new LoginResponse
{
Error = new LoginError
{
Message = "Invalid login credentials"
}
};
var token = user.GetToken(authInfo);
return new LoginResponse
{
Jwt = new Jwt
{
Token = token
}
};
}
using Aoba.RPC.Auth;
using AobaCore.Models;
using AobaCore.Services;
using AobaServer.Models;
using AobaServer.Utils;
using Grpc.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
namespace AobaServer.Services;
public class AobaAuthService(AccountsService accountsService, AuthInfo authInfo) : Aoba.RPC.Auth.AuthRpc.AuthRpcBase
{
[AllowAnonymous]
public override async Task<LoginResponse> Login(Credentials request, ServerCallContext context)
{
var user = await accountsService.VerifyLoginAsync(request.User, request.Password, context.CancellationToken);
if (user == null)
return new LoginResponse
{
Error = new LoginError
{
Message = "Invalid login credentials"
}
};
var token = user.GetToken(authInfo);
return new LoginResponse
{
Jwt = new Jwt
{
Token = token
}
};
}
}

View File

@@ -1,59 +1,59 @@
using Aoba.RPC;
using AobaCore.Services;
using AobaServer.Models;
using AobaServer.Utils;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using MongoDB.Bson.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace AobaServer.Services;
public class AobaRpcService(AobaService aobaService, AccountsService accountsService, AuthInfo authInfo) : AobaRpc.AobaRpcBase
{
public override async Task<MediaResponse> GetMedia(Id request, ServerCallContext context)
{
var media = await aobaService.GetMediaAsync(request.ToObjectId());
return media.ToResponse();
}
public override async Task<ListResponse> ListMedia(PageFilter request, ServerCallContext context)
{
var user = context.GetUserId();
var result = await aobaService.FindMediaAsync(request.Query, user, request.HasPage ? request.Page : 1, request.HasPageSize ? request.PageSize : 100);
return result.ToResponse();
}
public override async Task<ShareXResponse> GetShareXDestination(Empty request, ServerCallContext context)
{
var userId = context.GetHttpContext().User.GetId();
var user = await accountsService.GetUserAsync(userId, context.CancellationToken);
if (user == null)
return new ShareXResponse { Error = "User does not exist" };
var token = user.GetToken(authInfo);
var dest = new ShareXDestination
{
DeletionURL = string.Empty,
ThumbnailURL = string.Empty,
Headers = new()
{
{ "Authorization", $"Bearer {token}" }
}
};
return new ShareXResponse
{
Destination = JsonSerializer.Serialize(dest, new JsonSerializerOptions
{
WriteIndented = true
})
};
}
using Aoba.RPC;
using AobaCore.Services;
using AobaServer.Models;
using AobaServer.Utils;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using MongoDB.Bson.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace AobaServer.Services;
public class AobaRpcService(AobaService aobaService, AccountsService accountsService, AuthInfo authInfo) : AobaRpc.AobaRpcBase
{
public override async Task<MediaResponse> GetMedia(Id request, ServerCallContext context)
{
var media = await aobaService.GetMediaAsync(request.ToObjectId());
return media.ToResponse();
}
public override async Task<ListResponse> ListMedia(PageFilter request, ServerCallContext context)
{
var user = context.GetUserId();
var result = await aobaService.FindMediaAsync(request.Query, user, request.HasPage ? request.Page : 1, request.HasPageSize ? request.PageSize : 100);
return result.ToResponse();
}
public override async Task<ShareXResponse> GetShareXDestination(Empty request, ServerCallContext context)
{
var userId = context.GetHttpContext().User.GetId();
var user = await accountsService.GetUserAsync(userId, context.CancellationToken);
if (user == null)
return new ShareXResponse { Error = "User does not exist" };
var token = user.GetToken(authInfo);
var dest = new ShareXDestination
{
DeletionURL = string.Empty,
ThumbnailURL = string.Empty,
Headers = new()
{
{ "Authorization", $"Bearer {token}" }
}
};
return new ShareXResponse
{
Destination = JsonSerializer.Serialize(dest, new JsonSerializerOptions
{
WriteIndented = true
})
};
}
}

View File

@@ -1,47 +1,47 @@
using AobaCore.Models;
using AobaServer.Models;
using Grpc.Core;
using Microsoft.IdentityModel.Tokens;
using MongoDB.Bson;
using MongoDB.Driver;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace AobaServer.Utils;
public static class Extensions
{
public static ObjectId ToObjectId(this string? value)
{
if(value == null)
return ObjectId.Empty;
if(ObjectId.TryParse(value, out ObjectId result))
return result;
return ObjectId.Empty;
}
public static string GetToken(this User user, AuthInfo authInfo)
{
var handler = new JwtSecurityTokenHandler();
var signCreds = new SigningCredentials(new SymmetricSecurityKey(authInfo.SecureKey), SecurityAlgorithms.HmacSha256);
var identity = user.GetIdentity();
var token = handler.CreateEncodedJwt(authInfo.Issuer, authInfo.Audience, identity, notBefore: DateTime.Now, expires: null, issuedAt: DateTime.Now, signCreds);
return token;
}
public static ObjectId GetId(this ClaimsPrincipal user)
{
return user.FindFirstValue(ClaimTypes.NameIdentifier).ToObjectId();
}
public static ObjectId GetUserId(this ServerCallContext context)
{
return context.GetHttpContext().User.GetId();
}
}
using AobaCore.Models;
using AobaServer.Models;
using Grpc.Core;
using Microsoft.IdentityModel.Tokens;
using MongoDB.Bson;
using MongoDB.Driver;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace AobaServer.Utils;
public static class Extensions
{
public static ObjectId ToObjectId(this string? value)
{
if(value == null)
return ObjectId.Empty;
if(ObjectId.TryParse(value, out ObjectId result))
return result;
return ObjectId.Empty;
}
public static string GetToken(this User user, AuthInfo authInfo)
{
var handler = new JwtSecurityTokenHandler();
var signCreds = new SigningCredentials(new SymmetricSecurityKey(authInfo.SecureKey), SecurityAlgorithms.HmacSha256);
var identity = user.GetIdentity();
var token = handler.CreateEncodedJwt(authInfo.Issuer, authInfo.Audience, identity, notBefore: DateTime.Now, expires: null, issuedAt: DateTime.Now, signCreds);
return token;
}
public static ObjectId GetId(this ClaimsPrincipal user)
{
return user.FindFirstValue(ClaimTypes.NameIdentifier).ToObjectId();
}
public static ObjectId GetUserId(this ServerCallContext context)
{
return context.GetHttpContext().User.GetId();
}
}

View File

@@ -1,68 +1,68 @@
using AobaCore.Models;
using Aoba.RPC;
using MongoDB.Bson;
using Google.Protobuf.WellKnownTypes;
namespace AobaServer.Utils;
public static class ProtoExtensions
{
public static ListResponse ToResponse(this PagedResult<Media> result)
{
var res = new ListResponse()
{
Pagination = result.ToPagination(),
};
res.Items.AddRange(result.Items.Select(i => i.ToMediaModel()));
return res;
}
public static Pagination ToPagination<T>(this PagedResult<T> result)
{
var p =new Pagination()
{
Page = result.Page,
PageSize = result.PageSize,
TotalItems = result.TotalItems,
TotalPages = result.TotalPages,
};
if(result.Query != null)
p.Query = result.Query;
return p;
}
public static MediaResponse ToResponse(this Media? media)
{
if(media == null)
return new MediaResponse() { Empty = new Empty() };
return new MediaResponse()
{
Value = media.ToMediaModel()
};
}
public static MediaModel ToMediaModel(this Media media)
{
return new MediaModel()
{
Ext = media.Ext,
FileName = media.Filename,
Id = media.Id.ToId(),
MediaId = media.MediaId.ToId(),
MediaType = (Aoba.RPC.MediaType)media.MediaType,
Owner = media.Owner.ToId(),
ViewCount = media.ViewCount,
};
}
public static Id ToId(this ObjectId id)
{
return new Id() { Value = id.ToString() };
}
public static ObjectId ToObjectId(this Id id)
{
return id.Value.ToObjectId();
}
}
using AobaCore.Models;
using Aoba.RPC;
using MongoDB.Bson;
using Google.Protobuf.WellKnownTypes;
namespace AobaServer.Utils;
public static class ProtoExtensions
{
public static ListResponse ToResponse(this PagedResult<Media> result)
{
var res = new ListResponse()
{
Pagination = result.ToPagination(),
};
res.Items.AddRange(result.Items.Select(i => i.ToMediaModel()));
return res;
}
public static Pagination ToPagination<T>(this PagedResult<T> result)
{
var p =new Pagination()
{
Page = result.Page,
PageSize = result.PageSize,
TotalItems = result.TotalItems,
TotalPages = result.TotalPages,
};
if(result.Query != null)
p.Query = result.Query;
return p;
}
public static MediaResponse ToResponse(this Media? media)
{
if(media == null)
return new MediaResponse() { Empty = new Empty() };
return new MediaResponse()
{
Value = media.ToMediaModel()
};
}
public static MediaModel ToMediaModel(this Media media)
{
return new MediaModel()
{
Ext = media.Ext,
FileName = media.Filename,
Id = media.Id.ToId(),
MediaId = media.MediaId.ToId(),
MediaType = (Aoba.RPC.MediaType)media.MediaType,
Owner = media.Owner.ToId(),
ViewCount = media.ViewCount,
};
}
public static Id ToId(this ObjectId id)
{
return new Id() { Value = id.ToString() };
}
public static ObjectId ToObjectId(this Id id)
{
return id.Value.ToObjectId();
}
}

View File

@@ -1,9 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"DB_STRING": "mongodb://NinoIna:27017"
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"DB_STRING": "mongodb://NinoIna:27017"
}

View File

@@ -1,11 +1,11 @@
{
"Kestrel": {
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
{
"Kestrel": {
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
}