Merge branch 'feature/user-management' into 'dev'

Resolve "User management"

Closes #1

See merge request leon.hoppe/spotiparty!2
This commit was merged in pull request #5.
This commit is contained in:
2026-01-18 19:36:48 +01:00
35 changed files with 546 additions and 70 deletions

41
.gitlab-ci.yml Normal file
View File

@@ -0,0 +1,41 @@
stages:
- build
- test
- publish
variables:
DOCKER_IMAGE: registry.leon-hoppe.de/leon.hoppe/spotiparty
build:
stage: build
image: mcr.microsoft.com/dotnet/sdk:9.0
script:
- dotnet restore
- dotnet build --configuration Release --no-restore
artifacts:
paths:
- "**/bin/Release"
expire_in: 10 minutes
test:
stage: test
image: mcr.microsoft.com/dotnet/sdk:9.0
script:
- dotnet test --verbosity normal
dependencies:
- build
publish:
stage: publish
tags:
- docker
before_script:
- git lfs pull
script:
- export VERSION=$(echo $CI_COMMIT_TAG | sed 's/^v//')
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin registry.leon-hoppe.de
- docker build -t $DOCKER_IMAGE:$VERSION -t $DOCKER_IMAGE:latest -f SpotiParty.Web/Dockerfile .
- docker push $DOCKER_IMAGE:$VERSION
- docker push $DOCKER_IMAGE:latest
only:
- tags

View File

@@ -0,0 +1,7 @@
<component name="ProjectDictionaryState">
<dictionary name="project">
<words>
<w>Spoti</w>
</words>
</dictionary>
</component>

View File

@@ -1,4 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" /> <component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise">
<file url="file://$PROJECT_DIR$/SpotiParty.Web/Components/Pages/LoginPage.razor" charset="US-ASCII" />
</component>
</project> </project>

View File

@@ -0,0 +1,3 @@
{
"appHostPath": "../SpotiParty.AppHost.csproj"
}

View File

@@ -2,6 +2,13 @@ using Projects;
var builder = DistributedApplication.CreateBuilder(args); var builder = DistributedApplication.CreateBuilder(args);
var web = builder.AddProject<SpotiParty_Web>("web"); var dbServer = builder.AddPostgres("database")
.WithDataVolume();
var database = dbServer.AddDatabase("SpotiParty");
var web = builder.AddProject<SpotiParty_Web>("web")
.WithReference(database)
.WaitForStart(database);
builder.Build().Run(); builder.Build().Run();

View File

@@ -4,7 +4,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UserSecretsId>fe08e5bf-d119-470a-a4cc-7686f019ce64</UserSecretsId> <UserSecretsId>fe08e5bf-d119-470a-a4cc-7686f019ce64</UserSecretsId>
@@ -12,6 +12,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="13.0.1" /> <PackageReference Include="Aspire.Hosting.AppHost" Version="13.0.1" />
<PackageReference Include="Aspire.Hosting.PostgreSQL" Version="13.0.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<IsAspireSharedProject>true</IsAspireSharedProject> <IsAspireSharedProject>true</IsAspireSharedProject>

View File

@@ -9,7 +9,7 @@
<link rel="stylesheet" href="@Assets["app.css"]"/> <link rel="stylesheet" href="@Assets["app.css"]"/>
<link rel="stylesheet" href="@Assets["SpotiParty.Web.styles.css"]"/> <link rel="stylesheet" href="@Assets["SpotiParty.Web.styles.css"]"/>
<ImportMap/> <ImportMap/>
<link rel="icon" type="image/png" href="favicon.png"/> <link rel="icon" href="favicon.ico"/>
<HeadOutlet/> <HeadOutlet/>
</head> </head>

View File

