Add ALLOW_REGISTRATION flag and dynamic UI

This commit is contained in:
2026-01-15 06:30:48 +01:00
parent 3e474059f5
commit 7671bb05e4
5 changed files with 755 additions and 491 deletions

View File

@@ -10,6 +10,9 @@ HOST=0.0.0.0
JWT_SECRET=your-super-secure-jwt-secret-key-change-this-in-production
SESSION_SECRET=your-session-secret-change-this-in-production
# User Registration
ALLOW_REGISTRATION=true
# Database
DATABASE_PATH=/app/database/data/edh-stats.db
DATABASE_BACKUP_PATH=/app/database/data/backups

View File

@@ -38,3 +38,7 @@ export const securityConfig = {
commanderNameMinLength: 2,
maxNotesLength: 1000
}
export const registrationConfig = {
allowRegistration: process.env.ALLOW_REGISTRATION !== 'false'
}

View File

@@ -1,11 +1,17 @@
// Authentication routes
import { z } from 'zod'
import User from '../models/User.js'
import { registrationConfig } from '../config/jwt.js'
// Validation schemas
const registerSchema = z.object({
username: z.string().min(3).max(50).regex(/^[a-zA-Z0-9_-]+$/, {
message: 'Username can only contain letters, numbers, underscores, and hyphens'
username: z
.string()
.min(3)
.max(50)
.regex(/^[a-zA-Z0-9_-]+$/, {
message:
'Username can only contain letters, numbers, underscores, and hyphens'
}),
password: z.string().min(8).max(100),
email: z.string().email().optional()
@@ -26,12 +32,30 @@ const updateProfileSchema = z.object({
})
export default async function authRoutes(fastify, options) {
// Public endpoint to check if registration is allowed
fastify.get('/config', async (request, reply) => {
return {
allowRegistration: registrationConfig.allowRegistration
}
})
// Register new user
fastify.post('/register', {
fastify.post(
'/register',
{
config: { rateLimit: { max: 3, timeWindow: '15 minutes' } }
}, async (request, reply) => {
},
async (request, reply) => {
try {
// Check if registration is allowed
if (!registrationConfig.allowRegistration) {
reply.code(403).send({
error: 'Registration Disabled',
message: 'User registration is currently disabled'
})
return
}
// Validate input
const validatedData = registerSchema.parse(request.body)
@@ -39,12 +63,15 @@ export default async function authRoutes(fastify, options) {
const user = await User.create(validatedData)
// Generate JWT token
const token = await reply.jwtSign({
const token = await reply.jwtSign(
{
id: user.id,
username: user.username
}, {
},
{
expiresIn: '15m'
})
}
)
reply.code(201).send({
message: 'User registered successfully',
@@ -56,13 +83,12 @@ export default async function authRoutes(fastify, options) {
},
token
})
} catch (error) {
if (error instanceof z.ZodError) {
reply.code(400).send({
error: 'Validation Error',
message: 'Invalid input data',
details: error.errors.map(e => e.message)
details: error.errors.map((e) => e.message)
})
} else if (error.message.includes('already exists')) {
reply.code(400).send({
@@ -77,12 +103,16 @@ export default async function authRoutes(fastify, options) {
})
}
}
})
}
)
// Login user
fastify.post('/login', {
fastify.post(
'/login',
{
config: { rateLimit: { max: 10, timeWindow: '15 minutes' } }
}, async (request, reply) => {
},
async (request, reply) => {
try {
const { username, password } = loginSchema.parse(request.body)
@@ -97,7 +127,10 @@ export default async function authRoutes(fastify, options) {
}
// Verify password
const isValidPassword = await User.verifyPassword(password, user.password_hash)
const isValidPassword = await User.verifyPassword(
password,
user.password_hash
)
if (!isValidPassword) {
reply.code(401).send({
error: 'Authentication Failed',
@@ -107,12 +140,15 @@ export default async function authRoutes(fastify, options) {
}
// Generate JWT token
const token = await reply.jwtSign({
const token = await reply.jwtSign(
{
id: user.id,
username: user.username
}, {
},
{
expiresIn: '15m'
})
}
)
reply.send({
message: 'Login successful',
@@ -123,13 +159,12 @@ export default async function authRoutes(fastify, options) {
},
token
})
} catch (error) {
if (error instanceof z.ZodError) {
reply.code(400).send({
error: 'Validation Error',
message: 'Invalid input data',
details: error.errors.map(e => e.message)
details: error.errors.map((e) => e.message)
})
} else {
fastify.log.error('Login error:', error)
@@ -139,14 +174,18 @@ export default async function authRoutes(fastify, options) {
})
}
}
})
}
)
// Refresh token
fastify.post('/refresh', {
fastify.post(
'/refresh',
{
config: {
rateLimit: { max: 20, timeWindow: '15 minutes' }
}
}, async (request, reply) => {
},
async (request, reply) => {
try {
await request.jwtVerify()
@@ -160,29 +199,35 @@ export default async function authRoutes(fastify, options) {
}
// Generate new token
const token = await reply.jwtSign({
const token = await reply.jwtSign(
{
id: user.id,
username: user.username
}, {
},
{
expiresIn: '15m'
})
}
)
reply.send({
message: 'Token refreshed successfully',
token
})
} catch (error) {
reply.code(401).send({
error: 'Authentication Failed',
message: 'Invalid or expired token'
})
}
})
}
)
// Get current user profile
fastify.get('/me', {
preHandler: [async (request, reply) => {
fastify.get(
'/me',
{
preHandler: [
async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
@@ -191,8 +236,10 @@ export default async function authRoutes(fastify, options) {
message: 'Invalid or expired token'
})
}
}]
}, async (request, reply) => {
}
]
},
async (request, reply) => {
try {
const user = await User.findById(request.user.id)
if (!user) {
@@ -211,7 +258,6 @@ export default async function authRoutes(fastify, options) {
created_at: user.created_at
}
})
} catch (error) {
fastify.log.error('Get profile error:', error)
reply.code(500).send({
@@ -219,11 +265,15 @@ export default async function authRoutes(fastify, options) {
message: 'Failed to get user profile'
})
}
})
}
)
// Update user profile
fastify.patch('/me', {
preHandler: [async (request, reply) => {
fastify.patch(
'/me',
{
preHandler: [
async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
@@ -232,8 +282,10 @@ export default async function authRoutes(fastify, options) {
message: 'Invalid or expired token'
})
}
}]
}, async (request, reply) => {
}
]
},
async (request, reply) => {
try {
const validatedData = updateProfileSchema.parse(request.body)
@@ -258,13 +310,12 @@ export default async function authRoutes(fastify, options) {
updated_at: user.updated_at
}
})
} catch (error) {
if (error instanceof z.ZodError) {
reply.code(400).send({
error: 'Validation Error',
message: 'Invalid input data',
details: error.errors.map(e => e.message)
details: error.errors.map((e) => e.message)
})
} else if (error.message.includes('already exists')) {
reply.code(400).send({
@@ -279,11 +330,15 @@ export default async function authRoutes(fastify, options) {
})
}
}
})
}
)
// Change password
fastify.post('/change-password', {
preHandler: [async (request, reply) => {
fastify.post(
'/change-password',
{
preHandler: [
async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
@@ -292,11 +347,15 @@ export default async function authRoutes(fastify, options) {
message: 'Invalid or expired token'
})
}
}],
}
],
config: { rateLimit: { max: 3, timeWindow: '1 hour' } }
}, async (request, reply) => {
},
async (request, reply) => {
try {
const { currentPassword, newPassword } = changePasswordSchema.parse(request.body)
const { currentPassword, newPassword } = changePasswordSchema.parse(
request.body
)
// Verify current password
const user = await User.findByUsername(request.user.username)
@@ -308,7 +367,10 @@ export default async function authRoutes(fastify, options) {
return
}
const isValidPassword = await User.verifyPassword(currentPassword, user.password_hash)
const isValidPassword = await User.verifyPassword(
currentPassword,
user.password_hash
)
if (!isValidPassword) {
reply.code(401).send({
error: 'Authentication Failed',
@@ -331,13 +393,12 @@ export default async function authRoutes(fastify, options) {
reply.send({
message: 'Password changed successfully'
})
} catch (error) {
if (error instanceof z.ZodError) {
reply.code(400).send({
error: 'Validation Error',
message: 'Invalid input data',
details: error.errors.map(e => e.message)
details: error.errors.map((e) => e.message)
})
} else {
fastify.log.error('Change password error:', error)
@@ -347,5 +408,6 @@ export default async function authRoutes(fastify, options) {
})
}
}
})
}
)
}

View File

@@ -1,23 +1,36 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en" class="h-full bg-gray-50">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EDH Stats Tracker</title>
<meta name="description" content="Track your Magic: The Gathering EDH/Commander games and statistics">
<link rel="stylesheet" href="/css/styles.css">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
</head>
<body class="h-full flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8 text-center">
<h1 class="text-4xl font-bold font-mtg text-edh-primary mb-4">EDH Stats</h1>
<p class="text-xl text-gray-600 mb-8">Track your Commander games and statistics</p>
<meta
name="description"
content="Track your Magic: The Gathering EDH/Commander games and statistics"
/>
<link rel="stylesheet" href="/css/styles.css" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
</head>
<body
class="h-full flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8"
>
<div class="max-w-md w-full space-y-8 text-center" x-data="indexApp()">
<h1 class="text-4xl font-bold font-mtg text-edh-primary mb-4">
EDH Stats
</h1>
<p class="text-xl text-gray-600 mb-8">
Track your Commander games and statistics
</p>
<div class="space-y-4">
<a href="/login.html" class="btn btn-primary w-full">
🎮 Login to Track Games
</a>
<a href="/register.html" class="btn btn-secondary w-full">
<a
x-show="allowRegistration"
href="/register.html"
class="btn btn-secondary w-full"
>
📝 Create New Account
</a>
</div>
@@ -29,6 +42,41 @@
</div>
<script src="https://cdn.tailwindcss.com"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
</body>
<script
defer
src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"
></script>
<script>
function indexApp() {
return {
allowRegistration: true,
async init() {
await this.checkRegistrationConfig()
},
async checkRegistrationConfig() {
try {
const response = await fetch('/api/auth/config')
if (response.ok) {
const data = await response.json()
this.allowRegistration = data.allowRegistration
} else {
// Default to true if endpoint fails
this.allowRegistration = true
}
} catch (error) {
console.error('Failed to check registration config:', error)
// Default to true if request fails
this.allowRegistration = true
}
}
}
}
document.addEventListener('alpine:init', () => {
Alpine.data('indexApp', indexApp)
})
</script>
</body>
</html>

View File

@@ -1,18 +1,24 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en" class="h-full bg-gray-50">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login - EDH Stats Tracker</title>
<meta name="description" content="Login to track your Magic: The Gathering EDH/Commander games">
<link rel="stylesheet" href="/css/styles.css">
</head>
<body class="h-full flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8" x-data="loginForm()">
<meta
name="description"
content="Login to track your Magic: The Gathering EDH/Commander games"
/>
<link rel="stylesheet" href="/css/styles.css" />
</head>
<body
class="h-full flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8"
>
<div class="max-w-md w-full space-y-8" x-data="loginWithRegistration()">
<!-- Header -->
<div class="text-center">
<h1 class="text-4xl font-bold font-mtg text-edh-primary mb-2">EDH Stats</h1>
<h1 class="text-4xl font-bold font-mtg text-edh-primary mb-2">
EDH Stats
</h1>
<h2 class="text-xl text-gray-600">Sign in to your account</h2>
</div>
@@ -33,14 +39,30 @@
:class="errors.username ? 'border-red-500 focus:ring-red-500' : ''"
class="form-input pl-10"
placeholder="Enter your username"
/>
<div
class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"
>
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
<svg
class="h-5 w-5 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
></path>
</svg>
</div>
</div>
<p x-show="errors.username" x-text="errors.username" class="form-error"></p>
<p
x-show="errors.username"
x-text="errors.username"
class="form-error"
></p>
</div>
<!-- Password Field -->
@@ -57,10 +79,22 @@
:class="errors.password ? 'border-red-500 focus:ring-red-500' : ''"
class="form-input pl-10 pr-10"
placeholder="Enter your password"
/>
<div
class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"
>
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
<svg
class="h-5 w-5 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
></path>
</svg>
</div>
<button
@@ -68,16 +102,47 @@
@click="showPassword = !showPassword"
class="absolute inset-y-0 right-0 pr-3 flex items-center"
>
<svg x-show="!showPassword" class="h-5 w-5 text-gray-400 hover:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
<svg
x-show="!showPassword"
class="h-5 w-5 text-gray-400 hover:text-gray-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
></path>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
></path>
</svg>
<svg x-show="showPassword" class="h-5 w-5 text-gray-400 hover:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path>
<svg
x-show="showPassword"
class="h-5 w-5 text-gray-400 hover:text-gray-600"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
></path>
</svg>
</button>
</div>
<p x-show="errors.password" x-text="errors.password" class="form-error"></p>
<p
x-show="errors.password"
x-text="errors.password"
class="form-error"
></p>
</div>
<!-- Remember Me -->
@@ -89,25 +154,40 @@
type="checkbox"
x-model="formData.remember"
class="h-4 w-4 text-edh-accent focus:ring-edh-accent border-gray-300 rounded"
>
/>
<label for="remember" class="ml-2 block text-sm text-gray-900">
Remember me
</label>
</div>
<div class="text-sm">
<a href="#" class="font-medium text-edh-accent hover:text-edh-primary">
<a
href="#"
class="font-medium text-edh-accent hover:text-edh-primary"
>
Forgot password?
</a>
</div>
</div>
<!-- Error Message -->
<div x-show="serverError" x-transition class="rounded-md bg-red-50 p-4">
<div
x-show="serverError"
x-transition
class="rounded-md bg-red-50 p-4"
>
<div class="flex">
<div class="flex-shrink-0">
<svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
<svg
class="h-5 w-5 text-red-400"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
clip-rule="evenodd"
/>
</svg>
</div>
<div class="ml-3">
@@ -124,22 +204,52 @@
class="btn btn-primary w-full flex justify-center items-center space-x-2"
:class="{ 'opacity-50 cursor-not-allowed': loading }"
>
<svg x-show="!loading" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"></path>
<svg
x-show="!loading"
class="w-5 h-5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"
></path>
</svg>
<svg x-show="loading" class="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
<svg
x-show="loading"
class="animate-spin h-5 w-5"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
<span x-text="loading ? 'Signing in...' : 'Sign in'"></span>
</button>
</div>
<!-- Register Link -->
<div class="text-center">
<div class="text-center" x-show="allowRegistration">
<p class="text-sm text-gray-600">
Don't have an account?
<a href="/register.html" class="font-medium text-edh-accent hover:text-edh-primary">
<a
href="/register.html"
class="font-medium text-edh-accent hover:text-edh-primary"
>
Sign up
</a>
</p>
@@ -149,7 +259,9 @@
<!-- Test Credentials (for development) -->
<div class="card bg-blue-50 border-blue-200">
<h3 class="text-sm font-medium text-blue-800 mb-2">Test Credentials (Development)</h3>
<h3 class="text-sm font-medium text-blue-800 mb-2">
Test Credentials (Development)
</h3>
<div class="text-xs text-blue-700 space-y-1">
<p><strong>Username:</strong> testuser</p>
<p><strong>Password:</strong> password123</p>
@@ -161,7 +273,42 @@
<!-- Scripts -->
<script src="https://cdn.tailwindcss.com"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script
defer
src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"
></script>
<script src="/js/auth.js"></script>
</body>
<script>
function loginWithRegistration() {
return {
...loginForm(),
allowRegistration: true,
async init() {
// Check registration config
await this.checkRegistrationConfig()
// Call parent init if it exists
if (typeof super.init === 'function') {
super.init()
}
},
async checkRegistrationConfig() {
try {
const response = await fetch('/api/auth/config')
if (response.ok) {
const data = await response.json()
this.allowRegistration = data.allowRegistration
} else {
this.allowRegistration = true
}
} catch (error) {
console.error('Failed to check registration config:', error)
this.allowRegistration = true
}
}
}
}
</script>
</body>
</html>