chore: import Musify.WebApi into monorepo (preserving history)
git-subtree-dir: Musify.WebApi git-subtree-mainline:9d433868ccgit-subtree-split:ca8750c3b4
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
||||
@@ -0,0 +1,363 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Oo]ut/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
@@ -0,0 +1,3 @@
|
||||
<Solution>
|
||||
<Project Path="WebApi/WebApi.csproj" />
|
||||
</Solution>
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Authentication": {
|
||||
"MetadataAddress": "http://192.168.0.120:8080/.well-known/openid-configuration",
|
||||
"IssuerAddress": "http://192.168.0.120:8080",
|
||||
"AudienceAddress": "375710146774499331",
|
||||
"ClientId": "375710146774499331",
|
||||
"AuthorizationEndpoint": "http://192.168.0.120:8080/oauth/v2/authorize?prompt=login",
|
||||
"TokenEndpoint": "http://192.168.0.120:8080/oauth/v2/token",
|
||||
"Scopes": [ "openid", "profile", "email" ],
|
||||
"ScalarRedirectUri": "http://192.168.0.120:5111/scalar/",
|
||||
"RequireHttpsMetadata": false
|
||||
},
|
||||
"Database": {
|
||||
"ConnectionString": "Host=localhost;Port=59000;Database=musify_db;Username=postgres;Password=postgres"
|
||||
},
|
||||
"MassTransit": {
|
||||
"Address": "rabbitmq://127.0.0.1:5672",
|
||||
"Username": "guest",
|
||||
"Password": "guest"
|
||||
},
|
||||
"InfrastructureStorage": {
|
||||
"Address": "http://localhost:8333",
|
||||
"AccessKey": "admin_access_key",
|
||||
"SecretAccessKey": "admin_secret_key",
|
||||
"ForcePathStyle": true,
|
||||
"UseHttp": true
|
||||
},
|
||||
"ApplicationStorage": {
|
||||
"Bucket": "webapi-storage"
|
||||
},
|
||||
"StreamGateway": {
|
||||
"PublicBaseUrl": "http://localhost:8081",
|
||||
"ManifestFileName": "manifest.mpd"
|
||||
},
|
||||
"StreamTicket": {
|
||||
"PrivateKeyPath": "D:\\weed\\stream_private.pem",
|
||||
"Audience": "media-gateway",
|
||||
"Issuer": "musify-webapi",
|
||||
"TicketTtlSeconds": 3600
|
||||
},
|
||||
"OpenTelemetry": {
|
||||
"OtlpEndpoint": "http://localhost:4317"
|
||||
},
|
||||
"Workers": {
|
||||
"Routes": {
|
||||
"TemporaryFilesDirectory": "D:\\tempsFilesDev"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Authentication": {
|
||||
"MetadataAddress": "",
|
||||
"IssuerAddress": "",
|
||||
"AudienceAddress": "",
|
||||
"ClientId": "",
|
||||
"AuthorizationEndpoint": "",
|
||||
"TokenEndpoint": "",
|
||||
"Scopes": [],
|
||||
"ScalarRedirectUri": "",
|
||||
"RequireHttpsMetadata": true
|
||||
},
|
||||
"Database": {
|
||||
"ConnectionString": ""
|
||||
},
|
||||
"MassTransit": {
|
||||
"Address": "",
|
||||
"Username": "",
|
||||
"Password": ""
|
||||
},
|
||||
"InfrastructureStorage": {
|
||||
"Address": "",
|
||||
"AccessKey": "",
|
||||
"SecretAccessKey": "",
|
||||
"ForcePathStyle": false,
|
||||
"UseHttp": false
|
||||
},
|
||||
"ApplicationStorage": {
|
||||
"Bucket": ""
|
||||
},
|
||||
"StreamGateway": {
|
||||
"PublicBaseUrl": "",
|
||||
"AudioFileName": "audio.m4a"
|
||||
},
|
||||
"StreamTicket": {
|
||||
"PrivateKeyPath": "",
|
||||
"Audience": "media-gateway",
|
||||
"Issuer": "musify-webapi",
|
||||
"TicketTtlSeconds": 3600
|
||||
},
|
||||
"OpenTelemetry": {
|
||||
"OtlpEndpoint": ""
|
||||
},
|
||||
"PlayList": {
|
||||
"Routes": {
|
||||
"UploadsFolder": "uploads",
|
||||
"ParentFolders": "PlayLists",
|
||||
"OriginalPicturesFolder": "OriginalPictures",
|
||||
"SmallPicturesFolder": "SmallPictures",
|
||||
"MediumPicturesFolder": "MediumPictures",
|
||||
"LargePicturesFolder": "LargePictures",
|
||||
"PresetOriginalPicture": "PresetOriginalPicture.webp",
|
||||
"PresetSmallPicture": "PresetSmallPicture.webp",
|
||||
"PresetMediumPicture": "PresetMediumPicture.webp",
|
||||
"PresetLargePicture": "PresetLargePicture.webp"
|
||||
},
|
||||
"PicturesSizes": {
|
||||
"SmallPictureWidth": 128,
|
||||
"SmallPictureHeight": 128,
|
||||
"MediumPictureWidth": 256,
|
||||
"MediumPictureHeight": 256,
|
||||
"LargePictureWidth": 512,
|
||||
"LargePictureHeight": 512
|
||||
}
|
||||
},
|
||||
"Track": {
|
||||
"Routes": {
|
||||
"UploadsFolder": "uploads",
|
||||
"ParentFolder": "Tracks",
|
||||
"OriginalPicturesFolder": "OriginalPictures",
|
||||
"SmallPicturesFolder": "SmallPictures",
|
||||
"MediumPicturesFolder": "MediumPictures",
|
||||
"LargePicturesFolder": "LargePictures",
|
||||
"PresetOriginalPicture": "PresetOriginalPicture.webp",
|
||||
"PresetSmallPicture": "PresetSmallPicture.webp",
|
||||
"PresetMediumPicture": "PresetMediumPicture.webp",
|
||||
"PresetLargePicture": "PresetLargePicture.webp",
|
||||
"OriginalAudiosFolder": "OriginalAudios",
|
||||
"ProcessedAudioFolder": "ProcessedAudios"
|
||||
},
|
||||
"PicturesSizes": {
|
||||
"SmallPictureWidth": 128,
|
||||
"SmallPictureHeight": 128,
|
||||
"MediumPictureWidth": 256,
|
||||
"MediumPictureHeight": 256,
|
||||
"LargePictureWidth": 512,
|
||||
"LargePictureHeight": 512
|
||||
}
|
||||
},
|
||||
"AudioTranscoder": {
|
||||
"TranscodingTimeout": "00:05:00",
|
||||
"Ffmpeg": {
|
||||
"ExecutableName": "ffmpeg",
|
||||
"OutputFileName": "audio.m4a",
|
||||
"AudioCodec": "aac",
|
||||
"AudioBitrate": "128k",
|
||||
"AudioChannels": 2,
|
||||
"AudioSampleRate": 48000,
|
||||
"AudioProfile": "aac_low",
|
||||
"AdditionalArguments": ""
|
||||
}
|
||||
},
|
||||
"UploadIntent": {
|
||||
"UploadUrlExpiresInSeconds": 120,
|
||||
"MaxActiveUploadIntentsPerUser": 5,
|
||||
"MaxActiveUploadBytesPerUser": 209715200,
|
||||
"MaxUploadBytes": 104857600,
|
||||
"DefaultExpectedPictureSizeBytes": 10485760,
|
||||
"DefaultExpectedAudioSizeBytes": 104857600,
|
||||
"ExpirationJobIntervalSeconds": 300,
|
||||
"ExpiredIntentsRetentionDays": 7,
|
||||
"TempRootPrefix": "temp",
|
||||
"TempUploadsRetentionDays": 3,
|
||||
"TempCleanupJobIntervalSeconds": 3600
|
||||
},
|
||||
"Workers": {
|
||||
"Routes": {
|
||||
"TemporaryFilesDirectory": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace WebApi.Authentication;
|
||||
|
||||
public sealed class AuthenticationConfiguration
|
||||
{
|
||||
public const string SectionName = "Authentication";
|
||||
|
||||
[Required]
|
||||
[Url]
|
||||
public required string MetadataAddress { get; set; }
|
||||
|
||||
[Required]
|
||||
public required string IssuerAddress { get; set; }
|
||||
|
||||
[Required]
|
||||
public required string AudienceAddress { get; set; }
|
||||
|
||||
[Required]
|
||||
public required string ClientId { get; set; }
|
||||
|
||||
public string? ClientSecret { get; set; }
|
||||
|
||||
[Required]
|
||||
[Url]
|
||||
public required string AuthorizationEndpoint { get; set; }
|
||||
|
||||
[Required]
|
||||
[Url]
|
||||
public required string TokenEndpoint { get; set; }
|
||||
|
||||
[Required]
|
||||
[MinLength(1)]
|
||||
public required string[] Scopes { get; set; }
|
||||
|
||||
public string? ScalarRedirectUri { get; set; }
|
||||
|
||||
public bool RequireHttpsMetadata { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace WebApi.Authentication;
|
||||
|
||||
public static class AuthenticationExtensions
|
||||
{
|
||||
public static IServiceCollection AddAuthenticationConfiguration(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services
|
||||
.AddOptionsWithValidateOnStart<AuthenticationConfiguration>()
|
||||
.Bind(configuration.GetRequiredSection(AuthenticationConfiguration.SectionName))
|
||||
.ValidateDataAnnotations();
|
||||
|
||||
services.AddSingleton(serviceProvider =>
|
||||
serviceProvider.GetRequiredService<IOptions<AuthenticationConfiguration>>().Value);
|
||||
|
||||
services.AddScoped<JwtBearerEventsHandler>();
|
||||
services.ConfigureOptions<JwtBearerOptionsSetup>();
|
||||
|
||||
services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer();
|
||||
|
||||
services.AddAuthorization();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Reflection;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace WebApi.Authentication;
|
||||
|
||||
public sealed class CurrentUser : IBindableFromHttpContext<CurrentUser>
|
||||
{
|
||||
private CurrentUser(ClaimsPrincipal principal)
|
||||
{
|
||||
Principal = principal;
|
||||
var isAuthenticated = principal.Identity?.IsAuthenticated;
|
||||
IsAuthenticated = isAuthenticated.HasValue && isAuthenticated.Value;
|
||||
|
||||
var rawId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (long.TryParse(rawId, out var id) && id != 0)
|
||||
Id = id;
|
||||
|
||||
Username = principal.FindFirstValue(ClaimTypes.Name);
|
||||
FirstName = principal.FindFirstValue(ClaimTypes.GivenName);
|
||||
LastName = principal.FindFirstValue(ClaimTypes.Surname);
|
||||
}
|
||||
|
||||
public ClaimsPrincipal Principal { get; }
|
||||
|
||||
public bool IsAuthenticated { get; }
|
||||
|
||||
public long? Id { get; }
|
||||
|
||||
public string? Username { get; }
|
||||
|
||||
public string? FirstName { get; }
|
||||
|
||||
public string? LastName { get; }
|
||||
|
||||
public long RequiredId => Id ?? throw new InvalidOperationException("User Id claim is missing or invalid.");
|
||||
|
||||
public bool HasClaim(string type) => Principal.HasClaim(c => c.Type == type);
|
||||
|
||||
public string? FindClaim(string type) => Principal.FindFirstValue(type);
|
||||
|
||||
public static ValueTask<CurrentUser?> BindAsync(HttpContext context, ParameterInfo parameter) =>
|
||||
ValueTask.FromResult<CurrentUser?>(new CurrentUser(context.User));
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Musify.Application.Users.Commands;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace WebApi.Authentication;
|
||||
|
||||
public sealed class JwtBearerEventsHandler(IMediator mediator, ILogger<JwtBearerEventsHandler> logger) : JwtBearerEvents
|
||||
{
|
||||
public override async Task TokenValidated(TokenValidatedContext tokenValidatedContext)
|
||||
{
|
||||
var principal = tokenValidatedContext.Principal!;
|
||||
|
||||
var rawId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!long.TryParse(rawId, out var userId))
|
||||
{
|
||||
logger.LogWarning("Token subject '{Subject}' is not a numeric id; skipping user provisioning", rawId);
|
||||
return;
|
||||
}
|
||||
|
||||
var username = principal.FindFirstValue(ClaimTypes.Name)
|
||||
?? principal.FindFirstValue("preferred_username")
|
||||
?? principal.FindFirstValue(ClaimTypes.Email)
|
||||
?? rawId!;
|
||||
|
||||
var firstName = principal.FindFirstValue(ClaimTypes.GivenName);
|
||||
var lastName = principal.FindFirstValue(ClaimTypes.Surname);
|
||||
var profilePictureUrl = principal.FindFirstValue("picture");
|
||||
|
||||
try
|
||||
{
|
||||
await mediator.Send(
|
||||
new SyncUserCommand(userId, username, firstName, lastName, profilePictureUrl),
|
||||
tokenValidatedContext.HttpContext.RequestAborted);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to sync user {UserId} during token validation", userId);
|
||||
}
|
||||
}
|
||||
|
||||
public override Task AuthenticationFailed(AuthenticationFailedContext context)
|
||||
{
|
||||
logger.LogWarning(context.Exception, "JWT authentication failed");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public override Task Challenge(JwtBearerChallengeContext context)
|
||||
{
|
||||
if (context.AuthenticateFailure is not null)
|
||||
logger.LogWarning("JWT challenge: {Error} - {Description}", context.Error, context.ErrorDescription);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace WebApi.Authentication;
|
||||
|
||||
public sealed class JwtBearerOptionsSetup(IOptions<AuthenticationConfiguration> options)
|
||||
: IConfigureNamedOptions<JwtBearerOptions>
|
||||
{
|
||||
private readonly AuthenticationConfiguration _configuration = options.Value;
|
||||
|
||||
public void Configure(string? name, JwtBearerOptions options)
|
||||
{
|
||||
if (name != JwtBearerDefaults.AuthenticationScheme)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Configure(options);
|
||||
}
|
||||
|
||||
public void Configure(JwtBearerOptions options)
|
||||
{
|
||||
options.MetadataAddress = _configuration.MetadataAddress;
|
||||
options.RequireHttpsMetadata = _configuration.RequireHttpsMetadata;
|
||||
options.Audience = _configuration.AudienceAddress;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = _configuration.IssuerAddress,
|
||||
ValidAudience = _configuration.AudienceAddress,
|
||||
RoleClaimType = ClaimTypes.Role,
|
||||
NameClaimType = ClaimTypes.Name,
|
||||
};
|
||||
options.EventsType = typeof(JwtBearerEventsHandler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace WebApi.DataTransferObjects.PlayLists;
|
||||
|
||||
public record CreatePlayListRequest(
|
||||
string Name,
|
||||
string Description,
|
||||
Guid? PictureIntentId);
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
namespace WebApi.DataTransferObjects.PlayLists;
|
||||
|
||||
public record RequestPlayListPictureUploadRequest(
|
||||
string FileType,
|
||||
string ContentType,
|
||||
long? ExpectedSizeBytes = null);
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace WebApi.DataTransferObjects.PlayLists;
|
||||
|
||||
public record UpdatePlayListRequest(
|
||||
string? NewName,
|
||||
string? NewDescription,
|
||||
Guid? NewPictureIntentId);
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace WebApi.DataTransferObjects.Tracks;
|
||||
|
||||
public record CreateTrackRequest(
|
||||
string Title,
|
||||
Guid PictureIntentId,
|
||||
Guid AudioIntentId);
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace WebApi.DataTransferObjects.Tracks;
|
||||
|
||||
public record RequestTrackUploadUrlsRequest(
|
||||
string PictureFileType,
|
||||
string PictureContentType,
|
||||
string AudioFileType,
|
||||
string AudioContentType,
|
||||
long? ExpectedPictureSizeBytes = null,
|
||||
long? ExpectedAudioSizeBytes = null);
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace WebApi.DataTransferObjects.Users;
|
||||
|
||||
public record CreateUserRequest(
|
||||
long Id,
|
||||
string Name,
|
||||
string? FirstName,
|
||||
string? SecondName);
|
||||
@@ -0,0 +1,192 @@
|
||||
using Mediator;
|
||||
using Musify.Application.PlayLists.Commands;
|
||||
using Musify.Application.PlayLists.Queries;
|
||||
using WebApi.Authentication;
|
||||
using WebApi.DataTransferObjects.PlayLists;
|
||||
using WebApi.Extensions;
|
||||
using WebApi.Filters;
|
||||
|
||||
namespace WebApi.Endpoints;
|
||||
|
||||
public static class PlayListEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapPlayListEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/playLists")
|
||||
.WithTags("PlayLists");
|
||||
|
||||
group.MapGet("/", GetPlayLists)
|
||||
.WithName("GetPlayLists")
|
||||
.WithSummary("Get Paginated PlayLists.");
|
||||
|
||||
group.MapGet("/{id}", GetPlayListById)
|
||||
.WithName("GetPlayListById")
|
||||
.WithSummary("Get A PlayList By Id.");
|
||||
|
||||
group.MapGet("/users/{userId}", GetPlayListsByUserId)
|
||||
.WithName("GetPlayListsByUserId")
|
||||
.WithSummary("Get Paginated PlayLists For A User.");
|
||||
|
||||
group.MapGet("/{playlistId}/tracks", GetPlayListTracks)
|
||||
.WithName("GetPlayListTracks")
|
||||
.WithSummary("Get Paginated Tracks Of A PlayList.");
|
||||
|
||||
group.MapPost("/", CreatePlayList)
|
||||
.WithName("CreatePlayList")
|
||||
.WithSummary("Create A New PlayList.")
|
||||
.AddEndpointFilter<ValidationFilter<CreatePlayListRequest>>()
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapPut("/{playlistId}", UpdatePlayList)
|
||||
.WithName("UpdatePlayList")
|
||||
.WithSummary("Update An Existing PlayList.")
|
||||
.AddEndpointFilter<ValidationFilter<UpdatePlayListRequest>>()
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapDelete("/{playlistId}", DeletePlayList)
|
||||
.WithName("DeletePlayList")
|
||||
.WithSummary("Delete A PlayList.")
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapPost("/upload-picture", RequestPlayListPictureUpload)
|
||||
.WithName("RequestPlayListPictureUpload")
|
||||
.WithSummary("Request A Pre-Signed URL To Upload A PlayList Picture.")
|
||||
.AddEndpointFilter<ValidationFilter<RequestPlayListPictureUploadRequest>>()
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapPost("/{playlistId}/tracks/{trackId}", AddTrackToPlayList)
|
||||
.WithName("AddTrackToPlayList")
|
||||
.WithSummary("Add A Track To A PlayList.")
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapDelete("/{playlistId}/tracks/{trackId}", RemoveTrackFromPlayList)
|
||||
.WithName("RemoveTrackFromPlayList")
|
||||
.WithSummary("Remove A Track From A PlayList.")
|
||||
.RequireAuthorization();
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetPlayLists(
|
||||
IMediator mediator,
|
||||
CancellationToken cancellationToken,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
{
|
||||
var result = await mediator.Send(new GetPlayListsQuery(pageNumber, pageSize), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetPlayListById(
|
||||
IMediator mediator,
|
||||
Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetPlayListByIdQuery(id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetPlayListsByUserId(
|
||||
IMediator mediator,
|
||||
long userId,
|
||||
CancellationToken cancellationToken,
|
||||
string? name,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
{
|
||||
var result = await mediator.Send(new GetPlayListsByUserIdQuery(userId, name, pageNumber, pageSize), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetPlayListTracks(
|
||||
IMediator mediator,
|
||||
Guid playlistId,
|
||||
CancellationToken cancellationToken,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
{
|
||||
var result = await mediator.Send(new GetPlayListTracksQuery(playlistId, pageNumber, pageSize), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreatePlayList(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
CreatePlayListRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new CreatePlayListCommand(currentUser.RequiredId, request.Name, request.Description, request.PictureIntentId),
|
||||
cancellationToken);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
return result.ToHttpResult();
|
||||
|
||||
return Results.Created($"/playlists/{result.Value.Id}", result.Value);
|
||||
}
|
||||
|
||||
private static async Task<IResult> UpdatePlayList(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid playlistId,
|
||||
UpdatePlayListRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new UpdatePlayListCommand(currentUser.RequiredId, playlistId, request.NewName, request.NewDescription, request.NewPictureIntentId),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeletePlayList(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid playlistId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new DeletePlayListCommand(currentUser.RequiredId, playlistId), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> RequestPlayListPictureUpload(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
RequestPlayListPictureUploadRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new RequestPlayListPictureUploadCommand(currentUser.RequiredId, request.FileType, request.ContentType, request.ExpectedSizeBytes),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> AddTrackToPlayList(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid playlistId,
|
||||
Guid trackId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new AddTrackToPlayListCommand(currentUser.RequiredId, playlistId, trackId),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> RemoveTrackFromPlayList(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid playlistId,
|
||||
Guid trackId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new RemoveTrackFromPlayListCommand(currentUser.RequiredId, playlistId, trackId),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using Mediator;
|
||||
using Musify.Application.Tracks.Commands;
|
||||
using Musify.Application.Tracks.Queries;
|
||||
using WebApi.Authentication;
|
||||
using WebApi.DataTransferObjects.Tracks;
|
||||
using WebApi.Extensions;
|
||||
using WebApi.Filters;
|
||||
|
||||
namespace WebApi.Endpoints;
|
||||
|
||||
public static class TrackEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapTrackEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/tracks")
|
||||
.WithTags("Tracks");
|
||||
|
||||
group.MapGet("/", GetTracks)
|
||||
.WithName("GetTracks")
|
||||
.WithSummary("Get Paginated Tracks.");
|
||||
|
||||
group.MapGet("/{id}", GetTrackById)
|
||||
.WithName("GetTrackById")
|
||||
.WithSummary("Get A Track By Id.");
|
||||
|
||||
group.MapGet("/{id}/stream", GetTrackStream)
|
||||
.WithName("GetTrackStream")
|
||||
.WithSummary("Get A Streaming Manifest URL And Ticket For A Track.")
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapGet("/users/{userId}", GetTracksByUserId)
|
||||
.WithName("GetTracksByUserId")
|
||||
.WithSummary("Get Paginated Tracks For A User.");
|
||||
|
||||
group.MapPost("/", CreateTrack)
|
||||
.WithName("CreateTrack")
|
||||
.WithSummary("Create A New Track.")
|
||||
.AddEndpointFilter<ValidationFilter<CreateTrackRequest>>()
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapDelete("/{trackId}", DeleteTrack)
|
||||
.WithName("DeleteTrack")
|
||||
.WithSummary("Delete A Track.")
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapPost("/upload-urls", RequestTrackUploadUrls)
|
||||
.WithName("RequestTrackUploadUrls")
|
||||
.WithSummary("Request Pre-Signed URLs To Upload Track Picture And Audio.")
|
||||
.AddEndpointFilter<ValidationFilter<RequestTrackUploadUrlsRequest>>()
|
||||
.RequireAuthorization();
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetTracks(
|
||||
IMediator mediator,
|
||||
CancellationToken cancellationToken,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
{
|
||||
var result = await mediator.Send(new GetTracksQuery(pageNumber, pageSize), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetTrackById(
|
||||
IMediator mediator,
|
||||
Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetTrackByIdQuery(id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetTrackStream(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetTrackStreamQuery(id, currentUser.RequiredId), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetTracksByUserId(
|
||||
IMediator mediator,
|
||||
long userId,
|
||||
CancellationToken cancellationToken,
|
||||
string? name,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
{
|
||||
var result = await mediator.Send(new GetTracksByUserIdQuery(userId, name, pageNumber, pageSize), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateTrack(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
CreateTrackRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new CreateTrackCommand(currentUser.RequiredId, request.Title, request.PictureIntentId, request.AudioIntentId),
|
||||
cancellationToken);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
return result.ToHttpResult();
|
||||
|
||||
return Results.Created($"/tracks/{result.Value.Id}", result.Value);
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeleteTrack(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid trackId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new DeleteTrackCommand(currentUser.RequiredId, trackId), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> RequestTrackUploadUrls(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
RequestTrackUploadUrlsRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new RequestTrackUploadUrlsCommand(
|
||||
currentUser.RequiredId,
|
||||
request.PictureFileType,
|
||||
request.PictureContentType,
|
||||
request.AudioFileType,
|
||||
request.AudioContentType,
|
||||
request.ExpectedPictureSizeBytes,
|
||||
request.ExpectedAudioSizeBytes),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Mediator;
|
||||
using Musify.Application.Users.Commands;
|
||||
using Musify.Application.Users.Queries;
|
||||
using WebApi.DataTransferObjects.Users;
|
||||
using WebApi.Extensions;
|
||||
using WebApi.Filters;
|
||||
|
||||
namespace WebApi.Endpoints;
|
||||
|
||||
public static class UserEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapUserEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/users")
|
||||
.WithTags("Users");
|
||||
|
||||
group.MapGet("/", GetUsers)
|
||||
.WithName("GetUsers")
|
||||
.WithSummary("Get Paginated Users.");
|
||||
|
||||
group.MapGet("/{id}", GetUserById)
|
||||
.WithName("GetUserById")
|
||||
.WithSummary("Get A User By Id.");
|
||||
|
||||
group.MapPost("/", CreateUser)
|
||||
.WithName("CreateUser")
|
||||
.WithSummary("Create A New User.")
|
||||
.AddEndpointFilter<ValidationFilter<CreateUserRequest>>();
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetUsers(
|
||||
IMediator mediator,
|
||||
CancellationToken cancellationToken,
|
||||
string? usernameSearch,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
{
|
||||
var result = await mediator.Send(new GetUsersQuery(pageNumber, pageSize, usernameSearch), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetUserById(
|
||||
IMediator mediator,
|
||||
long id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetUserByIdQuery(id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateUser(
|
||||
IMediator mediator,
|
||||
CreateUserRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new CreateUserCommand(request.Id, request.Name, request.FirstName, request.SecondName),
|
||||
cancellationToken);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
return result.ToHttpResult();
|
||||
|
||||
return Results.Created($"/users/{result.Value.Id}", result.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Ardalis.Result;
|
||||
using IResult = Microsoft.AspNetCore.Http.IResult;
|
||||
|
||||
namespace WebApi.Extensions;
|
||||
|
||||
public static class ResultHttpExtensions
|
||||
{
|
||||
public static IResult ToHttpResult(this Result result) =>
|
||||
result.Status switch
|
||||
{
|
||||
ResultStatus.Ok or ResultStatus.NoContent => Results.NoContent(),
|
||||
ResultStatus.NotFound => Results.NotFound(result.Errors.FirstOrDefault()),
|
||||
ResultStatus.Invalid => Results.ValidationProblem(ToValidationDictionary(result.ValidationErrors)),
|
||||
ResultStatus.Unauthorized => Results.Unauthorized(),
|
||||
ResultStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden),
|
||||
ResultStatus.Conflict => Results.Conflict(result.Errors.FirstOrDefault()),
|
||||
_ => Results.Problem(string.Join(", ", result.Errors))
|
||||
};
|
||||
|
||||
public static IResult ToHttpResult<T>(this Result<T> result) =>
|
||||
result.Status switch
|
||||
{
|
||||
ResultStatus.Ok => Results.Ok(result.Value),
|
||||
ResultStatus.NotFound => Results.NotFound(result.Errors.FirstOrDefault()),
|
||||
ResultStatus.Invalid => Results.ValidationProblem(ToValidationDictionary(result.ValidationErrors)),
|
||||
ResultStatus.Unauthorized => Results.Unauthorized(),
|
||||
ResultStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden),
|
||||
ResultStatus.Conflict => Results.Conflict(result.Errors.FirstOrDefault()),
|
||||
_ => Results.Problem(string.Join(", ", result.Errors))
|
||||
};
|
||||
|
||||
private static Dictionary<string, string[]> ToValidationDictionary(IEnumerable<ValidationError> errors) =>
|
||||
errors
|
||||
.GroupBy(e => string.IsNullOrEmpty(e.Identifier) ? "general" : e.Identifier)
|
||||
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray());
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using FluentValidation;
|
||||
using Musify.Infrastructure.MassTransit;
|
||||
using Musify.Infrastructure.Persistence;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Infrastructure.Services;
|
||||
using WebApi.Authentication;
|
||||
using WebApi.DataTransferObjects.PlayLists;
|
||||
using WebApi.OpenApi;
|
||||
using WebApi.Scalar;
|
||||
|
||||
namespace WebApi.Extensions;
|
||||
|
||||
public static class ServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddDatabase(configuration);
|
||||
services.AddApplicationStorageConfiguration(configuration);
|
||||
services.AddPlayListConfiguration(configuration);
|
||||
services.AddTrackConfiguration(configuration);
|
||||
services.AddStreamGatewayConfiguration(configuration);
|
||||
services.AddStorageService(configuration);
|
||||
services.AddStreamTicketService(configuration);
|
||||
services.AddUploadIntentConfiguration(configuration);
|
||||
services.AddMassTransitClient(configuration);
|
||||
services.AddMediator();
|
||||
services.AddAuthenticationConfiguration(configuration);
|
||||
services.AddOpenApiConfiguration();
|
||||
services.AddScalarConfiguration();
|
||||
services.AddValidatorsFromAssemblyContaining<CreatePlayListRequest>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace WebApi.Filters;
|
||||
|
||||
public sealed class ValidationFilter<T>(IValidator<T> validator) : IEndpointFilter where T : class
|
||||
{
|
||||
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
||||
{
|
||||
var argument = context.Arguments.OfType<T>().FirstOrDefault();
|
||||
|
||||
if (argument is null)
|
||||
return await next(context);
|
||||
|
||||
var result = await validator.ValidateAsync(argument, context.HttpContext.RequestAborted);
|
||||
|
||||
return result.IsValid
|
||||
? await next(context)
|
||||
: Results.ValidationProblem(result.ToDictionary());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
|
||||
namespace WebApi.OpenApi;
|
||||
|
||||
public static class OpenApiExtensions
|
||||
{
|
||||
public static IServiceCollection AddOpenApiConfiguration(this IServiceCollection services)
|
||||
{
|
||||
services.AddOpenApi();
|
||||
services.ConfigureOptions<OpenApiOptionsSetup>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using WebApi.Authentication;
|
||||
|
||||
namespace WebApi.OpenApi;
|
||||
|
||||
public sealed class OpenApiOptionsSetup(IOptions<AuthenticationConfiguration> options)
|
||||
: IConfigureNamedOptions<OpenApiOptions>
|
||||
{
|
||||
private const string SecuritySchemeId = "OAuth2";
|
||||
|
||||
private readonly AuthenticationConfiguration _configuration = options.Value;
|
||||
|
||||
public void Configure(string? name, OpenApiOptions options) => Configure(options);
|
||||
|
||||
public void Configure(OpenApiOptions options)
|
||||
{
|
||||
options.AddDocumentTransformer((document, _, _) =>
|
||||
{
|
||||
document.Components ??= new OpenApiComponents();
|
||||
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
|
||||
document.Components.SecuritySchemes[SecuritySchemeId] = new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.OAuth2,
|
||||
Flows = new OpenApiOAuthFlows
|
||||
{
|
||||
AuthorizationCode = new OpenApiOAuthFlow
|
||||
{
|
||||
AuthorizationUrl = new Uri(_configuration.AuthorizationEndpoint),
|
||||
TokenUrl = new Uri(_configuration.TokenEndpoint),
|
||||
Scopes = _configuration.Scopes.ToDictionary(scope => scope, scope => scope),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
options.AddOperationTransformer((operation, context, _) =>
|
||||
{
|
||||
var requiresAuthorization = context.Description.ActionDescriptor.EndpointMetadata
|
||||
.OfType<IAuthorizeData>()
|
||||
.Any();
|
||||
|
||||
var allowsAnonymous = context.Description.ActionDescriptor.EndpointMetadata
|
||||
.OfType<IAllowAnonymous>()
|
||||
.Any();
|
||||
|
||||
if (!requiresAuthorization || allowsAnonymous)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
operation.Security ??= new List<OpenApiSecurityRequirement>();
|
||||
operation.Security.Add(new OpenApiSecurityRequirement
|
||||
{
|
||||
[new OpenApiSecuritySchemeReference(SecuritySchemeId, context.Document)] =
|
||||
_configuration.Scopes.ToList(),
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Musify.Infrastructure.Observability;
|
||||
using Scalar.AspNetCore;
|
||||
using WebApi.Endpoints;
|
||||
using WebApi.Extensions;
|
||||
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
|
||||
const string devCorsPolicy = "dev-cors";
|
||||
|
||||
builder.Services
|
||||
.AddApplicationServices(builder.Configuration)
|
||||
.AddObservability(builder.Configuration);
|
||||
|
||||
if (builder.Environment.IsDevelopment())
|
||||
{
|
||||
builder.Services.AddCors(options => options.AddPolicy(devCorsPolicy, policy =>
|
||||
policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseCors(devCorsPolicy);
|
||||
app.MapOpenApi();
|
||||
app.MapScalarApiReference();
|
||||
}
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app
|
||||
.MapPlayListEndpoints()
|
||||
.MapTrackEndpoints()
|
||||
.MapUserEndpoints();
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://192.168.0.120:5111",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace WebApi.Scalar;
|
||||
|
||||
public static class ScalarExtensions
|
||||
{
|
||||
public static IServiceCollection AddScalarConfiguration(this IServiceCollection services)
|
||||
{
|
||||
services.ConfigureOptions<ScalarOptionsSetup>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using Scalar.AspNetCore;
|
||||
using WebApi.Authentication;
|
||||
|
||||
namespace WebApi.Scalar;
|
||||
|
||||
public sealed class ScalarOptionsSetup(IOptions<AuthenticationConfiguration> options)
|
||||
: IConfigureOptions<ScalarOptions>
|
||||
{
|
||||
private const string SecuritySchemeId = "OAuth2";
|
||||
|
||||
private readonly AuthenticationConfiguration _configuration = options.Value;
|
||||
|
||||
public void Configure(ScalarOptions scalarOptions)
|
||||
{
|
||||
scalarOptions
|
||||
.WithTitle("Musify API")
|
||||
.AddPreferredSecuritySchemes(SecuritySchemeId)
|
||||
.AddAuthorizationCodeFlow(SecuritySchemeId, flow =>
|
||||
{
|
||||
flow.ClientId = _configuration.ClientId;
|
||||
flow.ClientSecret = _configuration.ClientSecret;
|
||||
flow.AuthorizationUrl = _configuration.AuthorizationEndpoint;
|
||||
flow.TokenUrl = _configuration.TokenEndpoint;
|
||||
flow.Pkce = Pkce.Sha256;
|
||||
flow.SelectedScopes = _configuration.Scopes;
|
||||
flow.RedirectUri = _configuration.ScalarRedirectUri;
|
||||
flow.RefreshUrl = _configuration.TokenEndpoint;
|
||||
} )
|
||||
.HideModels();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using FluentValidation;
|
||||
using WebApi.DataTransferObjects.PlayLists;
|
||||
|
||||
namespace WebApi.Validators.PlayLists;
|
||||
|
||||
public sealed class CreatePlayListRequestValidator : AbstractValidator<CreatePlayListRequest>
|
||||
{
|
||||
public CreatePlayListRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty()
|
||||
.MaximumLength(50);
|
||||
|
||||
RuleFor(x => x.Description)
|
||||
.NotEmpty()
|
||||
.MaximumLength(256);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
using FluentValidation;
|
||||
using WebApi.DataTransferObjects.PlayLists;
|
||||
|
||||
namespace WebApi.Validators.PlayLists;
|
||||
|
||||
public sealed class RequestPlayListPictureUploadRequestValidator : AbstractValidator<RequestPlayListPictureUploadRequest>
|
||||
{
|
||||
public RequestPlayListPictureUploadRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.FileType)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.ContentType)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.ExpectedSizeBytes)
|
||||
.GreaterThan(0)
|
||||
.When(x => x.ExpectedSizeBytes.HasValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using FluentValidation;
|
||||
using WebApi.DataTransferObjects.PlayLists;
|
||||
|
||||
namespace WebApi.Validators.PlayLists;
|
||||
|
||||
public sealed class UpdatePlayListRequestValidator : AbstractValidator<UpdatePlayListRequest>
|
||||
{
|
||||
public UpdatePlayListRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.NewName)
|
||||
.MaximumLength(50)
|
||||
.When(x => x.NewName is not null);
|
||||
|
||||
RuleFor(x => x.NewDescription)
|
||||
.MaximumLength(256)
|
||||
.When(x => x.NewDescription is not null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using FluentValidation;
|
||||
using WebApi.DataTransferObjects.Tracks;
|
||||
|
||||
namespace WebApi.Validators.Tracks;
|
||||
|
||||
public sealed class CreateTrackRequestValidator : AbstractValidator<CreateTrackRequest>
|
||||
{
|
||||
public CreateTrackRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Title)
|
||||
.NotEmpty()
|
||||
.MaximumLength(50);
|
||||
|
||||
RuleFor(x => x.PictureIntentId)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.AudioIntentId)
|
||||
.NotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using FluentValidation;
|
||||
using WebApi.DataTransferObjects.Tracks;
|
||||
|
||||
namespace WebApi.Validators.Tracks;
|
||||
|
||||
public sealed class RequestTrackUploadUrlsRequestValidator : AbstractValidator<RequestTrackUploadUrlsRequest>
|
||||
{
|
||||
public RequestTrackUploadUrlsRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.PictureFileType)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.PictureContentType)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.AudioFileType)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.AudioContentType)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.ExpectedPictureSizeBytes)
|
||||
.GreaterThan(0)
|
||||
.When(x => x.ExpectedPictureSizeBytes.HasValue);
|
||||
|
||||
RuleFor(x => x.ExpectedAudioSizeBytes)
|
||||
.GreaterThan(0)
|
||||
.When(x => x.ExpectedAudioSizeBytes.HasValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using FluentValidation;
|
||||
using WebApi.DataTransferObjects.Users;
|
||||
|
||||
namespace WebApi.Validators.Users;
|
||||
|
||||
public sealed class CreateUserRequestValidator : AbstractValidator<CreateUserRequest>
|
||||
{
|
||||
public CreateUserRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Id)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty()
|
||||
.MaximumLength(48);
|
||||
|
||||
RuleFor(x => x.FirstName)
|
||||
.MaximumLength(48)
|
||||
.When(x => x.FirstName is not null);
|
||||
|
||||
RuleFor(x => x.SecondName)
|
||||
.MaximumLength(48)
|
||||
.When(x => x.SecondName is not null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>1c3fa41c-6f07-433b-af79-1f67fad338fd</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Ardalis.Result" Version="10.1.0" />
|
||||
<PackageReference Include="AWSSDK.S3" Version="4.0.23.4" />
|
||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1" />
|
||||
<PackageReference Include="MassTransit" Version="8.5.9" />
|
||||
<PackageReference Include="MassTransit.EntityFrameworkCore" Version="8.5.9" />
|
||||
<PackageReference Include="MassTransit.RabbitMQ" Version="8.5.9" />
|
||||
<PackageReference Include="Mediator.Abstractions" Version="3.0.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.8" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2" />
|
||||
<PackageReference Include="OpenTelemetry" Version="1.15.3" />
|
||||
<PackageReference Include="OpenTelemetry.Api" Version="1.15.3" />
|
||||
<PackageReference Include="OpenTelemetry.Api.ProviderBuilderExtensions" Version="1.15.3" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.15.3" />
|
||||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.15.3" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.15.2" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.15.1" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.15.1" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.14.14" />
|
||||
<PackageReference Include="X.PagedList.EF" Version="10.5.9" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\MusifyBackend\Application\Application.csproj" />
|
||||
<ProjectReference Include="..\..\MusifyBackend\Domain\Domain.csproj" />
|
||||
<ProjectReference Include="..\..\MusifyBackend\Infrastructure\Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@WebApi_HostAddress = http://localhost:5111
|
||||
|
||||
GET {{WebApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
Reference in New Issue
Block a user