@@ -0,0 +1,27 @@
@page "/callback"
@using SpotiParty.Web.Services
@inject NavigationManager Navigator
@inject AuthorizationHandler AuthHandler
@code {
[Parameter, SupplyParameterFromQuery(Name = "error")]
public string? Error { get; set; }
[Parameter, SupplyParameterFromQuery(Name = "code")]
public string? Code { get; set; }
[Parameter, SupplyParameterFromQuery(Name = "state")]
public string? State { get; set; }
protected override async Task OnInitializedAsync() {
await base.OnInitializedAsync();
if (string.IsNullOrWhiteSpace(Code)) {
Navigator.NavigateTo("/login", forceLoad: true);
return;
}
await AuthHandler.HandleCallback(Code);
Navigator.NavigateTo("/admin", forceLoad: true);
}
}

View File

@@ -1,15 +1,17 @@
@page "/enqueue" @page "/enqueue/{eventId}"
@using SpotiParty.Web.Components.Components @using SpotiParty.Web.Components.Components
@rendermode InteractiveServer @rendermode InteractiveServer
<PageTitle>SpotiParty</PageTitle>
<header> <header>
<h1>🎵 SpotiParty</h1> <h1>@(_event?.Name ?? " ")</h1>
<p>Suche ein Lied und füge es zur Warteschlange hinzu</p> <p>Suche ein Lied und füge es zur Warteschlange hinzu</p>
</header> </header>
<main> <main>
<form class="search-section" @onsubmit="ExecuteSearch"> <form class="search-section" @onsubmit="ExecuteSearch">
<input type="text" id="searchInput" placeholder="Song oder Künstler suchen..." @onchange="e => _searchText = e.Value!.ToString()!"> <input type="search" id="searchInput" placeholder="Song oder Künstler suchen..." @onchange="e => _searchText = e.Value!.ToString()!">
<button class="button-primary" type="submit" disabled=@_isLoading>Suchen</button> <button class="button-primary" type="submit" disabled=@_isLoading>Suchen</button>
</form> </form>
@@ -27,7 +29,7 @@
</main> </main>
<footer> <footer>
<p>SpotiParty © @_currentYear</p> <p><a href="https://git.leon-hoppe.de/leon.hoppe/spotiparty" target="_blank">SpotiParty</a> © @_currentYear</p>
</footer> </footer>
<dialog class="confirm-dialog" style="display: @(_selectedTrack is null ? "none" : "block")"> <dialog class="confirm-dialog" style="display: @(_selectedTrack is null ? "none" : "block")">

View File

