diff options
-rw-r--r-- | .gitignore | 488 | ||||
-rw-r--r-- | LICENSE | 21 | ||||
-rw-r--r-- | VPNAuth.Server/Config.cs | 49 | ||||
-rw-r--r-- | VPNAuth.Server/Database/AccessToken.cs | 10 | ||||
-rw-r--r-- | VPNAuth.Server/Database/AuthRequest.cs | 14 | ||||
-rw-r--r-- | VPNAuth.Server/Database/Database.cs | 14 | ||||
-rw-r--r-- | VPNAuth.Server/HttpContextUtils.cs | 15 | ||||
-rw-r--r-- | VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs | 91 | ||||
-rw-r--r-- | VPNAuth.Server/Migrations/20250418102156_DbInit.cs | 61 | ||||
-rw-r--r-- | VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs | 88 | ||||
-rw-r--r-- | VPNAuth.Server/Pages/Auth.cshtml | 31 | ||||
-rw-r--r-- | VPNAuth.Server/Pages/Auth.cshtml.cs | 52 | ||||
-rw-r--r-- | VPNAuth.Server/Pages/Dashboard.cshtml | 41 | ||||
-rw-r--r-- | VPNAuth.Server/PkceUtils.cs | 17 | ||||
-rw-r--r-- | VPNAuth.Server/Program.cs | 98 | ||||
-rw-r--r-- | VPNAuth.Server/Responses/Token.cs | 11 | ||||
-rw-r--r-- | VPNAuth.Server/Responses/UserInfo.cs | 28 | ||||
-rw-r--r-- | VPNAuth.Server/VPNAuth.Server.csproj | 87 | ||||
-rw-r--r-- | VPNAuth.sln | 16 |
19 files changed, 1232 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7cd6c3e --- /dev/null +++ b/.gitignore @@ -0,0 +1,488 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# 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/ +[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 +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# 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 +*.tlog +*.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 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# 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/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# 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 + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp + +# Project Specific +VPNAuth.Server/vpnauth.db +VPNAuth.Server/config.json @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Tim R. <contact@bytim.eu> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/VPNAuth.Server/Config.cs b/VPNAuth.Server/Config.cs new file mode 100644 index 0000000..84b01ef --- /dev/null +++ b/VPNAuth.Server/Config.cs @@ -0,0 +1,49 @@ +using System.Text.Json; + +namespace VPNAuth.Server; + +public class ConfigUser +{ + public string? Username { get; set; } + public List<string>? Ips { get; set; } + + public string? Sub { get; set; } + public string? Name { get; set; } + public string? GivenName { get; set; } + public string? FamilyName { get; set; } + public string? PreferredUsername { get; set; } + public string? Email { get; set; } + public string? Picture { get; set; } +} + +public class ConfigApp +{ + public string? ClientId { get; set; } + public string? RedirectUri { get; set; } + public string? Secret { get; set; } +} + +public class Config +{ + public List<ConfigUser>? Users { get; set; } + public List<ConfigApp>? Apps { get; set; } + + public ConfigApp? FindApp(string clientId) + => Apps?.Find(app => app.ClientId == clientId); + + private static string _filePath = "./config.json"; + + public static void CreateIfNotExists() + { + if (File.Exists(_filePath)) return; + + File.Create(_filePath); + File.WriteAllText(_filePath, JsonSerializer.Serialize(new Config + { + Users = [] + })); + } + + public static Config Read() + => JsonSerializer.Deserialize<Config>(File.ReadAllText(_filePath))!; +} diff --git a/VPNAuth.Server/Database/AccessToken.cs b/VPNAuth.Server/Database/AccessToken.cs new file mode 100644 index 0000000..3cdc3ba --- /dev/null +++ b/VPNAuth.Server/Database/AccessToken.cs @@ -0,0 +1,10 @@ +namespace VPNAuth.Server.Database; + +public class AccessToken +{ + public int Id { get; set; } + public string Token { get; set; } + public string ClientId { get; set; } + public DateTime CreationTime { get; set; } + public List<string> Scopes { get; set; } +} diff --git a/VPNAuth.Server/Database/AuthRequest.cs b/VPNAuth.Server/Database/AuthRequest.cs new file mode 100644 index 0000000..98fe001 --- /dev/null +++ b/VPNAuth.Server/Database/AuthRequest.cs @@ -0,0 +1,14 @@ +namespace VPNAuth.Server.Database; + +public class AuthRequest +{ + public int Id { get; set; } + public DateTime InitTime { get; set; } + public string Code { get; set; } + public string? State { get; set; } + public string ClientId { get; set; } + public List<string> Scopes { get; set; } + public string CodeChallenge { get; set; } + public string CodeChallengeMethod { get; set; } + public bool Accepted { get; set; } +} diff --git a/VPNAuth.Server/Database/Database.cs b/VPNAuth.Server/Database/Database.cs new file mode 100644 index 0000000..a8cf8eb --- /dev/null +++ b/VPNAuth.Server/Database/Database.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; + +namespace VPNAuth.Server.Database; + +public class Database : DbContext +{ + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseSqlite("Data Source=vpnauth.db"); + } + + public DbSet<AuthRequest> AuthRequests { get; set; } + public DbSet<AccessToken> AccessTokens { get; set; } +} diff --git a/VPNAuth.Server/HttpContextUtils.cs b/VPNAuth.Server/HttpContextUtils.cs new file mode 100644 index 0000000..5bba471 --- /dev/null +++ b/VPNAuth.Server/HttpContextUtils.cs @@ -0,0 +1,15 @@ +namespace VPNAuth.Server; + +public static class HttpContextUtils +{ + public static string GetRemoteIpAddress(this HttpContext context) + => context.Request.Headers["X-Forwarded-For"].DefaultIfEmpty(context.Connection.RemoteIpAddress!.ToString()) + .First()!; + + public static ConfigUser? GetUser(this HttpContext context) + { + var config = Config.Read(); + if (config.Users == null || config.Users.Count == 0) return null; + return config.Users!.Find(user => user.Ips!.Contains(context.GetRemoteIpAddress())); + } +} diff --git a/VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs b/VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs new file mode 100644 index 0000000..57eda44 --- /dev/null +++ b/VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs @@ -0,0 +1,91 @@ +// <auto-generated /> +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using VPNAuth.Server.Database; + +#nullable disable + +namespace VPNAuth.Server.Migrations +{ + [DbContext(typeof(Database.Database))] + [Migration("20250418102156_DbInit")] + partial class DbInit + { + /// <inheritdoc /> + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.4"); + + modelBuilder.Entity("VPNAuth.Server.Database.AccessToken", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<DateTime>("CreationTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection<string>("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("Token") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AccessTokens"); + }); + + modelBuilder.Entity("VPNAuth.Server.Database.AuthRequest", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<bool>("Accepted") + .HasColumnType("INTEGER"); + + b.Property<string>("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("Code") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("CodeChallenge") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("CodeChallengeMethod") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<DateTime>("InitTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection<string>("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("State") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AuthRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/VPNAuth.Server/Migrations/20250418102156_DbInit.cs b/VPNAuth.Server/Migrations/20250418102156_DbInit.cs new file mode 100644 index 0000000..70967ca --- /dev/null +++ b/VPNAuth.Server/Migrations/20250418102156_DbInit.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace VPNAuth.Server.Migrations +{ + /// <inheritdoc /> + public partial class DbInit : Migration + { + /// <inheritdoc /> + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AccessTokens", + columns: table => new + { + Id = table.Column<int>(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Token = table.Column<string>(type: "TEXT", nullable: false), + ClientId = table.Column<string>(type: "TEXT", nullable: false), + CreationTime = table.Column<DateTime>(type: "TEXT", nullable: false), + Scopes = table.Column<string>(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AccessTokens", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AuthRequests", + columns: table => new + { + Id = table.Column<int>(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + InitTime = table.Column<DateTime>(type: "TEXT", nullable: false), + Code = table.Column<string>(type: "TEXT", nullable: false), + State = table.Column<string>(type: "TEXT", nullable: true), + ClientId = table.Column<string>(type: "TEXT", nullable: false), + Scopes = table.Column<string>(type: "TEXT", nullable: false), + CodeChallenge = table.Column<string>(type: "TEXT", nullable: false), + CodeChallengeMethod = table.Column<string>(type: "TEXT", nullable: false), + Accepted = table.Column<bool>(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AuthRequests", x => x.Id); + }); + } + + /// <inheritdoc /> + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AccessTokens"); + + migrationBuilder.DropTable( + name: "AuthRequests"); + } + } +} diff --git a/VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs b/VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs new file mode 100644 index 0000000..d735267 --- /dev/null +++ b/VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs @@ -0,0 +1,88 @@ +// <auto-generated /> +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using VPNAuth.Server.Database; + +#nullable disable + +namespace VPNAuth.Server.Migrations +{ + [DbContext(typeof(Database.Database))] + partial class DatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.4"); + + modelBuilder.Entity("VPNAuth.Server.Database.AccessToken", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<DateTime>("CreationTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection<string>("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("Token") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AccessTokens"); + }); + + modelBuilder.Entity("VPNAuth.Server.Database.AuthRequest", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<bool>("Accepted") + .HasColumnType("INTEGER"); + + b.Property<string>("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("Code") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("CodeChallenge") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("CodeChallengeMethod") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<DateTime>("InitTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection<string>("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("State") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AuthRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/VPNAuth.Server/Pages/Auth.cshtml b/VPNAuth.Server/Pages/Auth.cshtml new file mode 100644 index 0000000..5ac8efe --- /dev/null +++ b/VPNAuth.Server/Pages/Auth.cshtml @@ -0,0 +1,31 @@ +@page "/auth" +@model VPNAuth.Server.Pages.Auth + +@{ + Layout = null; +} + +<!DOCTYPE html> + +<html> +<head> + <title>VPNAuth - Auth</title> +</head> +<body style="text-align: center;"> + <h1>Authorization</h1> + <h2>VPNAuth</h2> + @if (Model.ValidRequest) + { + <div> + <p>Do you want to log into <i>@Request.Query["client_id"]</i>?</p> + <button onclick="window.location = '/accept-auth/@Model.RequestEntry?.Entity.Id'">Yes</button> + <br/> + <p>You are logged in as <i>@Model.User?.Username</i>.</p> + </div> + } + else + { + <b>Invalid request.</b> + } +</body> +</html> diff --git a/VPNAuth.Server/Pages/Auth.cshtml.cs b/VPNAuth.Server/Pages/Auth.cshtml.cs new file mode 100644 index 0000000..bdcbc59 --- /dev/null +++ b/VPNAuth.Server/Pages/Auth.cshtml.cs @@ -0,0 +1,52 @@ +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using VPNAuth.Server.Database; + +namespace VPNAuth.Server.Pages; + +public class Auth : PageModel +{ + public Config Config; + public ConfigUser? User; + public bool ValidRequest; + public EntityEntry<AuthRequest>? RequestEntry; + + public readonly List<string> RequiredQueryParams = + [ + "response_type", + "client_id", + "scope", + "code_challenge_method", + "code_challenge" + ]; + + public void OnGet() + { + Config = Config.Read(); + User = HttpContext.GetUser(); + + ValidRequest = RequiredQueryParams.All(key => Request.Query.ContainsKey(key)) + && Config.FindApp(Request.Query["client_id"]!) != null + && Request.Query["code_challenge_method"] == "S256" + && User != null; + + RequestEntry = null; + + if (ValidRequest) + { + using var db = new Database.Database(); + RequestEntry = db.Add(new AuthRequest + { + InitTime = DateTime.Now, + ClientId = Request.Query["client_id"]!, + Code = PkceUtils.GenerateCode(), + State = Request.Query["state"], + Scopes = Request.Query["scope"].ToString().Split(" ").ToList(), + CodeChallenge = Request.Query["code_challenge"]!, + CodeChallengeMethod = Request.Query["code_challenge_method"]!, + Accepted = false + }); + db.SaveChanges(); + } + } +} diff --git a/VPNAuth.Server/Pages/Dashboard.cshtml b/VPNAuth.Server/Pages/Dashboard.cshtml new file mode 100644 index 0000000..cb00d9f --- /dev/null +++ b/VPNAuth.Server/Pages/Dashboard.cshtml @@ -0,0 +1,41 @@ +@page "/" +@using Microsoft.EntityFrameworkCore.ChangeTracking +@using VPNAuth.Server +@using VPNAuth.Server.Database + +@{ + Layout = null; + + string remoteIp = Request.HttpContext.GetRemoteIpAddress(); + ConfigUser? user = Request.HttpContext.GetUser(); +} + +<!DOCTYPE html> + +<html> +<head> + <title>VPNAuth - Dashboard</title> +</head> +<body style="text-align: center;"> + @if (user == null) + { + <p>No user detected</p> + } + else + { + <div> + <h1>Dashboard</h1> + <h2>VPNAuth</h2> + <p>Hey, @user.Username!</p> + <i>User settings coming soon...</i> + <h3>Your IPs</h3> + <ul style="list-style-position: inside;"> + @foreach (var ip in user.Ips!) + { + <li>@ip</li> + } + </ul> + </div> + } +</body> +</html> diff --git a/VPNAuth.Server/PkceUtils.cs b/VPNAuth.Server/PkceUtils.cs new file mode 100644 index 0000000..a11926e --- /dev/null +++ b/VPNAuth.Server/PkceUtils.cs @@ -0,0 +1,17 @@ +namespace VPNAuth.Server; + +public static class PkceUtils +{ + private static string _codeChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; + + public static string GenerateCode(int length = 10) + { + string code = ""; + for (int i = 0; i < length; i++) + code += _codeChars[new Random().Next(_codeChars.Length)]; // TODO: Is that function random enough? + return code; + } + + public static string GenerateToken(int length = 20) + => GenerateCode(length); // TODO: maybe add more possible chars then for GenerateCode +} diff --git a/VPNAuth.Server/Program.cs b/VPNAuth.Server/Program.cs new file mode 100644 index 0000000..6ea0b40 --- /dev/null +++ b/VPNAuth.Server/Program.cs @@ -0,0 +1,98 @@ +using VPNAuth.Server; +using VPNAuth.Server.Database; +using VPNAuth.Server.Responses; + +Config.CreateIfNotExists(); + +var builder = WebApplica |