Resolve "User management" #5
41
.gitlab-ci.yml
Normal file
41
.gitlab-ci.yml
Normal 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
|
||||
7
.idea/.idea.SpotiParty/.idea/dictionaries/project.xml
generated
Normal file
7
.idea/.idea.SpotiParty/.idea/dictionaries/project.xml
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
<component name="ProjectDictionaryState">
|
||||
<dictionary name="project">
|
||||
<words>
|
||||
<w>Spoti</w>
|
||||
</words>
|
||||
</dictionary>
|
||||
</component>
|
||||
4
.idea/.idea.SpotiParty/.idea/encodings.xml
generated
4
.idea/.idea.SpotiParty/.idea/encodings.xml
generated
@@ -1,4 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
3
SpotiParty.AppHost/.aspire/settings.json
Normal file
3
SpotiParty.AppHost/.aspire/settings.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"appHostPath": "../SpotiParty.AppHost.csproj"
|
||||
}
|
||||
@@ -2,6 +2,13 @@ using Projects;
|
||||
|
||||
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();
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<UserSecretsId>fe08e5bf-d119-470a-a4cc-7686f019ce64</UserSecretsId>
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Hosting.AppHost" Version="13.0.1" />
|
||||
<PackageReference Include="Aspire.Hosting.PostgreSQL" Version="13.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsAspireSharedProject>true</IsAspireSharedProject>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<link rel="stylesheet" href="@Assets["app.css"]"/>
|
||||
<link rel="stylesheet" href="@Assets["SpotiParty.Web.styles.css"]"/>
|
||||
<ImportMap/>
|
||||
<link rel="icon" type="image/png" href="favicon.png"/>
|
||||
<link rel="icon" href="favicon.ico"/>
|
||||
<HeadOutlet/>
|
||||
</head>
|
||||
|
||||
|
||||
27
SpotiParty.Web/Components/Pages/CallbackPage.razor
Normal file
27
SpotiParty.Web/Components/Pages/CallbackPage.razor
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
@page "/enqueue"
|
||||
@page "/enqueue/{eventId}"
|
||||
@using SpotiParty.Web.Components.Components
|
||||
@rendermode InteractiveServer
|
||||
|
||||
<PageTitle>SpotiParty</PageTitle>
|
||||
|
||||
<header>
|
||||
<h1>🎵 SpotiParty</h1>
|
||||
<h1>@(_event?.Name ?? " ")</h1>
|
||||
<p>Suche ein Lied und füge es zur Warteschlange hinzu</p>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<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>
|
||||
</form>
|
||||
|
||||
@@ -27,7 +29,7 @@
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<p>SpotiParty © @_currentYear</p>
|
||||
<p><a href="https://git.leon-hoppe.de/leon.hoppe/spotiparty" target="_blank">SpotiParty</a> © @_currentYear</p>
|
||||
</footer>
|
||||
|
||||
<dialog class="confirm-dialog" style="display: @(_selectedTrack is null ? "none" : "block")">
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SpotifyAPI.Web;
|
||||
using SpotiParty.Web.Models;
|
||||
using SpotiParty.Web.Services;
|
||||
|
||||
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 SpotifyClient _client = null!;
|
||||
|
||||
@@ -17,7 +25,37 @@ public partial class EnqueuePage(AuthorizationHandler authHandler) : ComponentBa
|
||||
|
||||
protected override async Task 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() {
|
||||
@@ -51,9 +89,8 @@ public partial class EnqueuePage(AuthorizationHandler authHandler) : ComponentBa
|
||||
private async Task DialogAccept() {
|
||||
if (_selectedTrack is null || _isAdding) return;
|
||||
_isAdding = true;
|
||||
/*var request = new PlayerAddToQueueRequest(_selectedTrack.Uri);
|
||||
await _client.Player.AddToQueue(request);*/
|
||||
await Task.Delay(3000); //TODO: Simulate adding
|
||||
var request = new PlayerAddToQueueRequest(_selectedTrack.Uri);
|
||||
await _client.Player.AddToQueue(request);
|
||||
_isAdding = false;
|
||||
|
||||
_success = true;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
header h1 {
|
||||
margin: 0;
|
||||
font-size: 2rem;
|
||||
height: 2rem;
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
@@ -63,6 +64,10 @@ footer {
|
||||
text-align: center;
|
||||
padding: 0.5rem;
|
||||
background: var(--color-primary);
|
||||
|
||||
a {
|
||||
color: var(--color-text);
|
||||
}
|
||||
}
|
||||
|
||||
.confirm-dialog {
|
||||
@@ -105,16 +110,3 @@ footer {
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
6
SpotiParty.Web/Components/Pages/HomePage.razor
Normal file
6
SpotiParty.Web/Components/Pages/HomePage.razor
Normal file
@@ -0,0 +1,6 @@
|
||||
@page "/"
|
||||
<h3>HomePage</h3>
|
||||
|
||||
@code {
|
||||
|
||||
}
|
||||
1
SpotiParty.Web/Components/Pages/HomePage.razor.css
Normal file
1
SpotiParty.Web/Components/Pages/HomePage.razor.css
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
15
SpotiParty.Web/Components/Pages/LoginPage.razor
Normal file
15
SpotiParty.Web/Components/Pages/LoginPage.razor
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
protected override void OnInitialized() {
|
||||
base.OnInitialized();
|
||||
Navigator.NavigateTo("/enqueue", forceLoad: true);
|
||||
Navigator.NavigateTo("/", forceLoad: true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
|
||||
<Router AppAssembly="typeof(Program).Assembly">
|
||||
<Found Context="routeData">
|
||||
<RouteView RouteData="routeData"/>
|
||||
<FocusOnNavigate RouteData="routeData" Selector="h1"/>
|
||||
|
||||
12
SpotiParty.Web/DatabaseContext.cs
Normal file
12
SpotiParty.Web/DatabaseContext.cs
Normal 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; }
|
||||
|
||||
}
|
||||
@@ -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
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
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
|
||||
WORKDIR /src
|
||||
COPY ["SpotiParty.Web/SpotiParty.Web.csproj", "SpotiParty.Web/"]
|
||||
|
||||
19
SpotiParty.Web/Models/Event.cs
Normal file
19
SpotiParty.Web/Models/Event.cs
Normal 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);
|
||||
}
|
||||
19
SpotiParty.Web/Models/User.cs
Normal file
19
SpotiParty.Web/Models/User.cs
Normal 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; }
|
||||
}
|
||||
@@ -1,15 +1,76 @@
|
||||
using HopFrame.Core.Services;
|
||||
using HopFrame.Web;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SpotiParty.Web;
|
||||
using SpotiParty.Web.Components;
|
||||
using SpotiParty.Web.Models;
|
||||
using SpotiParty.Web.Services;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Configuration.AddEnvironmentVariables();
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
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();
|
||||
|
||||
@@ -20,15 +81,21 @@ if (!app.Environment.IsDevelopment()) {
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
await using (var scope = app.Services.CreateAsyncScope()) {
|
||||
var context = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
|
||||
await context.Database.MigrateAsync();
|
||||
}
|
||||
|
||||
app.MapDefaultEndpoints();
|
||||
|
||||
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
|
||||
app.UseHttpsRedirection();
|
||||
app.UseStatusCodePagesWithReExecute("/not-found");
|
||||
//app.UseHttpsRedirection();
|
||||
|
||||
app.UseAntiforgery();
|
||||
|
||||
app.MapStaticAssets();
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
.AddInteractiveServerRenderMode()
|
||||
.AddHopFramePages();
|
||||
|
||||
app.Run();
|
||||
27
SpotiParty.Web/Services/AdminDashboardPlugin.cs
Normal file
27
SpotiParty.Web/Services/AdminDashboardPlugin.cs
Normal 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}");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,46 +1,76 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Authentication;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SpotifyAPI.Web;
|
||||
using SpotiParty.Web.Models;
|
||||
|
||||
namespace SpotiParty.Web.Services;
|
||||
|
||||
public sealed class AuthorizationHandler {
|
||||
public sealed class AuthorizationHandler(NavigationManager navigator, DatabaseContext context, ClientSideStorage storage, IConfiguration configuration) {
|
||||
|
||||
private AuthResponse? _token;
|
||||
|
||||
private class AuthResponse {
|
||||
[JsonPropertyName("access_token")]
|
||||
public string AccessToken { get; set; }
|
||||
|
||||
[JsonPropertyName("token_type")]
|
||||
public string TokenType { get; set; }
|
||||
|
||||
[JsonPropertyName("expires_in")]
|
||||
public int ExpiresIn { get; set; }
|
||||
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
|
||||
|
||||
#pragma warning disable CS0162 // Unreachable code detected
|
||||
return (configuration["ClientId"]!, configuration["ClientSecret"]!);
|
||||
#pragma warning restore CS0162 // Unreachable code detected
|
||||
}
|
||||
|
||||
public async Task<SpotifyClient> ConfigureClient() {
|
||||
if (_token is null) {
|
||||
var fileLines = await File.ReadAllLinesAsync(Path.Combine(Environment.CurrentDirectory, ".dev-token"));
|
||||
var clientId = fileLines[0];
|
||||
var clientSecret = fileLines[1];
|
||||
public async Task<SpotifyClient?> ConfigureClient(Guid userId) {
|
||||
var user = await context.Users.FindAsync(userId);
|
||||
if (user is null) return null;
|
||||
|
||||
var (clientId, clientSecret) = await GetClientSecrets();
|
||||
var request = new AuthorizationCodeRefreshRequest(clientId, clientSecret, user.RefreshToken);
|
||||
var response = await new OAuthClient().RequestToken(request);
|
||||
|
||||
return new SpotifyClient(response.AccessToken);
|
||||
}
|
||||
|
||||
var basicAuthToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
|
||||
var httpClient = new HttpClient();
|
||||
httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {basicAuthToken}");
|
||||
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]
|
||||
};
|
||||
|
||||
var response = await httpClient.PostAsync("https://accounts.spotify.com/api/token", new FormUrlEncodedContent(new[] {
|
||||
new KeyValuePair<string, string>("grant_type", "client_credentials")
|
||||
}));
|
||||
response.EnsureSuccessStatusCode();
|
||||
_token = await response.Content.ReadFromJsonAsync<AuthResponse>();
|
||||
return request.ToUri();
|
||||
}
|
||||
|
||||
if (_token is null) throw new AuthenticationException("Spotify auth failed!");
|
||||
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();
|
||||
}
|
||||
|
||||
return new SpotifyClient(_token.AccessToken, _token.TokenType);
|
||||
else {
|
||||
user.RefreshToken = response.RefreshToken;
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
storage.SaveUserToken(response.RefreshToken);
|
||||
}
|
||||
|
||||
}
|
||||
19
SpotiParty.Web/Services/ClientSideStorage.cs
Normal file
19
SpotiParty.Web/Services/ClientSideStorage.cs
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
44
SpotiParty.Web/Services/DashboardAuthHandler.cs
Normal file
44
SpotiParty.Web/Services/DashboardAuthHandler.cs
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
53
SpotiParty.Web/Services/EventsDashboardRepo.cs
Normal file
53
SpotiParty.Web/Services/EventsDashboardRepo.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
|
||||
@@ -19,6 +19,13 @@
|
||||
</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" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -75,4 +82,8 @@
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Migrations\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"HopFrame": "Debug",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
}
|
||||
},
|
||||
"DetailedErrors": true
|
||||
|
||||
@@ -5,5 +5,7 @@
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
"ClientId": null,
|
||||
"ClientSecret": null
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
--color-primary: #1db954;
|
||||
--color-primary-dark: #17a74a;
|
||||
--color-accent: #333333;
|
||||
--color-accent-dark: #555555;
|
||||
--color-background: #121212;
|
||||
--color-background-light: #181818;
|
||||
--color-text: #ffffff;
|
||||
@@ -38,3 +39,20 @@ body {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
BIN
SpotiParty.Web/wwwroot/favicon.ico
Normal file
BIN
SpotiParty.Web/wwwroot/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.1 KiB |
2
SpotiParty.sln.DotSettings
Normal file
2
SpotiParty.sln.DotSettings
Normal 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>
|
||||
10
SpotiParty.sln.DotSettings.user
Normal file
10
SpotiParty.sln.DotSettings.user
Normal 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>
|
||||
Reference in New Issue
Block a user