@@ -1,10 +1,18 @@
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using SpotifyAPI.Web; using SpotifyAPI.Web;
using SpotiParty.Web.Models;
using SpotiParty.Web.Services; using SpotiParty.Web.Services;
namespace SpotiParty.Web.Components.Pages; namespace SpotiParty.Web.Components.Pages;
public partial class EnqueuePage(AuthorizationHandler authHandler) : ComponentBase { public partial class EnqueuePage(AuthorizationHandler authHandler, NavigationManager navigator, DatabaseContext context) : ComponentBase {
[Parameter]
public string EventId { get; set; } = string.Empty;
private Event? _event;
private readonly int _currentYear = DateTime.Now.Year; private readonly int _currentYear = DateTime.Now.Year;
private SpotifyClient _client = null!; private SpotifyClient _client = null!;
@@ -17,7 +25,37 @@ public partial class EnqueuePage(AuthorizationHandler authHandler) : ComponentBa
protected override async Task OnInitializedAsync() { protected override async Task OnInitializedAsync() {
await base.OnInitializedAsync(); await base.OnInitializedAsync();
_client = await authHandler.ConfigureClient();
if (!Guid.TryParse(EventId, out var guid)) {
navigator.NavigateTo("/", forceLoad: true);
return;
}
_event = await context.Events
.Include(e => e.Host)
.FirstOrDefaultAsync(e => e.Id == guid);
if (_event is null) {
navigator.NavigateTo("/", forceLoad: true);
return;
}
StateHasChanged();
var now = DateTime.Now;
if (_event.Start > now || _event.End < now) {
navigator.NavigateTo("/", forceLoad: true);
return;
}
var client = await authHandler.ConfigureClient(_event.Host.UserId);
if (client is null) {
navigator.NavigateTo("/", forceLoad: true);
return;
}
_client = client;
} }
private async Task ExecuteSearch() { private async Task ExecuteSearch() {
@@ -51,9 +89,8 @@ public partial class EnqueuePage(AuthorizationHandler authHandler) : ComponentBa
private async Task DialogAccept() { private async Task DialogAccept() {
if (_selectedTrack is null || _isAdding) return; if (_selectedTrack is null || _isAdding) return;
_isAdding = true; _isAdding = true;
/*var request = new PlayerAddToQueueRequest(_selectedTrack.Uri); var request = new PlayerAddToQueueRequest(_selectedTrack.Uri);
await _client.Player.AddToQueue(request);*/ await _client.Player.AddToQueue(request);
await Task.Delay(3000); //TODO: Simulate adding
_isAdding = false; _isAdding = false;
_success = true; _success = true;

View File

@@ -8,6 +8,7 @@
header h1 { header h1 {
margin: 0; margin: 0;
font-size: 2rem; font-size: 2rem;
height: 2rem;
&:focus { &:focus {
outline: none; outline: none;
@@ -63,6 +64,10 @@ footer {
text-align: center; text-align: center;
padding: 0.5rem; padding: 0.5rem;
background: var(--color-primary); background: var(--color-primary);
a {
color: var(--color-text);
}
} }
.confirm-dialog { .confirm-dialog {
@@ -105,16 +110,3 @@ footer {
background: var(--color-background-light) !important; background: var(--color-background-light) !important;
} }
.button-secondary {
padding: 0.6rem 1rem;
border: none;
border-radius: 5px;
background: var(--color-accent);
color: var(--color-text);
cursor: pointer;
}
.button-secondary:hover {
background: #555555;
}

View File

@@ -0,0 +1,6 @@
@page "/"
<h3>HomePage</h3>
@code {
}

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,15 @@
@page "/login"
@using SpotiParty.Web.Services
@inject AuthorizationHandler AuthHandler
@inject NavigationManager Navigator
@code {
protected override async Task OnInitializedAsync() {
await base.OnInitializedAsync();
var uri = await AuthHandler.ConstructLoginUri();
Navigator.NavigateTo(uri.ToString(), forceLoad: true);
}
}

View File

@@ -6,7 +6,7 @@
protected override void OnInitialized() { protected override void OnInitialized() {
base.OnInitialized(); base.OnInitialized();
Navigator.NavigateTo("/enqueue", forceLoad: true); Navigator.NavigateTo("/", forceLoad: true);
} }
} }

View File

@@ -1,4 +1,4 @@
<Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)"> <Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData"> <Found Context="routeData">
<RouteView RouteData="routeData"/> <RouteView RouteData="routeData"/>
<FocusOnNavigate RouteData="routeData" Selector="h1"/> <FocusOnNavigate RouteData="routeData" Selector="h1"/>

View File

@@ -0,0 +1,12 @@
using Microsoft.EntityFrameworkCore;
using SpotiParty.Web.Models;
namespace SpotiParty.Web;
public class DatabaseContext(DbContextOptions<DatabaseContext> options) : DbContext(options) {
public DbSet<User> Users { get; set; }
public DbSet<Event> Events { get; set; }
}

View File

@@ -1,10 +1,10 @@
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
USER $APP_UID USER $APP_UID
WORKDIR /app WORKDIR /app
EXPOSE 8080 EXPOSE 8080
EXPOSE 8081 EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release ARG BUILD_CONFIGURATION=Release
WORKDIR /src WORKDIR /src
COPY ["SpotiParty.Web/SpotiParty.Web.csproj", "SpotiParty.Web/"] COPY ["SpotiParty.Web/SpotiParty.Web.csproj", "SpotiParty.Web/"]

View File

@@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SpotiParty.Web.Models;
public class Event {
[Key]
public Guid Id { get; init; } = Guid.CreateVersion7();
[ForeignKey("host")]
public virtual required User Host { get; set; }
[MaxLength(255)]
public required string Name { get; set; }
public DateTime Start { get; set; } = DateTime.Today;
public DateTime End { get; set; } = DateTime.Today + TimeSpan.FromDays(1);
}

View File

@@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations;
namespace SpotiParty.Web.Models;
public class User {
[Key]
public Guid UserId { get; init; } = Guid.CreateVersion7();
[MaxLength(255)]
public required string SpotifyUserId { get; init; }
[MaxLength(255)]
public required string DisplayName { get; init; }
[MaxLength(255)]
public required string RefreshToken { get; set; }
public bool IsAdmin { get; set; }
}

View File

@@ -1,15 +1,76 @@
using HopFrame.Core.Services;
using HopFrame.Web;
using Microsoft.EntityFrameworkCore;
using SpotiParty.Web;
using SpotiParty.Web.Components; using SpotiParty.Web.Components;
using SpotiParty.Web.Models;
using SpotiParty.Web.Services; using SpotiParty.Web.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddEnvironmentVariables();
// Add services to the container. // Add services to the container.
builder.Services.AddRazorComponents() builder.Services.AddRazorComponents()
.AddInteractiveServerComponents(); .AddInteractiveServerComponents();
builder.AddServiceDefaults(); builder.AddServiceDefaults();
builder.Services.AddSingleton<AuthorizationHandler>(); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ClientSideStorage>();
builder.AddNpgsqlDbContext<DatabaseContext>("SpotiParty");
builder.Services.AddDbContextFactory<DatabaseContext>(options => {
options.UseNpgsql(builder.Configuration.GetConnectionString("SpotiParty"));
});
builder.Services.AddScoped<AuthorizationHandler>();
builder.Services.AddScoped<IHopFrameAuthHandler, DashboardAuthHandler>();
builder.Services.AddScoped<DashboardAuthHandler>();
builder.Services.AddScoped<EventsDashboardRepo>();
builder.Services.AddHopFrame(config => {
config.SetLoginPage("/login");
config.AddDbContext<DatabaseContext>(context => {
context.Table<User>(table => {
table
.SetViewPolicy(DashboardAuthHandler.AdminPolicy)
.SetCreatePolicy(DashboardAuthHandler.AdminPolicy)
.SetUpdatePolicy(DashboardAuthHandler.AdminPolicy)
.SetDeletePolicy(DashboardAuthHandler.AdminPolicy);
table.Property(u => u.RefreshToken)
.List(false)
.DisplayValue(false)
.SetEditable(false);
});
context.Table<Event>()
.SetDisplayName(Guid.NewGuid().ToString())
.Ignore(true);
});
config.AddCustomRepository<EventsDashboardRepo, Event, Guid>(e => e.Id, table => {
table.SetDisplayName("Events");
table.Property(e => e.Id)
.List(false)
.SetEditable(false)
.SetCreatable(false);
table.Property(e => e.Host)
.List(false)
.SetEditable(false)
.SetCreatable(false)
.SetDisplayedProperty(u => u.DisplayName);
table.ShowSearchSuggestions(false);
});
config.AddPlugin<AdminDashboardPlugin>();
});
var app = builder.Build(); var app = builder.Build();
@@ -20,15 +81,21 @@ if (!app.Environment.IsDevelopment()) {
app.UseHsts(); app.UseHsts();
} }
await using (var scope = app.Services.CreateAsyncScope()) {
var context = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
await context.Database.MigrateAsync();
}
app.MapDefaultEndpoints(); app.MapDefaultEndpoints();
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); app.UseStatusCodePagesWithReExecute("/not-found");
app.UseHttpsRedirection(); //app.UseHttpsRedirection();
app.UseAntiforgery(); app.UseAntiforgery();
app.MapStaticAssets(); app.MapStaticAssets();
app.MapRazorComponents<App>() app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode(); .AddInteractiveServerRenderMode()
.AddHopFramePages();
app.Run(); app.Run();

View File

@@ -0,0 +1,27 @@
using HopFrame.Core.Config;
using HopFrame.Web.Plugins.Events;
using Microsoft.AspNetCore.Components;
using Microsoft.FluentUI.AspNetCore.Components;
using SpotiParty.Web.Models;
namespace SpotiParty.Web.Services;
public class AdminDashboardPlugin(NavigationManager navigator) {
[HopFrame.Web.Plugins.Annotations.EventHandler]
public void OnTableInitialized(TableInitializedEvent e) {
if (e.Table.TableType != typeof(Event)) return;
e.AddEntityButton(new IconInfo {
Variant = IconVariant.Regular,
Size = IconSize.Size16,
Name = "Open"
}, OnButtonClicked);
}
private void OnButtonClicked(object o, TableConfig config) {
var entity = (Event)o;
navigator.NavigateTo(navigator.BaseUri + $"enqueue/{entity.Id}");
}
}

View File

@@ -1,46 +1,76 @@
using System.Net.Http.Headers; using Microsoft.AspNetCore.Components;
using System.Security.Authentication; using Microsoft.EntityFrameworkCore;
using System.Text;
using System.Text.Json.Serialization;
using SpotifyAPI.Web; using SpotifyAPI.Web;
using SpotiParty.Web.Models;
namespace SpotiParty.Web.Services; namespace SpotiParty.Web.Services;
public sealed class AuthorizationHandler { public sealed class AuthorizationHandler(NavigationManager navigator, DatabaseContext context, ClientSideStorage storage, IConfiguration configuration) {
private AuthResponse? _token; private async Task<(string clientId, string clientSecret)> GetClientSecrets() {
#if DEBUG
var fileLines = await File.ReadAllLinesAsync(Path.Combine(Environment.CurrentDirectory, ".dev-token"));
return (fileLines[0], fileLines[1]);
#endif
private class AuthResponse { #pragma warning disable CS0162 // Unreachable code detected
[JsonPropertyName("access_token")] return (configuration["ClientId"]!, configuration["ClientSecret"]!);
public string AccessToken { get; set; } #pragma warning restore CS0162 // Unreachable code detected
[JsonPropertyName("token_type")]
public string TokenType { get; set; }
[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }
} }
public async Task<SpotifyClient> ConfigureClient() { public async Task<SpotifyClient?> ConfigureClient(Guid userId) {
if (_token is null) { var user = await context.Users.FindAsync(userId);
var fileLines = await File.ReadAllLinesAsync(Path.Combine(Environment.CurrentDirectory, ".dev-token")); if (user is null) return null;
var clientId = fileLines[0];
var clientSecret = fileLines[1];
var basicAuthToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); var (clientId, clientSecret) = await GetClientSecrets();
var httpClient = new HttpClient(); var request = new AuthorizationCodeRefreshRequest(clientId, clientSecret, user.RefreshToken);
httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {basicAuthToken}"); var response = await new OAuthClient().RequestToken(request);
var response = await httpClient.PostAsync("https://accounts.spotify.com/api/token", new FormUrlEncodedContent(new[] { return new SpotifyClient(response.AccessToken);
new KeyValuePair<string, string>("grant_type", "client_credentials") }
}));
response.EnsureSuccessStatusCode();
_token = await response.Content.ReadFromJsonAsync<AuthResponse>();
if (_token is null) throw new AuthenticationException("Spotify auth failed!"); public async Task<Uri> ConstructLoginUri() {
var (clientId, _) = await GetClientSecrets();
var request = new LoginRequest(
new Uri(navigator.BaseUri + "callback"),
clientId,
LoginRequest.ResponseType.Code) {
Scope = [Scopes.UserReadPlaybackState, Scopes.UserModifyPlaybackState, Scopes.UserReadPrivate, Scopes.UserReadEmail]
};
return request.ToUri();
}
public async Task HandleCallback(string code) {
var (clientId, clientSecret) = await GetClientSecrets();
var response = await new OAuthClient().RequestToken(
new AuthorizationCodeTokenRequest(
clientId,
clientSecret,
code,
new Uri(navigator.BaseUri + "callback")));
var client = new SpotifyClient(response.AccessToken);
var spotiUser = await client.UserProfile.Current();
var user = await context.Users.FirstOrDefaultAsync(u => u.SpotifyUserId == spotiUser.Id);
if (user is null) {
user = new User {
DisplayName = spotiUser.DisplayName,
RefreshToken = response.RefreshToken,
SpotifyUserId = spotiUser.Id,
IsAdmin = await context.Users.CountAsync() == 0
};
await context.Users.AddAsync(user);
await context.SaveChangesAsync();
}
else {
user.RefreshToken = response.RefreshToken;
await context.SaveChangesAsync();
} }
return new SpotifyClient(_token.AccessToken, _token.TokenType); storage.SaveUserToken(response.RefreshToken);
} }
} }

View File

@@ -0,0 +1,19 @@
namespace SpotiParty.Web.Services;
public class ClientSideStorage(IHttpContextAccessor accessor) {
private const string AuthCookieName = "RefreshToken";
public void SaveUserToken(string token) {
accessor.HttpContext?.Response.Cookies.Append(AuthCookieName, token);
}
public string? GetUserToken() {
return accessor.HttpContext?.Request.Cookies[AuthCookieName];
}
public void DeleteUserToken() {
accessor.HttpContext?.Response.Cookies.Delete(AuthCookieName);
}
}

View File

@@ -0,0 +1,44 @@
using HopFrame.Core.Services;
using Microsoft.EntityFrameworkCore;
using SpotiParty.Web.Models;
namespace SpotiParty.Web.Services;
public class DashboardAuthHandler(ClientSideStorage storage, IDbContextFactory<DatabaseContext> contextFactory) : IHopFrameAuthHandler {
public const string AdminPolicy = "ADMIN";
public async Task<bool> IsAuthenticatedAsync(string? policy) {
var user = await GetCurrentUser();
if (user is null)
return false;
if (policy == AdminPolicy) {
return user.IsAdmin;
}
return true;
}
public async Task<string> GetCurrentUserDisplayNameAsync() {
var token = storage.GetUserToken();
if (string.IsNullOrWhiteSpace(token))
return string.Empty;
await using var context = await contextFactory.CreateDbContextAsync();
var user = await context.Users.AsNoTracking().FirstOrDefaultAsync(u => u.RefreshToken == token);
if (user is null) return string.Empty;
return user.DisplayName;
}
public async Task<User?> GetCurrentUser() {
var token = storage.GetUserToken();
if (string.IsNullOrWhiteSpace(token))
return null;
await using var context = await contextFactory.CreateDbContextAsync();
return await context.Users.AsNoTracking().FirstOrDefaultAsync(u => u.RefreshToken == token);
}
}

View File

@@ -0,0 +1,53 @@
using HopFrame.Core.Repositories;
using Microsoft.EntityFrameworkCore;
using SpotiParty.Web.Models;
namespace SpotiParty.Web.Services;
public class EventsDashboardRepo(DatabaseContext context, DashboardAuthHandler handler) : IHopFrameRepository<Event, Guid> {
public async Task<IEnumerable<Event>> LoadPage(int page, int perPage) {
var user = await handler.GetCurrentUser();
if (user is null) return [];
return await context.Events
.AsNoTracking()
.Include(e => e.Host)
.Where(e => e.Host.UserId == user.UserId)
.Skip(page * perPage)
.Take(perPage)
.ToListAsync();
}
public async Task<SearchResult<Event>> Search(string searchTerm, int page, int perPage) {
var entries = await LoadPage(page, perPage);
return new(entries, await GetTotalPageCount(perPage));
}
public async Task<int> GetTotalPageCount(int perPage) {
double count = await context.Events.CountAsync();
return Convert.ToInt32(Math.Ceiling(count / perPage));
}
public async Task CreateItem(Event item) {
var creator = await handler.GetCurrentUser();
context.Attach(creator!);
item.Host = creator!;
await context.Events.AddAsync(item);
await context.SaveChangesAsync();
}
public async Task EditItem(Event item) {
context.Events.Update(item);
await context.SaveChangesAsync();
}
public async Task DeleteItem(Event item) {
context.Events.Remove(item);
await context.SaveChangesAsync();
}
public async Task<Event?> GetOne(Guid key) {
return await context.Events.FindAsync(key);
}
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException> <BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
@@ -19,6 +19,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.5.2" />
<PackageReference Include="HopFrame.Web" Version="3.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.12">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SpotifyAPI.Web" Version="7.2.1" /> <PackageReference Include="SpotifyAPI.Web" Version="7.2.1" />
</ItemGroup> </ItemGroup>
@@ -75,4 +82,8 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project> </Project>

View File

@@ -2,7 +2,9 @@
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning",
"HopFrame": "Debug",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
} }
}, },
"DetailedErrors": true "DetailedErrors": true

View File

@@ -5,5 +5,7 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"ClientId": null,
"ClientSecret": null
} }

