Add project files.

This commit is contained in:
jheaps
2025-10-07 14:24:23 -06:00
parent 3b4d2709f5
commit 4350e4ce4a
93 changed files with 77112 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36327.8 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Media.JoshHeaps.Net", "Media.JoshHeaps.Net\Media.JoshHeaps.Net.csproj", "{2FE68C18-2051-4A9D-86A5-CB81103196D4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2FE68C18-2051-4A9D-86A5-CB81103196D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2FE68C18-2051-4A9D-86A5-CB81103196D4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2FE68C18-2051-4A9D-86A5-CB81103196D4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2FE68C18-2051-4A9D-86A5-CB81103196D4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C8FF1729-29CA-4459-A0C9-74EFC42940AE}
EndGlobalSection
EndGlobal
@@ -0,0 +1,14 @@
-- Email Verification Tokens Table
CREATE TABLE IF NOT EXISTS app.email_verification_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
token VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL,
verified_at TIMESTAMP NULL,
FOREIGN KEY (user_id) REFERENCES app.users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_token ON app.email_verification_tokens(token);
CREATE INDEX IF NOT EXISTS idx_user_id ON app.email_verification_tokens(user_id);
CREATE INDEX IF NOT EXISTS idx_expires_at ON app.email_verification_tokens(expires_at);
@@ -0,0 +1,25 @@
-- User Profiles Table
CREATE TABLE IF NOT EXISTS app.user_profiles (
user_id BIGINT PRIMARY KEY,
bio TEXT NULL,
avatar_url VARCHAR(500) NULL,
location VARCHAR(100) NULL,
website VARCHAR(200) NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES app.users(id) ON DELETE CASCADE
);
-- Create a trigger to automatically create a profile when a user is created
CREATE OR REPLACE FUNCTION app.create_user_profile()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO app.user_profiles (user_id)
VALUES (NEW.id);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_create_user_profile
AFTER INSERT ON app.users
FOR EACH ROW
EXECUTE FUNCTION app.create_user_profile();
+81
View File
@@ -0,0 +1,81 @@
using Npgsql;
namespace Media.JoshHeaps.Net;
public class DbExecutor(IConfiguration config)
{
private string ConnectionString => config["connectionString"]!;
// Returns a single value (first column, first row)
public async Task<T?> ExecuteAsync<T>(string query, object? parameters = null)
{
parameters ??= new();
using var conn = new NpgsqlConnection(ConnectionString);
await conn.OpenAsync();
using var cmd = new NpgsqlCommand(query, conn);
// Add parameters if provided
foreach (var prop in parameters.GetType().GetProperties())
{
cmd.Parameters.AddWithValue($"@{prop.Name}", prop.GetValue(parameters) ?? DBNull.Value);
}
var result = await cmd.ExecuteScalarAsync();
if (result == null || result == DBNull.Value)
return default;
return (T)result;
}
// Returns a list of values (first column from all rows)
public async Task<List<T>> ExecuteListAsync<T>(string query, object? parameters = null)
{
parameters ??= new();
using var conn = new NpgsqlConnection(ConnectionString);
await conn.OpenAsync();
using var cmd = new NpgsqlCommand(query, conn);
foreach (var prop in parameters.GetType().GetProperties())
{
cmd.Parameters.AddWithValue($"@{prop.Name}", prop.GetValue(parameters) ?? DBNull.Value);
}
using var reader = await cmd.ExecuteReaderAsync();
List<T> results = [];
while (await reader.ReadAsync())
{
if (reader.IsDBNull(0))
continue;
results.Add((T)reader.GetValue(0));
}
return results;
}
// Returns a data reader for custom mapping (caller must dispose)
public async Task<T?> ExecuteReaderAsync<T>(string query, Func<NpgsqlDataReader, T?> mapper, object? parameters = null)
{
parameters ??= new();
using var conn = new NpgsqlConnection(ConnectionString);
await conn.OpenAsync();
using var cmd = new NpgsqlCommand(query, conn);
foreach (var prop in parameters.GetType().GetProperties())
{
cmd.Parameters.AddWithValue($"@{prop.Name}", prop.GetValue(parameters) ?? DBNull.Value);
}
using var reader = await cmd.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
return mapper(reader);
}
return default;
}
}
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>1ee15d15-1d19-471d-8772-ce72aeaafbd3</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="MailKit" Version="4.8.0" />
<PackageReference Include="Npgsql" Version="9.0.4" />
</ItemGroup>
</Project>
@@ -0,0 +1,10 @@
namespace Media.JoshHeaps.Net.Models;
public class UserLoginInfo
{
public long Id { get; set; }
public string Email { get; set; } = string.Empty;
public string Username { get; set; } = string.Empty;
public bool IsActive { get; set; }
public bool EmailVerified { get; set; }
}
+22
View File
@@ -0,0 +1,22 @@
namespace Media.JoshHeaps.Net.Models;
public class UserProfile
{
public long UserId { get; set; }
public string? Bio { get; set; }
public string? AvatarUrl { get; set; }
public string? Location { get; set; }
public string? Website { get; set; }
public DateTime UpdatedAt { get; set; }
}
public class UserDashboard
{
public long UserId { get; set; }
public string Username { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public bool EmailVerified { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? LastLogin { get; set; }
public UserProfile Profile { get; set; } = new();
}
+13
View File
@@ -0,0 +1,13 @@
namespace Media.JoshHeaps.Net.Models;
public class UserRow
{
public long Id { get; set; }
public string Email { get; set; } = string.Empty;
public string Username { get; set; } = string.Empty;
public string PasswordHash { get; set; } = string.Empty;
public bool IsActive { get; set; }
public bool EmailVerified { get; set; }
public int FailedAttempts { get; set; }
public DateTime? LockedUntil { get; set; }
}
@@ -0,0 +1,39 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public abstract class AuthenticatedPageModel : PageModel
{
protected long UserId { get; private set; }
protected string Username { get; private set; } = string.Empty;
protected string Email { get; private set; } = string.Empty;
protected bool EmailVerified { get; private set; }
protected bool IsAuthenticated()
{
var userIdStr = HttpContext.Session.GetString("UserId");
return !string.IsNullOrEmpty(userIdStr);
}
protected void LoadUserSession()
{
var userIdStr = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userIdStr) && long.TryParse(userIdStr, out var userId))
{
UserId = userId;
Username = HttpContext.Session.GetString("Username") ?? string.Empty;
Email = HttpContext.Session.GetString("Email") ?? string.Empty;
var emailVerifiedStr = HttpContext.Session.GetString("EmailVerified");
EmailVerified = bool.TryParse(emailVerifiedStr, out var verified) && verified;
}
}
protected void RequireAuthentication()
{
if (!IsAuthenticated())
{
Response.Redirect("/Login");
}
}
}
+244
View File
@@ -0,0 +1,244 @@
@page
@model Media.JoshHeaps.Net.Pages.IndexModel
@{
ViewData["Title"] = "Dashboard";
Layout = "_Layout";
}
@section Styles {
<style>
.dashboard-container {
max-width: 1200px;
margin: 0 auto;
padding: 40px 20px;
}
.welcome-section {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 40px;
border-radius: 12px;
margin-bottom: 30px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.welcome-section h1 {
margin: 0 0 10px 0;
font-size: 32px;
font-weight: 600;
}
.welcome-section p {
margin: 0;
opacity: 0.9;
font-size: 16px;
}
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.card {
background: white;
border-radius: 12px;
padding: 30px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.card h2 {
margin: 0 0 20px 0;
font-size: 20px;
font-weight: 600;
color: #333;
border-bottom: 2px solid #667eea;
padding-bottom: 10px;
}
.info-row {
display: flex;
justify-content: space-between;
padding: 12px 0;
border-bottom: 1px solid #f0f0f0;
}
.info-row:last-child {
border-bottom: none;
}
.info-label {
font-weight: 500;
color: #666;
}
.info-value {
color: #333;
font-weight: 500;
}
.status-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
}
.status-verified {
background: #d4edda;
color: #155724;
}
.status-unverified {
background: #fff3cd;
color: #856404;
}
.quick-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-top: 20px;
}
.btn {
padding: 10px 20px;
border-radius: 6px;
text-decoration: none;
font-weight: 500;
display: inline-block;
transition: all 0.2s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn-secondary:hover {
background: #5a6268;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-danger:hover {
background: #c82333;
}
.empty-state {
text-align: center;
color: #999;
padding: 20px;
font-style: italic;
}
</style>
}
<div class="dashboard-container">
<div class="welcome-section">
<h1>Welcome back, @Model.Dashboard?.Username!</h1>
<p>Here's your account overview</p>
</div>
<div class="dashboard-grid">
<div class="card">
<h2>Account Information</h2>
<div class="info-row">
<span class="info-label">Username:</span>
<span class="info-value">@Model.Dashboard?.Username</span>
</div>
<div class="info-row">
<span class="info-label">Email:</span>
<span class="info-value">@Model.Dashboard?.Email</span>
</div>
<div class="info-row">
<span class="info-label">Email Status:</span>
<span class="info-value">
@if (Model.Dashboard?.EmailVerified == true)
{
<span class="status-badge status-verified">✓ Verified</span>
}
else
{
<span class="status-badge status-unverified">⚠ Not Verified</span>
}
</span>
</div>
<div class="info-row">
<span class="info-label">Member Since:</span>
<span class="info-value">@Model.Dashboard?.CreatedAt.ToString("MMMM d, yyyy")</span>
</div>
@if (Model.Dashboard?.LastLogin != null)
{
<div class="info-row">
<span class="info-label">Last Login:</span>
<span class="info-value">@Model.Dashboard.LastLogin.Value.ToString("MMMM d, yyyy h:mm tt")</span>
</div>
}
</div>
<div class="card">
<h2>Profile Details</h2>
@if (!string.IsNullOrEmpty(Model.Dashboard?.Profile?.Bio))
{
<div class="info-row">
<span class="info-label">Bio:</span>
<span class="info-value">@Model.Dashboard.Profile.Bio</span>
</div>
}
@if (!string.IsNullOrEmpty(Model.Dashboard?.Profile?.Location))
{
<div class="info-row">
<span class="info-label">Location:</span>
<span class="info-value">@Model.Dashboard.Profile.Location</span>
</div>
}
@if (!string.IsNullOrEmpty(Model.Dashboard?.Profile?.Website))
{
<div class="info-row">
<span class="info-label">Website:</span>
<span class="info-value">
<a href="@Model.Dashboard.Profile.Website" target="_blank" style="color: #667eea;">
@Model.Dashboard.Profile.Website
</a>
</span>
</div>
}
@if (string.IsNullOrEmpty(Model.Dashboard?.Profile?.Bio) &&
string.IsNullOrEmpty(Model.Dashboard?.Profile?.Location) &&
string.IsNullOrEmpty(Model.Dashboard?.Profile?.Website))
{
<div class="empty-state">
No profile information yet
</div>
}
</div>
</div>
<div class="card">
<h2>Quick Actions</h2>
<div class="quick-actions">
@if (Model.Dashboard?.EmailVerified == false)
{
<a href="/[email protected](Model.Dashboard.Email)" class="btn btn-primary">
Verify Email
</a>
}
<a href="/Logout" class="btn btn-danger">Logout</a>
</div>
</div>
</div>
+26
View File
@@ -0,0 +1,26 @@
using Media.JoshHeaps.Net.Models;
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages
{
public class IndexModel(UserService userService) : AuthenticatedPageModel
{
public UserDashboard? Dashboard { get; set; }
public async Task<IActionResult> OnGetAsync()
{
if (!IsAuthenticated())
{
return Redirect("/Login");
}
LoadUserSession();
// Load user dashboard data
Dashboard = await userService.GetUserDashboardAsync(UserId);
return Page();
}
}
}
+76
View File
@@ -0,0 +1,76 @@
@page
@model Media.JoshHeaps.Net.Pages.LoginModel
@{
ViewData["Title"] = "Login";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/auth.css" asp-append-version="true" />
}
@section Scripts {
<script src="~/js/auth.js" asp-append-version="true"></script>
}
<div class="auth-container">
<div class="auth-card">
<div class="auth-header">
<h1>Welcome Back</h1>
<p>Sign in to your account to continue</p>
</div>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">
@Model.ErrorMessage
</div>
}
@if (!string.IsNullOrEmpty(Model.SuccessMessage))
{
<div class="alert alert-success">
@Model.SuccessMessage
</div>
}
@if (!string.IsNullOrEmpty(Model.WarningMessage))
{
<div class="alert alert-warning">
@Model.WarningMessage
</div>
}
<form id="loginForm" method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label for="email" class="form-label">Email or Username</label>
<input type="text" class="form-control" id="email" name="email"
value="@Model.Email" autocomplete="username" required />
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="password" class="form-label">Password</label>
<div class="password-wrapper">
<input type="password" class="form-control" id="password" name="password"
autocomplete="current-password" required />
<button type="button" class="password-toggle">Show</button>
</div>
<div class="invalid-feedback"></div>
</div>
<div class="checkbox-wrapper">
<input type="checkbox" id="rememberMe" name="rememberMe"
@(Model.RememberMe ? "checked" : "") />
<label for="rememberMe">Remember me</label>
</div>
<button type="submit" class="btn-primary">Sign In</button>
</form>
<div class="auth-footer">
<p>Don't have an account? <a href="/Register">Sign up</a></p>
</div>
</div>
</div>
+96
View File
@@ -0,0 +1,96 @@
using Media.JoshHeaps.Net.Models;
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class LoginModel : PageModel
{
private readonly AuthService _authService;
[BindProperty]
public string Email { get; set; } = string.Empty;
[BindProperty]
public string Password { get; set; } = string.Empty;
[BindProperty]
public bool RememberMe { get; set; }
public string? ErrorMessage { get; set; }
public string? SuccessMessage { get; set; }
public string? WarningMessage { get; set; }
public LoginModel(AuthService authService)
{
_authService = authService;
}
public void OnGet([FromQuery] string? registered, [FromQuery] string? verified)
{
// Check if user is already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
{
Response.Redirect("/");
return;
}
// Show success message if coming from registration
if (registered == "true")
{
SuccessMessage = "Registration successful! Please check your email to verify your account.";
}
// Show success message if email was just verified
if (verified == "true")
{
SuccessMessage = "Email verified! You can now sign in.";
}
}
public async Task<IActionResult> OnPostAsync()
{
if (string.IsNullOrWhiteSpace(Email) || string.IsNullOrWhiteSpace(Password))
{
ErrorMessage = "Email/username and password are required";
return Page();
}
var (success, error, userInfo) = await _authService.LoginAsync(Email, Password);
if (!success || userInfo == null)
{
ErrorMessage = error ?? "Login failed";
return Page();
}
// Set session
HttpContext.Session.SetString("UserId", userInfo.Id.ToString());
HttpContext.Session.SetString("Username", userInfo.Username);
HttpContext.Session.SetString("Email", userInfo.Email);
HttpContext.Session.SetString("EmailVerified", userInfo.EmailVerified.ToString());
// Show warning if email not verified (but still allow login)
if (!userInfo.EmailVerified)
{
WarningMessage = $"Your email is not verified. <a href='/ResendVerification?email={Uri.EscapeDataString(userInfo.Email)}'>Resend verification email</a>";
}
// Set cookie if remember me is checked
if (RememberMe)
{
var cookieOptions = new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddDays(30),
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict
};
Response.Cookies.Append("RememberMe", userInfo.Id.ToString(), cookieOptions);
}
return Redirect("/");
}
}
@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class LogoutModel : PageModel
{
public IActionResult OnGet()
{
// Clear session
HttpContext.Session.Clear();
// Clear remember me cookie if exists
if (Request.Cookies.ContainsKey("RememberMe"))
{
Response.Cookies.Delete("RememberMe");
}
// Redirect to login page
return Redirect("/Login");
}
public IActionResult OnPost()
{
// Same as OnGet
return OnGet();
}
}
+79
View File
@@ -0,0 +1,79 @@
@page
@model Media.JoshHeaps.Net.Pages.RegisterModel
@{
ViewData["Title"] = "Register";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/auth.css" asp-append-version="true" />
}
@section Scripts {
<script src="~/js/auth.js" asp-append-version="true"></script>
}
<div class="auth-container">
<div class="auth-card">
<div class="auth-header">
<h1>Create Account</h1>
<p>Sign up to get started</p>
</div>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">
@Model.ErrorMessage
</div>
}
<form id="registerForm" method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" name="email"
value="@Model.Email" autocomplete="email" required />
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username"
value="@Model.Username" autocomplete="username" required
pattern="[a-zA-Z0-9_]{3,50}"
title="Username must be 3-50 characters, alphanumeric and underscores only" />
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="password" class="form-label">Password</label>
<div class="password-wrapper">
<input type="password" class="form-control" id="password" name="password"
autocomplete="new-password" required minlength="8" />
<button type="button" class="password-toggle">Show</button>
</div>
<div class="invalid-feedback"></div>
<div class="password-strength">
<div class="password-strength-bar"></div>
</div>
<div class="password-strength-text"></div>
</div>
<div class="form-group">
<label for="confirmPassword" class="form-label">Confirm Password</label>
<div class="password-wrapper">
<input type="password" class="form-control" id="confirmPassword" name="confirmPassword"
autocomplete="new-password" required minlength="8" />
<button type="button" class="password-toggle">Show</button>
</div>
<div class="invalid-feedback"></div>
</div>
<button type="submit" class="btn-primary">Create Account</button>
</form>
<div class="auth-footer">
<p>Already have an account? <a href="/Login">Sign in</a></p>
</div>
</div>
</div>
@@ -0,0 +1,125 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text.RegularExpressions;
namespace Media.JoshHeaps.Net.Pages;
public class RegisterModel : PageModel
{
private readonly AuthService _authService;
private readonly EmailService _emailService;
[BindProperty]
public string Email { get; set; } = string.Empty;
[BindProperty]
public string Username { get; set; } = string.Empty;
[BindProperty]
public string Password { get; set; } = string.Empty;
[BindProperty]
public string ConfirmPassword { get; set; } = string.Empty;
public string? ErrorMessage { get; set; }
public RegisterModel(AuthService authService, EmailService emailService)
{
_authService = authService;
_emailService = emailService;
}
public void OnGet()
{
// Check if user is already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
{
Response.Redirect("/");
}
}
public async Task<IActionResult> OnPostAsync()
{
// Validation
if (string.IsNullOrWhiteSpace(Email) || string.IsNullOrWhiteSpace(Username) ||
string.IsNullOrWhiteSpace(Password) || string.IsNullOrWhiteSpace(ConfirmPassword))
{
ErrorMessage = "All fields are required";
return Page();
}
// Validate email format
if (!IsValidEmail(Email))
{
ErrorMessage = "Please enter a valid email address";
return Page();
}
// Validate username format
if (!IsValidUsername(Username))
{
ErrorMessage = "Username must be 3-50 characters, alphanumeric and underscores only";
return Page();
}
// Validate password length
if (Password.Length < 8)
{
ErrorMessage = "Password must be at least 8 characters";
return Page();
}
// Validate password match
if (Password != ConfirmPassword)
{
ErrorMessage = "Passwords do not match";
return Page();
}
// Register user
var (success, error, verificationToken) = await _authService.RegisterUserAsync(Email, Username, Password);
if (!success)
{
ErrorMessage = error ?? "Registration failed";
return Page();
}
// Send verification email
if (!string.IsNullOrEmpty(verificationToken))
{
await _emailService.SendVerificationEmailAsync(Email, Username, verificationToken);
}
// Redirect to verification pending page
return Redirect("/VerificationPending?email=" + Uri.EscapeDataString(Email));
}
private bool IsValidEmail(string email)
{
try
{
var regex = new Regex(@"^[^\s@]+@[^\s@]+\.[^\s@]+$");
return regex.IsMatch(email);
}
catch
{
return false;
}
}
private bool IsValidUsername(string username)
{
try
{
var regex = new Regex(@"^[a-zA-Z0-9_]{3,50}$");
return regex.IsMatch(username);
}
catch
{
return false;
}
}
}
@@ -0,0 +1,51 @@
@page
@model Media.JoshHeaps.Net.Pages.ResendVerificationModel
@{
ViewData["Title"] = "Resend Verification Email";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/auth.css" asp-append-version="true" />
}
<div class="auth-container">
<div class="auth-card">
<div class="auth-header">
<h1>Resend Verification Email</h1>
<p>Enter your email address to receive a new verification link</p>
</div>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">
@Model.ErrorMessage
</div>
}
@if (!string.IsNullOrEmpty(Model.SuccessMessage))
{
<div class="alert alert-success">
@Model.SuccessMessage
</div>
}
<form method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label for="email" class="form-label">Email Address</label>
<input type="email" class="form-control" id="email" name="email"
value="@Model.Email" autocomplete="email" required />
<div class="invalid-feedback"></div>
</div>
<button type="submit" class="btn-primary">Send Verification Email</button>
</form>
<div class="auth-footer">
<p>
<a href="/Login">Back to Login</a>
</p>
</div>
</div>
</div>
@@ -0,0 +1,66 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class ResendVerificationModel : PageModel
{
private readonly AuthService _authService;
private readonly EmailService _emailService;
[BindProperty]
public string Email { get; set; } = string.Empty;
public string? ErrorMessage { get; set; }
public string? SuccessMessage { get; set; }
public ResendVerificationModel(AuthService authService, EmailService emailService)
{
_authService = authService;
_emailService = emailService;
}
public void OnGet([FromQuery] string? email)
{
if (!string.IsNullOrEmpty(email))
{
Email = email;
}
}
public async Task<IActionResult> OnPostAsync()
{
if (string.IsNullOrWhiteSpace(Email))
{
ErrorMessage = "Email is required";
return Page();
}
var (success, error, verificationToken) = await _authService.ResendVerificationTokenAsync(Email);
if (!success)
{
ErrorMessage = error ?? "Failed to resend verification email";
return Page();
}
// Send verification email
if (!string.IsNullOrEmpty(verificationToken))
{
var emailSent = await _emailService.SendVerificationEmailAsync(Email, Email, verificationToken);
if (emailSent)
{
SuccessMessage = "Verification email sent! Please check your inbox.";
}
else
{
ErrorMessage = "Failed to send email. Please try again later.";
return Page();
}
}
return Page();
}
}
@@ -0,0 +1,32 @@
@{
Layout = null;
ViewData["cssVersion"] = "0.0.1"; // <--- change this once to bust cache
}
<!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>
@await RenderSectionAsync("Styles", required: false)
@await RenderSectionAsync("Scripts", required: false)
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</head>
<body>
<header>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
</footer>
</body>
</html>
@@ -0,0 +1,48 @@
/* Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}
@@ -0,0 +1,59 @@
@page
@model Media.JoshHeaps.Net.Pages.VerificationPendingModel
@{
ViewData["Title"] = "Check Your Email";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/auth.css" asp-append-version="true" />
}
<div class="auth-container">
<div class="auth-card">
<div class="auth-header">
<h1>Check Your Email</h1>
<p>We've sent you a verification link</p>
</div>
<div style="text-align: center; padding: 20px 0;">
<svg width="80" height="80" viewBox="0 0 80 80" fill="none" style="margin-bottom: 20px;">
<circle cx="40" cy="40" r="38" stroke="#667eea" stroke-width="4"/>
<path d="M20 35 L40 50 L60 35" stroke="#667eea" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="20" y="30" width="40" height="25" stroke="#667eea" stroke-width="4" fill="none" rx="2"/>
</svg>
</div>
<div style="background: #f9f9f9; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
<p style="margin: 0 0 15px 0; text-align: center;">
A verification email has been sent to:
</p>
<p style="margin: 0; text-align: center; font-weight: 600; color: #667eea;">
@Model.Email
</p>
</div>
<p style="text-align: center; color: #666; font-size: 14px; line-height: 1.6;">
Please check your inbox and click the verification link to activate your account.
The link will expire in 24 hours.
</p>
<div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #dee2e6;">
<p style="text-align: center; color: #666; font-size: 14px; margin-bottom: 15px;">
Didn't receive the email?
</p>
<p style="text-align: center;">
<a href="/[email protected](Model.Email)"
style="color: #667eea; text-decoration: none; font-weight: 500;">
Resend verification email
</a>
</p>
</div>
<div class="auth-footer" style="margin-top: 30px;">
<p>
<a href="/Login">Back to Login</a>
</p>
</div>
</div>
</div>
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class VerificationPendingModel : PageModel
{
public string Email { get; set; } = string.Empty;
public IActionResult OnGet([FromQuery] string? email)
{
if (string.IsNullOrEmpty(email))
{
return Redirect("/Register");
}
Email = email;
return Page();
}
}
@@ -0,0 +1,50 @@
@page
@model Media.JoshHeaps.Net.Pages.VerifyEmailModel
@{
ViewData["Title"] = "Verify Email";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/auth.css" asp-append-version="true" />
}
<div class="auth-container">
<div class="auth-card">
<div class="auth-header">
<h1>@(Model.Success ? "Email Verified!" : "Verification Failed")</h1>
</div>
@if (Model.Success)
{
<div class="alert alert-success">
@Model.Message
</div>
<p style="text-align: center; margin-top: 20px;">
Your email has been successfully verified. You can now sign in to your account.
</p>
<a href="/Login" class="btn-primary" style="display: inline-block; text-align: center; text-decoration: none;">
Go to Login
</a>
}
else
{
<div class="alert alert-danger">
@Model.Message
</div>
@if (Model.ShowResendLink)
{
<p style="text-align: center; margin-top: 20px;">
<a href="/ResendVerification" style="color: #667eea;">Request a new verification email</a>
</p>
}
else
{
<p style="text-align: center; margin-top: 20px;">
<a href="/Login" style="color: #667eea;">Go to Login</a>
</p>
}
}
</div>
</div>
@@ -0,0 +1,48 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class VerifyEmailModel : PageModel
{
private readonly AuthService _authService;
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
public bool ShowResendLink { get; set; }
public VerifyEmailModel(AuthService authService)
{
_authService = authService;
}
public async Task<IActionResult> OnGetAsync([FromQuery] string? token)
{
if (string.IsNullOrEmpty(token))
{
Success = false;
Message = "Invalid verification link";
ShowResendLink = false;
return Page();
}
var (success, error) = await _authService.VerifyEmailAsync(token);
Success = success;
if (success)
{
Message = "Your email has been successfully verified!";
ShowResendLink = false;
}
else
{
Message = error ?? "Verification failed";
// Show resend link if token expired
ShowResendLink = error?.Contains("expired", StringComparison.OrdinalIgnoreCase) ?? false;
}
return Page();
}
}
+42
View File
@@ -0,0 +1,42 @@
using Media.JoshHeaps.Net;
using Media.JoshHeaps.Net.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSingleton<DbExecutor>();
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<EmailService>();
builder.Services.AddScoped<UserService>();
// Add session support
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromHours(2);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:49894",
"sslPort": 44317
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5029",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7007;http://localhost:5029",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
+305
View File
@@ -0,0 +1,305 @@
using Media.JoshHeaps.Net;
using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class AuthService(DbExecutor db)
{
// Hash a password using BCrypt
public string HashPassword(string password)
{
return BCrypt.Net.BCrypt.HashPassword(password);
}
// Verify a password against a hash
public bool VerifyPassword(string password, string hash)
{
try
{
return BCrypt.Net.BCrypt.Verify(password, hash);
}
catch
{
return false;
}
}
// Register a new user
public async Task<(bool Success, string? Error, string? VerificationToken)> RegisterUserAsync(string email, string username, string password)
{
try
{
// Check if email already exists
var emailExists = await db.ExecuteAsync<long>(
"SELECT COUNT(*) FROM app.users WHERE email = @email",
new { email }
);
if (emailExists > 0)
{
return (false, "Email is already registered", null);
}
// Check if username already exists
var usernameExists = await db.ExecuteAsync<long>(
"SELECT COUNT(*) FROM app.users WHERE username = @username",
new { username }
);
if (usernameExists > 0)
{
return (false, "Username is already taken", null);
}
// Hash the password
var passwordHash = HashPassword(password);
// Insert new user and get the user ID
var userId = await db.ExecuteAsync<long>(
@"INSERT INTO app.users (email, username, password_hash, is_active, email_verified, failed_login_attempts)
VALUES (@email, @username, @passwordHash, true, false, 0)
RETURNING id",
new { email, username, passwordHash }
);
// Generate verification token
var verificationToken = GenerateVerificationToken();
var expiresAt = DateTime.UtcNow.AddHours(24);
// Store verification token
await db.ExecuteAsync<object>(
@"INSERT INTO app.email_verification_tokens (user_id, token, expires_at)
VALUES (@userId, @verificationToken, @expiresAt)",
new { userId, verificationToken, expiresAt }
);
return (true, null, verificationToken);
}
catch (Exception ex)
{
return (false, $"Registration failed: {ex.Message}", null);
}
}
// Generate verification token
private string GenerateVerificationToken()
{
return Guid.NewGuid().ToString("N");
}
// Verify email with token
public async Task<(bool Success, string? Error)> VerifyEmailAsync(string token)
{
try
{
// Get token info
var tokenRow = await db.ExecuteReaderAsync(
@"SELECT user_id, expires_at, verified_at
FROM app.email_verification_tokens
WHERE token = @token",
reader =>
{
return new
{
UserId = reader.GetInt64(0),
ExpiresAt = reader.GetDateTime(1),
VerifiedAt = reader.IsDBNull(2) ? (DateTime?)null : reader.GetDateTime(2)
};
},
new { token }
);
if (tokenRow == null)
{
return (false, "Invalid verification token");
}
if (tokenRow.VerifiedAt.HasValue)
{
return (false, "Email has already been verified");
}
if (tokenRow.ExpiresAt < DateTime.UtcNow)
{
return (false, "Verification token has expired");
}
// Mark token as verified
await db.ExecuteAsync<object>(
"UPDATE app.email_verification_tokens SET verified_at = @verifiedAt WHERE token = @token",
new { verifiedAt = DateTime.UtcNow, token }
);
// Mark user email as verified
await db.ExecuteAsync<object>(
"UPDATE app.users SET email_verified = true WHERE id = @userId",
new { userId = tokenRow.UserId }
);
return (true, null);
}
catch (Exception ex)
{
return (false, $"Verification failed: {ex.Message}");
}
}
// Resend verification email
public async Task<(bool Success, string? Error, string? VerificationToken)> ResendVerificationTokenAsync(string email)
{
try
{
// Get user by email
var userRow = await db.ExecuteReaderAsync(
"SELECT id, email_verified FROM app.users WHERE email = @email",
reader =>
{
return new
{
UserId = reader.GetInt64(0),
EmailVerified = reader.GetBoolean(1)
};
},
new { email }
);
if (userRow == null)
{
return (false, "Email not found", null);
}
if (userRow.EmailVerified)
{
return (false, "Email is already verified", null);
}
// Invalidate old tokens (set verified_at to prevent reuse)
await db.ExecuteAsync<object>(
"UPDATE app.email_verification_tokens SET verified_at = @verifiedAt WHERE user_id = @userId AND verified_at IS NULL",
new { verifiedAt = DateTime.UtcNow, userId = userRow.UserId }
);
// Generate new verification token
var verificationToken = GenerateVerificationToken();
var expiresAt = DateTime.UtcNow.AddHours(24);
// Store new verification token
await db.ExecuteAsync<object>(
@"INSERT INTO app.email_verification_tokens (user_id, token, expires_at)
VALUES (@userId, @verificationToken, @expiresAt)",
new { userId = userRow.UserId, verificationToken, expiresAt }
);
return (true, null, verificationToken);
}
catch (Exception ex)
{
return (false, $"Failed to resend verification: {ex.Message}", null);
}
}
// Login user
public async Task<(bool Success, string? Error, UserLoginInfo? User)> LoginAsync(string emailOrUsername, string password)
{
try
{
// Get user by email or username
var query = @"
SELECT id, email, username, password_hash, is_active, email_verified,
failed_login_attempts, locked_until, last_login
FROM app.users
WHERE email = @emailOrUsername OR username = @emailOrUsername";
var userRow = await db.ExecuteReaderAsync(query, reader =>
{
return new UserRow
{
Id = reader.GetInt64(0),
Email = reader.GetString(1),
Username = reader.GetString(2),
PasswordHash = reader.GetString(3),
IsActive = reader.GetBoolean(4),
EmailVerified = reader.GetBoolean(5),
FailedAttempts = reader.GetInt32(6),
LockedUntil = reader.IsDBNull(7) ? (DateTime?)null : reader.GetDateTime(7)
};
}, new { emailOrUsername });
if (userRow == null)
{
return (false, "Invalid email/username or password", null);
}
// Check if account is locked
if (userRow.LockedUntil.HasValue && userRow.LockedUntil.Value > DateTime.UtcNow)
{
var remainingMinutes = (int)(userRow.LockedUntil.Value - DateTime.UtcNow).TotalMinutes;
return (false, $"Account is locked. Try again in {remainingMinutes} minute(s)", null);
}
// Check if account is active
if (!userRow.IsActive)
{
return (false, "Account is deactivated", null);
}
// Verify password
if (!VerifyPassword(password, userRow.PasswordHash))
{
// Increment failed attempts
await IncrementFailedLoginAttemptsAsync(userRow.Id, userRow.FailedAttempts);
return (false, "Invalid email/username or password", null);
}
// Successful login - reset failed attempts and update last login
await ResetFailedLoginAttemptsAsync(userRow.Id);
var userInfo = new UserLoginInfo
{
Id = userRow.Id,
Email = userRow.Email,
Username = userRow.Username,
IsActive = userRow.IsActive,
EmailVerified = userRow.EmailVerified
};
return (true, null, userInfo);
}
catch (Exception ex)
{
return (false, $"Login failed: {ex.Message}", null);
}
}
// Increment failed login attempts
private async Task IncrementFailedLoginAttemptsAsync(long userId, int currentAttempts)
{
var newAttempts = currentAttempts + 1;
// Lock account for 15 minutes after 5 failed attempts
if (newAttempts >= 5)
{
var lockUntil = DateTime.UtcNow.AddMinutes(15);
await db.ExecuteAsync<object>(
"UPDATE app.users SET failed_login_attempts = @newAttempts, locked_until = @lockUntil WHERE id = @userId",
new { userId, newAttempts, lockUntil }
);
}
else
{
await db.ExecuteAsync<object>(
"UPDATE app.users SET failed_login_attempts = @newAttempts WHERE id = @userId",
new { userId, newAttempts }
);
}
}
// Reset failed login attempts
private async Task ResetFailedLoginAttemptsAsync(long userId)
{
await db.ExecuteAsync<object>(
"UPDATE app.users SET failed_login_attempts = 0, locked_until = NULL, last_login = @lastLogin WHERE id = @userId",
new { userId, lastLogin = DateTime.UtcNow }
);
}
}
@@ -0,0 +1,212 @@
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
namespace Media.JoshHeaps.Net.Services;
public class EmailService
{
private readonly IConfiguration _config;
private readonly ILogger<EmailService> _logger;
public EmailService(IConfiguration config, ILogger<EmailService> logger)
{
_config = config;
_logger = logger;
}
public async Task<bool> SendVerificationEmailAsync(string toEmail, string username, string verificationToken)
{
try
{
var appUrl = _config["AppUrl"] ?? "http://localhost:5000";
var verificationUrl = $"{appUrl}/VerifyEmail?token={verificationToken}";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(
_config["Email:FromName"] ?? "Media App",
_config["Email:FromEmail"] ?? "[email protected]"
));
message.To.Add(new MailboxAddress(username, toEmail));
message.Subject = "Verify Your Email Address";
var bodyBuilder = new BodyBuilder
{
HtmlBody = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
.container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
.header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }}
.content {{ background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; }}
.button {{ display: inline-block; padding: 12px 30px; background: #667eea; color: white; text-decoration: none; border-radius: 6px; margin: 20px 0; }}
.footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
</style>
</head>
<body>
<div class='container'>
<div class='header'>
<h1>Welcome, {username}!</h1>
</div>
<div class='content'>
<h2>Verify Your Email Address</h2>
<p>Thank you for registering! Please click the button below to verify your email address and activate your account.</p>
<p style='text-align: center;'>
<a href='{verificationUrl}' class='button'>Verify Email Address</a>
</p>
<p>Or copy and paste this link into your browser:</p>
<p style='word-break: break-all; color: #667eea;'>{verificationUrl}</p>
<p style='margin-top: 30px; color: #666; font-size: 14px;'>
This link will expire in 24 hours. If you didn't create an account, you can safely ignore this email.
</p>
</div>
<div class='footer'>
<p>&copy; {DateTime.UtcNow.Year} Media App. All rights reserved.</p>
</div>
</div>
</body>
</html>
",
TextBody = $@"
Welcome, {username}!
Thank you for registering! Please verify your email address by visiting:
{verificationUrl}
This link will expire in 24 hours.
If you didn't create an account, you can safely ignore this email.
"
};
message.Body = bodyBuilder.ToMessageBody();
using var client = new SmtpClient();
var smtpHost = _config["Email:SmtpHost"];
var smtpPort = int.Parse(_config["Email:SmtpPort"] ?? "587");
var smtpUsername = _config["Email:SmtpUsername"];
var smtpPassword = _config["Email:SmtpPassword"];
var enableSsl = bool.Parse(_config["Email:EnableSsl"] ?? "true");
await client.ConnectAsync(smtpHost, smtpPort, enableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
if (!string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(smtpPassword))
{
await client.AuthenticateAsync(smtpUsername, smtpPassword);
}
await client.SendAsync(message);
await client.DisconnectAsync(true);
_logger.LogInformation($"Verification email sent to {toEmail}");
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed to send verification email to {toEmail}");
return false;
}
}
public async Task<bool> SendPasswordResetEmailAsync(string toEmail, string username, string resetToken)
{
try
{
var appUrl = _config["AppUrl"] ?? "http://localhost:5000";
var resetUrl = $"{appUrl}/ResetPassword?token={resetToken}";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(
_config["Email:FromName"] ?? "Media App",
_config["Email:FromEmail"] ?? "[email protected]"
));
message.To.Add(new MailboxAddress(username, toEmail));
message.Subject = "Password Reset Request";
var bodyBuilder = new BodyBuilder
{
HtmlBody = $@"
<!DOCTYPE html>
<html>
<head>
<style>
body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
.container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
.header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }}
.content {{ background: #f9f9f9; padding: 30px; border-radius: 0 0 8px 8px; }}
.button {{ display: inline-block; padding: 12px 30px; background: #667eea; color: white; text-decoration: none; border-radius: 6px; margin: 20px 0; }}
.footer {{ text-align: center; margin-top: 20px; color: #666; font-size: 12px; }}
</style>
</head>
<body>
<div class='container'>
<div class='header'>
<h1>Password Reset</h1>
</div>
<div class='content'>
<h2>Reset Your Password</h2>
<p>Hello {username},</p>
<p>We received a request to reset your password. Click the button below to create a new password:</p>
<p style='text-align: center;'>
<a href='{resetUrl}' class='button'>Reset Password</a>
</p>
<p>Or copy and paste this link into your browser:</p>
<p style='word-break: break-all; color: #667eea;'>{resetUrl}</p>
<p style='margin-top: 30px; color: #666; font-size: 14px;'>
This link will expire in 1 hour. If you didn't request a password reset, you can safely ignore this email.
</p>
</div>
<div class='footer'>
<p>&copy; {DateTime.UtcNow.Year} Media App. All rights reserved.</p>
</div>
</div>
</body>
</html>
",
TextBody = $@"
Password Reset Request
Hello {username},
We received a request to reset your password. Visit the link below to create a new password:
{resetUrl}
This link will expire in 1 hour.
If you didn't request a password reset, you can safely ignore this email.
"
};
message.Body = bodyBuilder.ToMessageBody();
using var client = new SmtpClient();
var smtpHost = _config["Email:SmtpHost"];
var smtpPort = int.Parse(_config["Email:SmtpPort"] ?? "587");
var smtpUsername = _config["Email:SmtpUsername"];
var smtpPassword = _config["Email:SmtpPassword"];
var enableSsl = bool.Parse(_config["Email:EnableSsl"] ?? "true");
await client.ConnectAsync(smtpHost, smtpPort, enableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
if (!string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(smtpPassword))
{
await client.AuthenticateAsync(smtpUsername, smtpPassword);
}
await client.SendAsync(message);
await client.DisconnectAsync(true);
_logger.LogInformation($"Password reset email sent to {toEmail}");
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed to send password reset email to {toEmail}");
return false;
}
}
}
+105
View File
@@ -0,0 +1,105 @@
using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class UserService
{
private readonly DbExecutor _db;
public UserService(DbExecutor db)
{
_db = db;
}
public async Task<UserDashboard?> GetUserDashboardAsync(long userId)
{
try
{
var query = @"
SELECT
u.id, u.username, u.email, u.email_verified, u.created_at, u.last_login,
p.bio, p.avatar_url, p.location, p.website, p.updated_at
FROM app.users u
LEFT JOIN app.user_profiles p ON u.id = p.user_id
WHERE u.id = @userId";
var dashboard = await _db.ExecuteReaderAsync(query, reader =>
{
return new UserDashboard
{
UserId = reader.GetInt64(0),
Username = reader.GetString(1),
Email = reader.GetString(2),
EmailVerified = reader.GetBoolean(3),
CreatedAt = reader.GetDateTime(4),
LastLogin = reader.IsDBNull(5) ? null : reader.GetDateTime(5),
Profile = new UserProfile
{
UserId = reader.GetInt64(0),
Bio = reader.IsDBNull(6) ? null : reader.GetString(6),
AvatarUrl = reader.IsDBNull(7) ? null : reader.GetString(7),
Location = reader.IsDBNull(8) ? null : reader.GetString(8),
Website = reader.IsDBNull(9) ? null : reader.GetString(9),
UpdatedAt = reader.IsDBNull(10) ? DateTime.UtcNow : reader.GetDateTime(10)
}
};
}, new { userId });
return dashboard;
}
catch (Exception)
{
return null;
}
}
public async Task<UserProfile?> GetUserProfileAsync(long userId)
{
try
{
var query = @"
SELECT user_id, bio, avatar_url, location, website, updated_at
FROM app.user_profiles
WHERE user_id = @userId";
var profile = await _db.ExecuteReaderAsync(query, reader =>
{
return new UserProfile
{
UserId = reader.GetInt64(0),
Bio = reader.IsDBNull(1) ? null : reader.GetString(1),
AvatarUrl = reader.IsDBNull(2) ? null : reader.GetString(2),
Location = reader.IsDBNull(3) ? null : reader.GetString(3),
Website = reader.IsDBNull(4) ? null : reader.GetString(4),
UpdatedAt = reader.GetDateTime(5)
};
}, new { userId });
return profile;
}
catch (Exception)
{
return null;
}
}
public async Task<bool> UpdateUserProfileAsync(long userId, string? bio, string? avatarUrl, string? location, string? website)
{
try
{
await _db.ExecuteAsync<object>(
@"UPDATE app.user_profiles
SET bio = @bio, avatar_url = @avatarUrl, location = @location,
website = @website, updated_at = @updatedAt
WHERE user_id = @userId",
new { userId, bio, avatarUrl, location, website, updatedAt = DateTime.UtcNow }
);
return true;
}
catch (Exception)
{
return false;
}
}
}
@@ -0,0 +1,9 @@
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AppUrl": "https://localhost:5001",
"Email": {
"SmtpHost": "smtp.gmail.com",
"SmtpPort": "587",
"SmtpUsername": "[email protected]",
"SmtpPassword": "***REMOVED***",
"FromEmail": "[email protected]",
"FromName": "Media App",
"EnableSsl": "true"
}
}
+276
View File
@@ -0,0 +1,276 @@
/* Authentication Pages Styling */
:root {
--primary-color: #007bff;
--primary-hover: #0056b3;
--danger-color: #dc3545;
--success-color: #28a745;
--warning-color: #ffc107;
--border-color: #dee2e6;
--input-focus: #80bdff;
--text-muted: #6c757d;
}
.auth-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.auth-card {
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
padding: 40px;
width: 100%;
max-width: 450px;
}
.auth-header {
text-align: center;
margin-bottom: 30px;
}
.auth-header h1 {
font-size: 28px;
font-weight: 600;
color: #333;
margin-bottom: 10px;
}
.auth-header p {
color: var(--text-muted);
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
.form-label {
font-weight: 500;
color: #333;
margin-bottom: 8px;
display: block;
font-size: 14px;
}
.form-control {
width: 100%;
padding: 12px 16px;
border: 1px solid var(--border-color);
border-radius: 6px;
font-size: 14px;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.form-control:focus {
outline: none;
border-color: var(--input-focus);
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}
.form-control.is-invalid {
border-color: var(--danger-color);
}
.form-control.is-invalid:focus {
box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.1);
}
.invalid-feedback {
color: var(--danger-color);
font-size: 13px;
margin-top: 5px;
display: none;
}
.form-control.is-invalid ~ .invalid-feedback {
display: block;
}
.password-wrapper {
position: relative;
}
.password-toggle {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
padding: 4px 8px;
font-size: 14px;
}
.password-toggle:hover {
color: #333;
}
.password-strength {
margin-top: 8px;
height: 4px;
background: var(--border-color);
border-radius: 2px;
overflow: hidden;
display: none;
}
.password-strength.active {
display: block;
}
.password-strength-bar {
height: 100%;
transition: width 0.3s ease, background-color 0.3s ease;
width: 0;
}
.password-strength-bar.weak {
background-color: var(--danger-color);
width: 33%;
}
.password-strength-bar.medium {
background-color: var(--warning-color);
width: 66%;
}
.password-strength-bar.strong {
background-color: var(--success-color);
width: 100%;
}
.password-strength-text {
font-size: 12px;
margin-top: 4px;
display: none;
}
.password-strength-text.active {
display: block;
}
.checkbox-wrapper {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.checkbox-wrapper input[type="checkbox"] {
margin-right: 8px;
width: 16px;
height: 16px;
}
.checkbox-wrapper label {
font-size: 14px;
color: #333;
margin: 0;
cursor: pointer;
}
.btn-primary {
width: 100%;
padding: 12px;
background: var(--primary-color);
color: white;
border: none;
border-radius: 6px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.15s ease-in-out;
}
.btn-primary:hover {
background: var(--primary-hover);
}
.btn-primary:disabled {
background: var(--text-muted);
cursor: not-allowed;
}
.auth-footer {
text-align: center;
margin-top: 24px;
padding-top: 24px;
border-top: 1px solid var(--border-color);
}
.auth-footer p {
color: var(--text-muted);
font-size: 14px;
margin: 0;
}
.auth-footer a {
color: var(--primary-color);
text-decoration: none;
font-weight: 500;
}
.auth-footer a:hover {
text-decoration: underline;
}
.alert {
padding: 12px 16px;
border-radius: 6px;
margin-bottom: 20px;
font-size: 14px;
}
.alert-danger {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.alert-success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.alert-warning {
background-color: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
.spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: white;
border-radius: 50%;
animation: spin 0.6s linear infinite;
margin-right: 8px;
vertical-align: middle;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Responsive */
@media (max-width: 576px) {
.auth-card {
padding: 30px 20px;
}
.auth-header h1 {
font-size: 24px;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

+344
View File
@@ -0,0 +1,344 @@
// Authentication JavaScript
// Password strength checker
function checkPasswordStrength(password) {
let strength = 0;
const strengthBar = document.querySelector('.password-strength-bar');
const strengthText = document.querySelector('.password-strength-text');
const strengthContainer = document.querySelector('.password-strength');
if (!password || password.length === 0) {
if (strengthContainer) strengthContainer.classList.remove('active');
if (strengthText) strengthText.classList.remove('active');
return;
}
if (strengthContainer) strengthContainer.classList.add('active');
if (strengthText) strengthText.classList.add('active');
// Length check
if (password.length >= 8) strength++;
if (password.length >= 12) strength++;
// Character variety checks
if (/[a-z]/.test(password)) strength++;
if (/[A-Z]/.test(password)) strength++;
if (/[0-9]/.test(password)) strength++;
if (/[^a-zA-Z0-9]/.test(password)) strength++;
// Update UI
if (strengthBar) {
strengthBar.className = 'password-strength-bar';
if (strength <= 2) {
strengthBar.classList.add('weak');
if (strengthText) {
strengthText.textContent = 'Weak password';
strengthText.style.color = 'var(--danger-color)';
}
} else if (strength <= 4) {
strengthBar.classList.add('medium');
if (strengthText) {
strengthText.textContent = 'Medium password';
strengthText.style.color = 'var(--warning-color)';
}
} else {
strengthBar.classList.add('strong');
if (strengthText) {
strengthText.textContent = 'Strong password';
strengthText.style.color = 'var(--success-color)';
}
}
}
return strength;
}
// Password visibility toggle
function initPasswordToggles() {
document.querySelectorAll('.password-toggle').forEach(button => {
button.addEventListener('click', function() {
const input = this.previousElementSibling;
if (input && input.type === 'password') {
input.type = 'text';
this.textContent = 'Hide';
} else if (input) {
input.type = 'password';
this.textContent = 'Show';
}
});
});
}
// Form validation
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
function validateUsername(username) {
// Username: 3-50 characters, alphanumeric and underscores only
const re = /^[a-zA-Z0-9_]{3,50}$/;
return re.test(username);
}
function validatePassword(password) {
// Minimum 8 characters
return password && password.length >= 8;
}
function showError(input, message) {
input.classList.add('is-invalid');
let feedback = input.nextElementSibling;
if (!feedback || !feedback.classList.contains('invalid-feedback')) {
feedback = document.createElement('div');
feedback.className = 'invalid-feedback';
input.parentNode.insertBefore(feedback, input.nextSibling);
}
feedback.textContent = message;
}
function clearError(input) {
input.classList.remove('is-invalid');
const feedback = input.nextElementSibling;
if (feedback && feedback.classList.contains('invalid-feedback')) {
feedback.textContent = '';
}
}
// Login form validation
function initLoginForm() {
const form = document.getElementById('loginForm');
if (!form) return;
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');
// Real-time validation
if (emailInput) {
emailInput.addEventListener('blur', function() {
if (!this.value.trim()) {
showError(this, 'Email or username is required');
} else {
clearError(this);
}
});
emailInput.addEventListener('input', function() {
if (this.value.trim()) {
clearError(this);
}
});
}
if (passwordInput) {
passwordInput.addEventListener('blur', function() {
if (!this.value) {
showError(this, 'Password is required');
} else {
clearError(this);
}
});
passwordInput.addEventListener('input', function() {
if (this.value) {
clearError(this);
}
});
}
form.addEventListener('submit', async function(e) {
e.preventDefault();
let isValid = true;
// Validate email/username
if (!emailInput.value.trim()) {
showError(emailInput, 'Email or username is required');
isValid = false;
} else {
clearError(emailInput);
}
// Validate password
if (!passwordInput.value) {
showError(passwordInput, 'Password is required');
isValid = false;
} else {
clearError(passwordInput);
}
if (isValid) {
const submitBtn = form.querySelector('button[type="submit"]');
const originalText = submitBtn.innerHTML;
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner"></span> Logging in...';
// Submit the form
form.submit();
}
});
}
// Registration form validation
function initRegisterForm() {
const form = document.getElementById('registerForm');
if (!form) return;
const emailInput = document.getElementById('email');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const confirmPasswordInput = document.getElementById('confirmPassword');
// Email validation
if (emailInput) {
emailInput.addEventListener('blur', function() {
if (!this.value.trim()) {
showError(this, 'Email is required');
} else if (!validateEmail(this.value)) {
showError(this, 'Please enter a valid email address');
} else {
clearError(this);
}
});
emailInput.addEventListener('input', function() {
if (this.value.trim() && validateEmail(this.value)) {
clearError(this);
}
});
}
// Username validation
if (usernameInput) {
usernameInput.addEventListener('blur', function() {
if (!this.value.trim()) {
showError(this, 'Username is required');
} else if (!validateUsername(this.value)) {
showError(this, 'Username must be 3-50 characters, alphanumeric and underscores only');
} else {
clearError(this);
}
});
usernameInput.addEventListener('input', function() {
if (this.value.trim() && validateUsername(this.value)) {
clearError(this);
}
});
}
// Password validation with strength checker
if (passwordInput) {
passwordInput.addEventListener('input', function() {
checkPasswordStrength(this.value);
if (this.value && validatePassword(this.value)) {
clearError(this);
}
// Also validate confirm password if it has a value
if (confirmPasswordInput && confirmPasswordInput.value) {
if (confirmPasswordInput.value === this.value) {
clearError(confirmPasswordInput);
} else {
showError(confirmPasswordInput, 'Passwords do not match');
}
}
});
passwordInput.addEventListener('blur', function() {
if (!this.value) {
showError(this, 'Password is required');
} else if (!validatePassword(this.value)) {
showError(this, 'Password must be at least 8 characters');
} else {
clearError(this);
}
});
}
// Confirm password validation
if (confirmPasswordInput) {
confirmPasswordInput.addEventListener('input', function() {
if (passwordInput && this.value === passwordInput.value) {
clearError(this);
}
});
confirmPasswordInput.addEventListener('blur', function() {
if (!this.value) {
showError(this, 'Please confirm your password');
} else if (passwordInput && this.value !== passwordInput.value) {
showError(this, 'Passwords do not match');
} else {
clearError(this);
}
});
}
form.addEventListener('submit', async function(e) {
e.preventDefault();
let isValid = true;
// Validate email
if (!emailInput.value.trim()) {
showError(emailInput, 'Email is required');
isValid = false;
} else if (!validateEmail(emailInput.value)) {
showError(emailInput, 'Please enter a valid email address');
isValid = false;
} else {
clearError(emailInput);
}
// Validate username
if (!usernameInput.value.trim()) {
showError(usernameInput, 'Username is required');
isValid = false;
} else if (!validateUsername(usernameInput.value)) {
showError(usernameInput, 'Username must be 3-50 characters, alphanumeric and underscores only');
isValid = false;
} else {
clearError(usernameInput);
}
// Validate password
if (!passwordInput.value) {
showError(passwordInput, 'Password is required');
isValid = false;
} else if (!validatePassword(passwordInput.value)) {
showError(passwordInput, 'Password must be at least 8 characters');
isValid = false;
} else {
clearError(passwordInput);
}
// Validate confirm password
if (!confirmPasswordInput.value) {
showError(confirmPasswordInput, 'Please confirm your password');
isValid = false;
} else if (confirmPasswordInput.value !== passwordInput.value) {
showError(confirmPasswordInput, 'Passwords do not match');
isValid = false;
} else {
clearError(confirmPasswordInput);
}
if (isValid) {
const submitBtn = form.querySelector('button[type="submit"]');
const originalText = submitBtn.innerHTML;
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner"></span> Creating account...';
// Submit the form
form.submit();
}
});
}
// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
initPasswordToggles();
initLoginForm();
initRegisterForm();
});
+4
View File
@@ -0,0 +1,4 @@
// Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2011-2021 Twitter, Inc.
Copyright (c) 2011-2021 The Bootstrap Authors
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.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,427 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-left: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr /* rtl:ignore */;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: left;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: left;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: left;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
/* rtl:raw:
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.css.map */
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;background-color:currentColor;border:0;opacity:.25}hr:not([size]){height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[data-bs-original-title],abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-left:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.2em;background-color:#fcf8e3}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#0d6efd;text-decoration:underline}a:hover{color:#0a58ca}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em;direction:ltr;unicode-bidi:bidi-override}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:#d63384;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:.875em;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:1em;font-weight:700}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:#6c757d;text-align:left}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]::-webkit-calendar-picker-indicator{display:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:left;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:left}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important}
/*# sourceMappingURL=bootstrap-reboot.min.css.map */
File diff suppressed because one or more lines are too long
@@ -0,0 +1,424 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-right: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-right: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr ;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: right;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: right;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: right;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.rtl.css.map */
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;background-color:currentColor;border:0;opacity:.25}hr:not([size]){height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[data-bs-original-title],abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-right:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-right:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.2em;background-color:#fcf8e3}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#0d6efd;text-decoration:underline}a:hover{color:#0a58ca}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em;direction:ltr;unicode-bidi:bidi-override}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:#d63384;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:.875em;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:1em;font-weight:700}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:#6c757d;text-align:right}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]::-webkit-calendar-picker-indicator{display:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:right;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:right}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}[type=email],[type=number],[type=tel],[type=url]{direction:ltr}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important}
/*# sourceMappingURL=bootstrap-reboot.rtl.min.css.map */
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,23 @@
The MIT License (MIT)
Copyright (c) .NET Foundation and Contributors
All rights reserved.
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.
@@ -0,0 +1,435 @@
/**
* @license
* Unobtrusive validation support library for jQuery and jQuery Validate
* Copyright (c) .NET Foundation. All rights reserved.
* Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
* @version v4.0.0
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define("jquery.validate.unobtrusive", ['jquery-validation'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports
module.exports = factory(require('jquery-validation'));
} else {
// Browser global
jQuery.validator.unobtrusive = factory(jQuery);
}
}(function ($) {
var $jQval = $.validator,
adapters,
data_validation = "unobtrusiveValidation";
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
function splitAndTrim(value) {
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
}
function escapeAttributeValue(value) {
// As mentioned on http://api.jquery.com/category/selectors/
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
}
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}
function onErrors(event, validator) { // 'this' is the form element
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
function onSuccess(error) { // 'this' is the form element
var container = error.data("unobtrusiveContainer");
if (container) {
var replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
container.addClass("field-validation-valid").removeClass("field-validation-error");
error.removeData("unobtrusiveContainer");
if (replace) {
container.empty();
}
}
}
function onReset(event) { // 'this' is the form element
var $form = $(this),
key = '__jquery_unobtrusive_validation_form_reset';
if ($form.data(key)) {
return;
}
// Set a flag that indicates we're currently resetting the form.
$form.data(key, true);
try {
$form.data("validator").resetForm();
} finally {
$form.removeData(key);
}
$form.find(".validation-summary-errors")
.addClass("validation-summary-valid")
.removeClass("validation-summary-errors");
$form.find(".field-validation-error")
.addClass("field-validation-valid")
.removeClass("field-validation-error")
.removeData("unobtrusiveContainer")
.find(">*") // If we were using valmsg-replace, get the underlying error
.removeData("unobtrusiveContainer");
}
function validationInfo(form) {
var $form = $(form),
result = $form.data(data_validation),
onResetProxy = $.proxy(onReset, form),
defaultOptions = $jQval.unobtrusive.options || {},
execInContext = function (name, args) {
var func = defaultOptions[name];
func && $.isFunction(func) && func.apply(form, args);
};
if (!result) {
result = {
options: { // options structure passed to jQuery Validate's validate() method
errorClass: defaultOptions.errorClass || "input-validation-error",
errorElement: defaultOptions.errorElement || "span",
errorPlacement: function () {
onError.apply(form, arguments);
execInContext("errorPlacement", arguments);
},
invalidHandler: function () {
onErrors.apply(form, arguments);
execInContext("invalidHandler", arguments);
},
messages: {},
rules: {},
success: function () {
onSuccess.apply(form, arguments);
execInContext("success", arguments);
}
},
attachValidation: function () {
$form
.off("reset." + data_validation, onResetProxy)
.on("reset." + data_validation, onResetProxy)
.validate(this.options);
},
validate: function () { // a validation function that is called by unobtrusive Ajax
$form.validate();
return $form.valid();
}
};
$form.data(data_validation, result);
}
return result;
}
$jQval.unobtrusive = {
adapters: [],
parseElement: function (element, skipAttach) {
/// <summary>
/// Parses a single HTML element for unobtrusive validation attributes.
/// </summary>
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
/// validation to the form. If parsing just this single element, you should specify true.
/// If parsing several elements, you should specify false, and manually attach the validation
/// to the form when you are finished. The default is false.</param>
var $element = $(element),
form = $element.parents("form")[0],
valInfo, rules, messages;
if (!form) { // Cannot do client-side validation without a form
return;
}
valInfo = validationInfo(form);
valInfo.options.rules[element.name] = rules = {};
valInfo.options.messages[element.name] = messages = {};
$.each(this.adapters, function () {
var prefix = "data-val-" + this.name,
message = $element.attr(prefix),
paramValues = {};
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
prefix += "-";
$.each(this.params, function () {
paramValues[this] = $element.attr(prefix + this);
});
this.adapt({
element: element,
form: form,
message: message,
params: paramValues,
rules: rules,
messages: messages
});
}
});
$.extend(rules, { "__dummy__": true });
if (!skipAttach) {
valInfo.attachValidation();
}
},
parse: function (selector) {
/// <summary>
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
/// attribute values.
/// </summary>
/// <param name="selector" type="String">Any valid jQuery selector.</param>
// $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
// element with data-val=true
var $selector = $(selector),
$forms = $selector.parents()
.addBack()
.filter("form")
.add($selector.find("form"))
.has("[data-val=true]");
$selector.find("[data-val=true]").each(function () {
$jQval.unobtrusive.parseElement(this, true);
});
$forms.each(function () {
var info = validationInfo(this);
if (info) {
info.attachValidation();
}
});
}
};
adapters = $jQval.unobtrusive.adapters;
adapters.add = function (adapterName, params, fn) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
/// mmmm is the parameter name).</param>
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
/// attributes into jQuery Validate rules and/or messages.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
if (!fn) { // Called with no params, just a function
fn = params;
params = [];
}
this.push({ name: adapterName, params: params, adapt: fn });
return this;
};
adapters.addBool = function (adapterName, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has no parameter values.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, function (options) {
setValidationValues(options, ruleName || adapterName, true);
});
};
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a minimum value.</param>
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a maximum value.</param>
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
/// have both a minimum and maximum value.</param>
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the minimum value. The default is "min".</param>
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the maximum value. The default is "max".</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
var min = options.params.min,
max = options.params.max;
if (min && max) {
setValidationValues(options, minMaxRuleName, [min, max]);
}
else if (min) {
setValidationValues(options, minRuleName, min);
}
else if (max) {
setValidationValues(options, maxRuleName, max);
}
});
};
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has a single value.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
/// The default is "val".</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [attribute || "val"], function (options) {
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
});
};
$jQval.addMethod("__dummy__", function (value, element, params) {
return true;
});
$jQval.addMethod("regex", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
match = new RegExp(params).exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
var match;
if (nonalphamin) {
match = value.match(/\W/g);
match = match && match.length >= nonalphamin;
}
return match;
});
if ($jQval.methods.extension) {
adapters.addSingleVal("accept", "mimtype");
adapters.addSingleVal("extension", "extension");
} else {
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
// validating the extension, and ignore mime-type validations as they are not supported.
adapters.addSingleVal("extension", "extension", "accept");
}
adapters.addSingleVal("regex", "pattern");
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
adapters.add("equalto", ["other"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
setValidationValues(options, "equalTo", element);
});
adapters.add("required", function (options) {
// jQuery Validate equates "required" with "mandatory" for checkbox elements
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
setValidationValues(options, "required", true);
}
});
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
// For checkboxes and radio buttons, only pick up values from checked fields.
if (field.is(":checkbox")) {
return field.filter(":checked").val() || field.filter(":hidden").val() || '';
}
else if (field.is(":radio")) {
return field.filter(":checked").val() || '';
}
return field.val();
};
});
setValidationValues(options, "remote", value);
});
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
if (options.params.min) {
setValidationValues(options, "minlength", options.params.min);
}
if (options.params.nonalphamin) {
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
}
if (options.params.regex) {
setValidationValues(options, "regex", options.params.regex);
}
});
adapters.add("fileextensions", ["extensions"], function (options) {
setValidationValues(options, "extension", options.params.extensions);
});
$(function () {
$jQval.unobtrusive.parse(document);
});
return $jQval.unobtrusive;
}));
File diff suppressed because one or more lines are too long
@@ -0,0 +1,22 @@
The MIT License (MIT)
=====================
Copyright Jörn Zaefferer
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.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
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.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long