Add project files.
1d1a1c1c933a248f245136c91a1bf0351af158a0
0 files changed
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..1ff0c42
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4d45c2f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,365 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+Emails/
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Oo]ut/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
\ No newline at end of file
diff --git a/Extensions/DefaultExtensions.cs b/Extensions/DefaultExtensions.cs
new file mode 100644
index 0000000..5f8dac1
--- /dev/null
+++ b/Extensions/DefaultExtensions.cs
@@ -0,0 +1,50 @@
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Mvc.Razor;
+
+namespace LoginDing.Extensions;
+
+public static class DefaultExtensions
+{
+ // Adds SMTP server services to the specified IServiceCollection
+ public static IServiceCollection AddRazorUnderRoot(this IServiceCollection services)
+ {
+ services.AddRazorPages(o => o.RootDirectory = "/wwwroot");
+
+ services.Configure<RazorViewEngineOptions>(options =>
+ {
+ options.ViewLocationFormats.Clear();
+ options.ViewLocationFormats.Add("/wwwroot/{0}.cshtml");
+ options.ViewLocationFormats.Add("/wwwroot/MasterPages/{0}.cshtml");
+
+ options.PageViewLocationFormats.Clear();
+ options.PageViewLocationFormats.Add("/wwwroot/{0}.cshtml");
+ options.PageViewLocationFormats.Add("/wwwroot/MasterPages/{0}.cshtml");
+ });
+
+ return services;
+ }
+
+ public static IServiceCollection AddAuthenticationAndAddAuthorization(this IServiceCollection services)
+ {
+ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
+ .AddCookie(options =>
+ {
+ options.LoginPath = "/Account/Login";
+ options.AccessDeniedPath = "/Account/AccessDenied";
+ options.Cookie.HttpOnly = true;
+ options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
+ options.Cookie.SameSite = SameSiteMode.Strict;
+ });
+
+ services.AddAuthorization();
+
+ return services;
+ }
+
+ public static IApplicationBuilder UseAuthenticationAndAddAuthorization(this IApplicationBuilder app)
+ {
+ app.UseAuthentication();
+ app.UseAuthorization();
+ return app;
+ }
+}
\ No newline at end of file
diff --git a/LoginDing.csproj b/LoginDing.csproj
new file mode 100644
index 0000000..8e264c8
--- /dev/null
+++ b/LoginDing.csproj
@@ -0,0 +1,36 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+ <PropertyGroup>
+ <TargetFramework>net8.0</TargetFramework>
+ <Nullable>enable</Nullable>
+ <ImplicitUsings>enable</ImplicitUsings>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Compile Remove="Emails\**" />
+ <Content Remove="Emails\**" />
+ <EmbeddedResource Remove="Emails\**" />
+ <None Remove="Emails\**" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Content Remove="wwwroot\Account\Login.cshtml.cs" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Compile Include="wwwroot\Account\Login.cshtml.cs" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="9.0.9" />
+ <PackageReference Include="Microsoft.Extensions.Identity.Core" Version="9.0.9" />
+ <PackageReference Include="Mvc.ModelBinding.MultiParameter" Version="8.2.3" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <None Update="certificate.pfx">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ </ItemGroup>
+
+</Project>
diff --git a/LoginDing.sln b/LoginDing.sln
new file mode 100644
index 0000000..6144519
--- /dev/null
+++ b/LoginDing.sln
@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.14.36705.20 d17.14
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoginDing", "LoginDing.csproj", "{E1B23DA4-830E-3ED6-A3C1-837F4D0EAA84}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {E1B23DA4-830E-3ED6-A3C1-837F4D0EAA84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E1B23DA4-830E-3ED6-A3C1-837F4D0EAA84}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E1B23DA4-830E-3ED6-A3C1-837F4D0EAA84}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E1B23DA4-830E-3ED6-A3C1-837F4D0EAA84}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {C209C04D-C7FF-446C-BAC0-582F17EA5463}
+ EndGlobalSection
+EndGlobal
diff --git a/Program.cs b/Program.cs
new file mode 100644
index 0000000..9877732
--- /dev/null
+++ b/Program.cs
@@ -0,0 +1,32 @@
+using LoginDing.Extensions;
+
+var builder = WebApplication.CreateBuilder(new WebApplicationOptions
+{
+ ContentRootPath = AppContext.BaseDirectory
+});
+
+builder.Services.AddMvcCore().WithMultiParameterModelBinding();
+
+builder.Services.AddRazorUnderRoot();
+
+builder.Services.AddControllersWithViews();
+
+builder.Services.AddAuthenticationAndAddAuthorization();
+
+//builder.Host.UseWindowsService();
+
+builder.Services.AddLogging(logging => logging.AddConsole());
+
+var app = builder.Build();
+
+app.UseDefaultFiles();
+
+app.UseStaticFiles();
+
+app.UseAuthenticationAndAddAuthorization();
+
+app.MapDefaultControllerRoute();
+
+app.MapRazorPages();
+
+await app.RunAsync();
diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json
new file mode 100644
index 0000000..680a30a
--- /dev/null
+++ b/Properties/launchSettings.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:13273",
+ "sslPort": 44320
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5045",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7202;http://localhost:5045",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/appsettings.json b/appsettings.json
new file mode 100644
index 0000000..d75325b
--- /dev/null
+++ b/appsettings.json
@@ -0,0 +1,24 @@
+{
+ "MaintenanceUsers": [
+ {
+ "UserName": "test",
+ "Password": "test",
+ "Role": "User",
+ "ExpireDays": 365
+ },
+ {
+ "UserName": "admin",
+ "Password": "admin",
+ "Role": "Administrator",
+ "ExpireDays": 365
+ }
+ ],
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "MailSharp.Smtp": "Debug",
+ "Microsoft.AspNetCore": "None",
+ "Microsoft.Hosting": "None"
+ }
+ }
+}
diff --git a/wwwroot/Account/AccessDenied.cshtml b/wwwroot/Account/AccessDenied.cshtml
new file mode 100644
index 0000000..424151e
--- /dev/null
+++ b/wwwroot/Account/AccessDenied.cshtml
@@ -0,0 +1,74 @@
+@model dynamic
+@{
+ ViewData["Title"] = "Access Denied";
+}
+
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>@ViewData["Title"]</title>
+ <style>
+ body
+ {
+ font-family: Arial, sans-serif;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+ margin: 0;
+ background-color: #f0f0f0;
+ }
+
+ .container
+ {
+ background-color: white;
+ padding: 20px;
+ border-radius: 8px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+ text-align: center;
+ width: 100%;
+ max-width: 400px;
+ }
+
+ h1
+ {
+ font-size: 24px;
+ color: #dc3545;
+ }
+
+ a
+ {
+ color: #007bff;
+ text-decoration: none;
+ }
+
+ a:hover
+ {
+ text-decoration: underline;
+ }
+
+ @@media screen and (max-width: 600px)
+ {
+ .container
+ {
+ margin: 10px;
+ padding: 15px;
+ }
+
+ h1
+ {
+ font-size: 20px;
+ }
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>Access Denied</h1>
+ <p>You do not have permission to access this resource.</p>
+ <a href="/">Return to Homepage</a>
+ </div>
+</body>
+</html>
diff --git a/wwwroot/Account/Login.cshtml b/wwwroot/Account/Login.cshtml
new file mode 100644
index 0000000..2f2fe2b
--- /dev/null
+++ b/wwwroot/Account/Login.cshtml
@@ -0,0 +1,122 @@
+@{
+ ViewData["Title"] = "Login";
+}
+
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>@ViewData["Title"]</title>
+ <style>
+ body
+ {
+ font-family: Arial, sans-serif;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+ margin: 0;
+ background-color: #f0f0f0;
+ }
+
+ .login-container
+ {
+ background-color: white;
+ padding: 20px;
+ border-radius: 8px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+ width: 100%;
+ max-width: 400px;
+ }
+
+ h1
+ {
+ font-size: 24px;
+ text-align: center;
+ }
+
+ .form-group
+ {
+ margin-bottom: 15px;
+ }
+
+ label
+ {
+ display: block;
+ margin-bottom: 5px;
+ }
+
+ input
+ {
+ width: 100%;
+ padding: 8px;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+ box-sizing: border-box;
+ }
+
+ button
+ {
+ width: 100%;
+ padding: 10px;
+ background-color: #007bff;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ }
+
+ button:hover
+ {
+ background-color: #0056b3;
+ }
+
+ .error
+ {
+ color: red;
+ text-align: center;
+ }
+
+ @@media only screen and (max-width: 600px)
+ {
+ .container
+ {
+ margin: 10px;
+ padding: 15px;
+ }
+
+ h1
+ {
+ font-size: 20px;
+ }
+
+ input, button
+ {
+ padding: 6px;
+ }
+ }
+ </style>
+</head>
+<body>
+ <div class="login-container">
+ <h1>Login</h1>
+
+ @if (!string.IsNullOrEmpty(TempData["ErrorMessage"] as string))
+ {
+ <p class="error">@TempData["ErrorMessage"]</p>
+ }
+ <form method="post" action="/Account/Login">
+ <div class="form-group">
+ <label for="username">Username</label>
+ <input type="text" id="username" name="username" required />
+ </div>
+ <div class="form-group">
+ <label for="password">Password</label>
+ <input type="password" id="password" name="password" required />
+ </div>
+ <button type="submit">Login</button>
+ </form>
+ </div>
+</body>
+</html>
diff --git a/wwwroot/Account/Login.cshtml.cs b/wwwroot/Account/Login.cshtml.cs
new file mode 100644
index 0000000..39f893d
--- /dev/null
+++ b/wwwroot/Account/Login.cshtml.cs
@@ -0,0 +1,70 @@
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Mvc;
+using System.Security.Claims;
+
+namespace LoginDing.wwwroot.Account;
+
+public class LoginController(IConfiguration configuration) : Controller
+{
+
+ [HttpGet("~/Account/Login")]
+ public IActionResult Index() => View("/wwwroot/Account/Login.cshtml");
+
+ [HttpGet("~/Account/AccessDenied")]
+ public IActionResult AccessDenied() => View("/wwwroot/Account/AccessDenied.cshtml");
+
+ [HttpGet("~/Account/Logout")]
+ public async Task<IActionResult> Logout()
+ {
+ await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
+
+ return RedirectToAction("Index", "Login");
+ }
+
+ // User configuration model for appsettings.json
+ public class UserConfig
+ {
+ public string? UserName { get; set; }
+ public string? Password { get; set; }
+ public string? Role { get; set; }
+ public int ExpireDays { get; set; } = 365;
+ }
+
+ [HttpPost("~/Account/Login")]
+ public async Task<IActionResult> Login()
+ {
+ var username = Request.Form["username"];
+ var password = Request.Form["password"];
+
+ // Load users from appsettings.json
+ var users = configuration.GetSection("MaintenanceUsers").Get<List<UserConfig>>();
+ var user = users?.FirstOrDefault(u => u.UserName == username && u.Password == password);
+
+ TempData["ErrorMessage"] = "";
+
+ if (user != null)
+ {
+ // Add claims including role
+ List<Claim> claims =
+ [
+ new Claim(ClaimTypes.Name, username!),
+ new Claim("CustomClaim", "UserRole"),
+ new Claim(ClaimTypes.Role, user.Role ?? "User") // Add role claim
+ ];
+ var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
+ var authProperties = new AuthenticationProperties
+ {
+ IsPersistent = true,
+ ExpiresUtc = DateTimeOffset.UtcNow.AddDays(user.ExpireDays)
+ };
+
+ await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
+
+ return Redirect("/");
+ }
+ TempData["ErrorMessage"] = "Invalid login attempt";
+
+ return RedirectToAction("Index", "Login");
+ }
+}
diff --git a/wwwroot/Default.js b/wwwroot/Default.js
new file mode 100644
index 0000000..e911c8c
--- /dev/null
+++ b/wwwroot/Default.js
@@ -0,0 +1,23 @@
+onReady(() =>
+{
+ document.addEventListener("click", async function (e)
+ {
+ if (e.target.id && typeof window[e.target.id] === "function")
+ {
+ e.preventDefault();
+ const result = window[e.target.id].call(e, e);
+ if (result instanceof Promise)
+ await result;
+ }
+ });
+});
+
+async function getstatus()
+{
+ const result = await netproxyasync("/api/status/all");
+
+ document.getElementById("status").innerText =
+ ' Smtp:' + result.IsSmtpRunning + '\n' +
+ ' Imap:' + result.IsImapRunning + '\n' +
+ ' Pop3:' + result.IsPop3Running + '\n';
+}
\ No newline at end of file
diff --git a/wwwroot/Index.cshtml b/wwwroot/Index.cshtml
new file mode 100644
index 0000000..41ad521
--- /dev/null
+++ b/wwwroot/Index.cshtml
@@ -0,0 +1,82 @@
+@page
+@{
+ ViewData["Title"] = "Home";
+}
+
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>@ViewData["Title"]</title>
+ <script src="~/scripts/macros.js" defer></script>
+ <script src="~/scripts/netproxy.js" defer></script>
+ <script src="~/default.js" defer></script>
+ <style>
+ body
+ {
+ font-family: Arial, sans-serif;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+ margin: 0;
+ background-color: #f0f0f0;
+ }
+
+ .container
+ {
+ background-color: white;
+ padding: 20px;
+ border-radius: 8px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+ text-align: center;
+ width: 100%;
+ max-width: 400px;
+ }
+
+ h1
+ {
+ font-size: 24px;
+ }
+
+ a
+ {
+ color: #007bff;
+ text-decoration: none;
+ }
+
+ a:hover
+ {
+ text-decoration: underline;
+ }
+
+ @@media (max-width: 600px)
+ {
+ .container
+ {
+ margin: 10px;
+ padding: 15px;
+ }
+
+ h1
+ {
+ font-size: 20px;
+ }
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>Welcome, @User.Identity?.Name</h1>
+ @if (User.Identity?.IsAuthenticated == true)
+ {
+ <p><a href="/Account/Logout">Logout</a></p>
+ }
+ else
+ {
+ <p><a href="/Account/Login">Login</a></p>
+ }
+ </div>
+</body>
+</html>
diff --git a/wwwroot/scripts/macros.js b/wwwroot/scripts/macros.js
new file mode 100644
index 0000000..fd6154a
--- /dev/null
+++ b/wwwroot/scripts/macros.js
@@ -0,0 +1,156 @@
+// version 1.3 2020-08-30 (C) AAB van der Heijden
+// Updated 2.4 2025-01-03
+window.$ = document.querySelector.bind(document);
+window.$$ = document.querySelectorAll.bind(document);
+window.$id = document.getElementById.bind(document);
+
+//DOM reader
+//onReady(() =>
+//{
+//});
+const onReady = (callback) => document.addEventListener("DOMContentLoaded", callback);
+//DOM and stylesheets ready
+const onLoad = (callback) => window.addEventListener("load", callback);
+
+Element.prototype.$ = function (selector)
+{
+ return this.querySelector(selector);
+};
+
+Element.prototype.$$ = function (selector)
+{
+ return this.querySelectorAll(selector);
+};
+
+Element.prototype.addClass = function (className)
+{
+ this.classList.add(className);
+ return this;
+};
+
+Element.prototype.removeClass = function (className)
+{
+ this.classList.remove(className);
+ return this;
+};
+
+Element.prototype.toggleClass = function (className)
+{
+ this.classList.toggle(className);
+ return this;
+};
+
+Element.prototype.hasClass = function (className)
+{
+ return this.classList.contains(className);
+};
+
+Element.prototype.show = function ()
+{
+ this.style.display = 'inline-block';
+ return this;
+};
+
+Element.prototype.hide = function ()
+{
+ this.style.display = 'none';
+ return this;
+};
+
+Element.prototype.toggleVisibility = function ()
+{
+ this.style.display = this.style.display === 'none' ? '' : 'none';
+ return this;
+};
+
+Document.prototype.on = function (event, selectorOrHandler, handler)
+{
+ if (typeof selectorOrHandler === 'function')
+ {
+ this.addEventListener(event, selectorOrHandler);
+ }
+ else if (typeof selectorOrHandler === 'string' && typeof handler === 'function')
+ {
+ this.addEventListener(event, function (e)
+ {
+ if (e.target.matches(selectorOrHandler))
+ {
+ handler.call(e.target, e);
+ }
+ });
+ }
+ else
+ {
+ throw new Error('Invalid arguments: Expected (event, selector, handler) or (event, handler).');
+ }
+
+ return this;
+};
+
+
+Element.prototype.on = function (event, selectorOrHandler, handler)
+{
+ if (typeof selectorOrHandler === 'function')
+ {
+ this.addEventListener(event, selectorOrHandler);
+ }
+ else
+ {
+ this.addEventListener(event, function (e)
+ {
+ if (e.target.matches(selectorOrHandler))
+ {
+ handler.call(e.target, e);
+ }
+ });
+ }
+ return this;
+};
+
+Element.prototype.off = function (event, handler)
+{
+ this.removeEventListener(event, handler);
+ return this;
+};
+
+NodeList.prototype.addClass = function (className)
+{
+ this.forEach(el => el.addClass(className));
+ return this;
+};
+
+NodeList.prototype.removeClass = function (className)
+{
+ this.forEach(el => el.removeClass(className));
+ return this;
+};
+
+NodeList.prototype.toggleClass = function (className)
+{
+ this.forEach(el => el.toggleClass(className));
+ return this;
+};
+
+NodeList.prototype.on = function (event, selectorOrHandler, handler)
+{
+ this.forEach(el => el.on(event, selectorOrHandler, handler));
+ return this;
+};
+
+NodeList.prototype.off = function (event, handler)
+{
+ this.forEach(el => el.off(event, handler));
+ return this;
+};
+
+window.formatCurrency = (value, locale = 'nl-NL', currency = 'EUR', options = {}) =>
+{
+ const formatter = new Intl.NumberFormat(locale,
+ {
+ style: 'currency',
+ currency: currency,
+ ...options
+ });
+
+ return formatter.format(value);
+};
diff --git a/wwwroot/scripts/netproxy.js b/wwwroot/scripts/netproxy.js
new file mode 100644
index 0000000..f47e3f6
--- /dev/null
+++ b/wwwroot/scripts/netproxy.js
@@ -0,0 +1,233 @@
+/**
+ *
+ * @name pure-dom netproxy and template api
+ *
+ * @author Alphons van der Heijden <alphons@heijden.com>
+ * @version 3.0.4 (last revision 30 aug, 2025)
+ * @copyright (c) 2019-2025 Alphons van der Heijden
+ * @alias netproxy, netproxyasync, Element.Template, TemplateHtml
+ *
+ */
+
+// please use defer in script tag
+(function ()
+{
+ 'use strict';
+
+ // Escape functie om XSS te voorkomen
+ function escapeHtml(unsafe)
+ {
+ if (Array.isArray(unsafe))
+ {
+ return unsafe.map(item => escapeHtml(item)).join(', ');
+ }
+ if (unsafe === null || unsafe === undefined)
+ {
+ return '';
+ }
+ return String(unsafe).replace(/[&<>"']/g, function (match)
+ {
+ return {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": '''
+ }[match];
+ });
+ }
+
+ // Helper functie voor spinner logica
+ function manageSpinner(spinner, show, timeoutSpinner)
+ {
+ if (spinner)
+ {
+ spinner.style.display = show ? 'block' : 'none';
+ }
+ if (timeoutSpinner && !show)
+ {
+ clearTimeout(timeoutSpinner);
+ }
+ }
+
+ // Netproxy functionaliteit
+ window.netproxy = function (url, data, onsuccess, onerror, onprogress, timeout = 30000)
+ {
+ const spinner = document.getElementById("netproxyspinner");
+ if (typeof remote !== 'undefined')
+ {
+ url = remote + url;
+ }
+
+ const timeoutSpinner = spinner ? setTimeout(() => manageSpinner(spinner, true), 1000) : null;
+ const xhr = new XMLHttpRequest();
+ xhr.open(data ? 'POST' : 'GET', url, true);
+ xhr.withCredentials = url.indexOf(window.location.host) < 0 && url[0] !== '/';
+
+ if (!(data instanceof FormData))
+ {
+ xhr.timeout = timeout;
+ xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
+ }
+
+ xhr.onloadend = function ()
+ {
+ manageSpinner(spinner, false, timeoutSpinner);
+
+ if (xhr.status === 204)
+ {
+ if (typeof onsuccess === 'function')
+ {
+ onsuccess.call(null, null);
+ }
+ return;
+ }
+
+ if (xhr.status >= 200 && xhr.status < 300)
+ {
+ const contentDisposition = xhr.getResponseHeader('Content-Disposition');
+ if (contentDisposition && contentDisposition.includes('attachment'))
+ {
+ const blob = new Blob([xhr.response], { type: xhr.getResponseHeader('Content-Type') });
+ const filename = contentDisposition.split('filename="')[1]?.split('"')[0] || 'download';
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = filename;
+ a.rel = 'noopener';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ setTimeout(() => URL.revokeObjectURL(a.href), 40000);
+ return;
+ }
+
+ let response = xhr.response;
+ try
+ {
+ response = JSON.parse(xhr.responseText);
+ }
+ catch (e)
+ {
+ // Blijf bij tekst als JSON-parsen faalt
+ }
+
+ try
+ {
+ if (typeof onsuccess === 'function')
+ {
+ onsuccess.call(response, response);
+ }
+ return;
+ }
+ catch (error)
+ {
+ if (typeof onerror === 'function')
+ {
+ onerror.call(xhr, error);
+ }
+ return;
+ }
+ }
+
+ if (xhr.status >= 400)
+ {
+ const error = new Error(`Http:${xhr.status}`);
+ error.path = url;
+ if (typeof onerror === 'function')
+ {
+ onerror.call(xhr, error);
+ return;
+ }
+ throw error;
+ }
+
+ if (xhr.status === 0)
+ {
+ const error = xhr.timedout
+ ? new Error(`Timeout ${timeout}ms for ${url}`)
+ : new Error(`Network error or request canceled for ${url}`);
+ error.path = url;
+ if (typeof onerror === 'function')
+ {
+ onerror.call(xhr, error);
+ return;
+ }
+ throw error;
+ }
+ };
+
+ if (typeof onprogress === 'function')
+ {
+ xhr.upload.onprogress = onprogress;
+ xhr.onprogress = onprogress;
+ }
+
+ xhr.send(data instanceof FormData ? data : JSON.stringify(data));
+ };
+
+ window.netproxyasync = function (url, data, onprogress, timeout = 30000)
+ {
+ return new Promise((resolve, reject) =>
+ {
+ window.netproxy(url, data, resolve, reject, onprogress, timeout);
+ });
+ };
+
+ // Template functionaliteit
+ Element.prototype.Template = function (template, data, append)
+ {
+ var strHtml = window.TemplateHtml(template, data);
+ if (append)
+ {
+ var temp = document.createElement("span");
+ this.insertAdjacentElement('beforeend', temp);
+ temp.outerHTML = strHtml;
+ }
+ else
+ {
+ this.innerHTML = strHtml;
+ }
+ };
+
+ window.TemplateHtml = function (template, data)
+ {
+ try
+ {
+ var element = typeof template === "string" ? document.getElementById(template) : template;
+ if (!element)
+ throw new Error("Template niet gevonden.");
+ if (!element.jscache)
+ {
+ var html = element.innerHTML.replace(/[\t\r\n]/g, " ");
+ var js = "let _='';";
+ var direct, intI, intJ = 0;
+ while (intJ < html.length)
+ {
+ intI = html.indexOf("{{", intJ);
+ if (intI < 0)
+ break;
+ js += `_+='${html.substring(intJ, intI).replace(/'/g, "\\'")}';`;
+ intJ = intI + 2;
+ direct = (html[intJ] === "=");
+ if (direct)
+ intJ++;
+ intI = html.indexOf("}}", intJ);
+ if (intI < 0)
+ break;
+ js += direct ? `_+=escapeHtml(${html.substring(intJ, intI).trim()});` : html.substring(intJ, intI).trim() + ";";
+ intJ = intI + 2;
+ }
+ js += `_+='${html.substring(intJ).replace(/'/g, "\\'")}'; return _;`;
+ element.jscache = new Function('escapeHtml', 'data', js);
+ element.innerHTML = '';
+ }
+ return element.jscache.call(data, escapeHtml);
+ }
+ catch (err)
+ {
+ console.error("Template fout:", err.message);
+ return "";
+ }
+ };
+})();
+