View File

@@ -2,6 +2,7 @@
--color-primary: #1db954; --color-primary: #1db954;
--color-primary-dark: #17a74a; --color-primary-dark: #17a74a;
--color-accent: #333333; --color-accent: #333333;
--color-accent-dark: #555555;
--color-background: #121212; --color-background: #121212;
--color-background-light: #181818; --color-background-light: #181818;
--color-text: #ffffff; --color-text: #ffffff;
@@ -38,3 +39,20 @@ body {
background: var(--color-background); background: var(--color-background);
} }
} }
.button-secondary {
padding: 0.6rem 1rem;
border: none;
border-radius: 5px;
background: var(--color-accent);
color: var(--color-text);
cursor: pointer;
&:hover {
background: var(--color-accent-dark);
}
&:disabled {
background: var(--color-background);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=Spoti/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@@ -0,0 +1,10 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=C_003A_005CUsers_005Cleon_005CDocuments_005CProjekte_005CSpotiParty_005CHopFrame_002ECore_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=C_003A_005CUsers_005Cleon_005CDocuments_005CProjekte_005CSpotiParty_005CHopFrame_002EWeb_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AAspireEFPostgreSqlExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FSourcesCache_003F7b8c93872a6630cad8be31c0bbb3f21ffc274a4e8bf081b76fc09649b93393ee_003FAspireEFPostgreSqlExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AEntityFrameworkServiceCollectionExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FSourcesCache_003F93cfc51838b859ffb0d584bc342f1a2c3f0b2ad7f3197ea24cd81b4b845f0_003FEntityFrameworkServiceCollectionExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AFullTrack_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F8b91718e15e747bab2ecc54bf74dc11b39600_003Fd5_003F3f30c052_003FFullTrack_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHopFrameConfigurator_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F4682f2518e994f22b1a441cd50dcbd54f600_003F82_003Fb359f37f_003FHopFrameConfigurator_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AIToken_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F8b91718e15e747bab2ecc54bf74dc11b39600_003F9f_003F2fe8c76b_003FIToken_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AIUserToken_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F8b91718e15e747bab2ecc54bf74dc11b39600_003F00_003F10e67097_003FIUserToken_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AServiceCollectionExtensions_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Ff0aecc1b9e4e4164a6ba51415eba18fb1fa00_003F0f_003Fdac1d453_003FServiceCollectionExtensions_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary>