Implemented Login workflow

This commit is contained in:
2025-11-30 15:19:49 +01:00
parent 2b5b0c1067
commit 825bd80ef0
22 changed files with 330 additions and 56 deletions

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"?>
<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>

View File

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

View File

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

View File

@@ -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>

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("/enqueue", forceLoad: true);
}
}

View File

@@ -1,4 +1,4 @@
@page "/enqueue"
@page "/enqueue/{userid}"
@using SpotiParty.Web.Components.Components
@rendermode InteractiveServer

View File

@@ -4,7 +4,11 @@ using SpotiParty.Web.Services;
namespace SpotiParty.Web.Components.Pages;
public partial class EnqueuePage(AuthorizationHandler authHandler) : ComponentBase {
public partial class EnqueuePage(AuthorizationHandler authHandler, NavigationManager navigator) : ComponentBase {
[Parameter]
public string UserId { get; set; } = string.Empty;
private readonly int _currentYear = DateTime.Now.Year;
private SpotifyClient _client = null!;
@@ -17,7 +21,20 @@ public partial class EnqueuePage(AuthorizationHandler authHandler) : ComponentBa
protected override async Task OnInitializedAsync() {
await base.OnInitializedAsync();
_client = await authHandler.ConfigureClient();
if (!Guid.TryParse(UserId, out var guid)) {
navigator.NavigateTo("/", forceLoad: true);
return;
}
var client = await authHandler.ConfigureClient(guid);
if (client is null) {
navigator.NavigateTo("/", forceLoad: true);
return;
}
_client = client;
}
private async Task ExecuteSearch() {
@@ -51,9 +68,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;

View File

@@ -105,16 +105,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;
}

View File

@@ -0,0 +1,17 @@
@page "/login"
@using SpotiParty.Web.Services
<a class="button-primary" href="@_uri">Mit Spotify einloggen</a>
@inject AuthorizationHandler AuthHandler
@code {
private Uri _uri = null!;
protected override async Task OnInitializedAsync() {
await base.OnInitializedAsync();
_uri = await AuthHandler.ConstructLoginUri();
}
}

View File

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

View File

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

View File

@@ -0,0 +1,51 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SpotiParty.Web;
#nullable disable
namespace SpotiParty.Web.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20251130141048_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SpotiParty.Web.Models.User", b =>
{
b.Property<Guid>("UserId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<string>("RefreshToken")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.HasKey("UserId");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SpotiParty.Web.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
UserId = table.Column<Guid>(type: "uuid", nullable: false),
DisplayName = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),
RefreshToken = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.UserId);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -0,0 +1,48 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SpotiParty.Web;
#nullable disable
namespace SpotiParty.Web.Migrations
{
[DbContext(typeof(DatabaseContext))]
partial class DatabaseContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SpotiParty.Web.Models.User", b =>
{
b.Property<Guid>("UserId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.Property<string>("RefreshToken")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)");
b.HasKey("UserId");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}

View File

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

View File

@@ -1,3 +1,5 @@
using Microsoft.EntityFrameworkCore;
using SpotiParty.Web;
using SpotiParty.Web.Components;
using SpotiParty.Web.Services;
@@ -9,7 +11,8 @@ builder.Services.AddRazorComponents()
builder.AddServiceDefaults();
builder.Services.AddSingleton<AuthorizationHandler>();
builder.AddNpgsqlDbContext<DatabaseContext>("SpotiParty");
builder.Services.AddScoped<AuthorizationHandler>();
var app = builder.Build();
@@ -20,10 +23,15 @@ 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.UseHttpsRedirection();
app.UseAntiforgery();

View File

@@ -1,46 +1,57 @@
using System.Net.Http.Headers;
using System.Security.Authentication;
using System.Text;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Components;
using SpotifyAPI.Web;
using SpotiParty.Web.Models;
namespace SpotiParty.Web.Services;
public sealed class AuthorizationHandler {
public sealed class AuthorizationHandler(NavigationManager navigator, DatabaseContext context) {
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() {
var fileLines = await File.ReadAllLinesAsync(Path.Combine(Environment.CurrentDirectory, ".dev-token"));
return (fileLines[0], fileLines[1]);
}
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 basicAuthToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {basicAuthToken}");
var (clientId, clientSecret) = await GetClientSecrets();
var request = new AuthorizationCodeRefreshRequest(clientId, clientSecret, user.RefreshToken);
var response = await new OAuthClient().RequestToken(request);
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 new SpotifyClient(response.AccessToken);
}
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 new SpotifyClient(_token.AccessToken, _token.TokenType);
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 = new User {
DisplayName = spotiUser.DisplayName,
RefreshToken = response.RefreshToken
};
await context.Users.AddAsync(user);
await context.SaveChangesAsync();
}
}

View File

@@ -19,6 +19,12 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="13.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SpotifyAPI.Web" Version="7.2.1" />
</ItemGroup>

View File

@@ -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);
}
}

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,4 @@
<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: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_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></wpf:ResourceDictionary>