refactor(auth): replace JWT/password-lock with token guards
This commit is contained in:
@@ -3,11 +3,19 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useParams } from 'next/navigation';
|
import { useParams } from 'next/navigation';
|
||||||
import DOMPurify from 'dompurify';
|
import DOMPurify from 'dompurify';
|
||||||
import { wishlistsApi, itemsApi, claimingApi, type Wishlist, type Item } from '@/lib/api';
|
import { authApi, wishlistsApi, itemsApi, claimingApi, type Wishlist, type Item } from '@/lib/api';
|
||||||
import Header from '@/components/header';
|
import Header from '@/components/header';
|
||||||
import PasswordLockGuard from '@/components/password-lock-guard';
|
import GuestGuard from '@/components/guest-guard';
|
||||||
|
|
||||||
export default function PublicWishlistPage() {
|
export default function PublicWishlistPage() {
|
||||||
|
return (
|
||||||
|
<GuestGuard>
|
||||||
|
<PublicWishlistContent />
|
||||||
|
</GuestGuard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PublicWishlistContent() {
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
const [wishlist, setWishlist] = useState<Wishlist | null>(null);
|
const [wishlist, setWishlist] = useState<Wishlist | null>(null);
|
||||||
const [items, setItems] = useState<Item[]>([]);
|
const [items, setItems] = useState<Item[]>([]);
|
||||||
@@ -15,17 +23,36 @@ export default function PublicWishlistPage() {
|
|||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
// Current viewer
|
||||||
|
const [currentGuestId, setCurrentGuestId] = useState<string | null>(null);
|
||||||
|
const [isAdmin, setIsAdmin] = useState(false);
|
||||||
|
|
||||||
// Claim form state
|
// Claim form state
|
||||||
const [claimingItemId, setClaimingItemId] = useState<string | null>(null);
|
const [claimingItemId, setClaimingItemId] = useState<string | null>(null);
|
||||||
const [claimNote, setClaimNote] = useState('');
|
const [claimNote, setClaimNote] = useState('');
|
||||||
|
const [claimQty, setClaimQty] = useState(1);
|
||||||
const [isClaiming, setIsClaiming] = useState(false);
|
const [isClaiming, setIsClaiming] = useState(false);
|
||||||
const [claimError, setClaimError] = useState('');
|
const [claimError, setClaimError] = useState('');
|
||||||
const [justClaimedItemId, setJustClaimedItemId] = useState<string | null>(null);
|
const [justClaimedItemId, setJustClaimedItemId] = useState<string | null>(null);
|
||||||
const [justClaimedNote, setJustClaimedNote] = useState('');
|
|
||||||
|
|
||||||
// Unclaim state
|
// Unclaim state
|
||||||
const [isUnclaiming, setIsUnclaiming] = useState(false);
|
const [isUnclaiming, setIsUnclaiming] = useState(false);
|
||||||
const [unclaimError, setUnclaimError] = useState('');
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const who = await authApi.whoami();
|
||||||
|
if (who.role === 'admin') {
|
||||||
|
setIsAdmin(true);
|
||||||
|
if (who.guest) setCurrentGuestId(who.guest.id);
|
||||||
|
} else if (who.role === 'guest') {
|
||||||
|
setCurrentGuestId(who.guest.id);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchWishlist();
|
fetchWishlist();
|
||||||
@@ -47,10 +74,14 @@ export default function PublicWishlistPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClaimItem = (itemId: string) => {
|
const myClaimFor = (item: Item) => item.claims.find((c) => c.guest.id === currentGuestId);
|
||||||
setClaimingItemId(itemId);
|
|
||||||
|
const handleStartClaim = (item: Item) => {
|
||||||
|
const my = myClaimFor(item);
|
||||||
|
setClaimingItemId(item.id);
|
||||||
setClaimError('');
|
setClaimError('');
|
||||||
setClaimNote('');
|
setClaimNote(my?.note ?? '');
|
||||||
|
setClaimQty(my?.quantity ?? 1);
|
||||||
setJustClaimedItemId(null);
|
setJustClaimedItemId(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,12 +92,12 @@ export default function PublicWishlistPage() {
|
|||||||
setClaimError('');
|
setClaimError('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await claimingApi.claim(itemId, undefined, claimNote);
|
await claimingApi.claim(itemId, { quantity: claimQty, note: claimNote });
|
||||||
|
|
||||||
setJustClaimedItemId(itemId);
|
setJustClaimedItemId(itemId);
|
||||||
setJustClaimedNote(claimNote);
|
|
||||||
setClaimingItemId(null);
|
setClaimingItemId(null);
|
||||||
setClaimNote('');
|
setClaimNote('');
|
||||||
|
setClaimQty(1);
|
||||||
fetchWishlist();
|
fetchWishlist();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setClaimError(err.message || 'Erro ao reservar item');
|
setClaimError(err.message || 'Erro ao reservar item');
|
||||||
@@ -75,19 +106,16 @@ export default function PublicWishlistPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUnclaim = async (itemId: string) => {
|
const handleUnclaim = async (itemId: string, guestId?: string) => {
|
||||||
if (!confirm('Tem certeza que deseja cancelar a reserva deste item?')) {
|
if (!confirm('Cancelar a reserva?')) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsUnclaiming(true);
|
setIsUnclaiming(true);
|
||||||
setUnclaimError('');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await claimingApi.unclaim(itemId);
|
await claimingApi.unclaim(itemId, guestId ? { guestId } : {});
|
||||||
fetchWishlist();
|
fetchWishlist();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setUnclaimError(err.message || 'Erro ao cancelar reserva');
|
alert(err.message || 'Erro ao cancelar reserva');
|
||||||
} finally {
|
} finally {
|
||||||
setIsUnclaiming(false);
|
setIsUnclaiming(false);
|
||||||
}
|
}
|
||||||
@@ -95,7 +123,10 @@ export default function PublicWishlistPage() {
|
|||||||
|
|
||||||
const filteredItems = showClaimed
|
const filteredItems = showClaimed
|
||||||
? items
|
? items
|
||||||
: items.filter((item) => !item.claimedAt || item.id === justClaimedItemId);
|
: items.filter((item) => {
|
||||||
|
const my = myClaimFor(item);
|
||||||
|
return item.remainingQuantity > 0 || my || item.id === justClaimedItemId;
|
||||||
|
});
|
||||||
|
|
||||||
const formatPrice = (price: number | null, currency: string) => {
|
const formatPrice = (price: number | null, currency: string) => {
|
||||||
if (!price) return null;
|
if (!price) return null;
|
||||||
@@ -125,7 +156,6 @@ export default function PublicWishlistPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PasswordLockGuard>
|
|
||||||
<div className="min-h-screen bg-cosmic">
|
<div className="min-h-screen bg-cosmic">
|
||||||
<Header
|
<Header
|
||||||
title={wishlist.name}
|
title={wishlist.name}
|
||||||
@@ -167,7 +197,6 @@ export default function PublicWishlistPage() {
|
|||||||
className="prose prose-indigo dark:prose-invert max-w-none text-gray-700 dark:text-gray-300 [&_a]:text-indigo-600 [&_a]:dark:text-indigo-400 [&_a]:hover:underline"
|
className="prose prose-indigo dark:prose-invert max-w-none text-gray-700 dark:text-gray-300 [&_a]:text-indigo-600 [&_a]:dark:text-indigo-400 [&_a]:hover:underline"
|
||||||
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(wishlist.preferences) }}
|
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(wishlist.preferences) }}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
// Make all links open in new tab
|
|
||||||
const target = e.target as HTMLElement;
|
const target = e.target as HTMLElement;
|
||||||
if (target.tagName === 'A') {
|
if (target.tagName === 'A') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -188,7 +217,7 @@ export default function PublicWishlistPage() {
|
|||||||
onChange={(e) => setShowClaimed(e.target.checked)}
|
onChange={(e) => setShowClaimed(e.target.checked)}
|
||||||
className="h-4 w-4 text-blue-600 border-gray-300 rounded"
|
className="h-4 w-4 text-blue-600 border-gray-300 rounded"
|
||||||
/>
|
/>
|
||||||
<span className="ml-2 text-sm text-gray-700 dark:text-gray-300">Mostrar itens reservados</span>
|
<span className="ml-2 text-sm text-gray-700 dark:text-gray-300">Mostrar itens esgotados</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-gray-600 dark:text-gray-400">
|
<div className="text-sm text-gray-600 dark:text-gray-400">
|
||||||
@@ -205,10 +234,16 @@ export default function PublicWishlistPage() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{filteredItems.map((item) => (
|
{filteredItems.map((item) => {
|
||||||
|
const myClaim = myClaimFor(item);
|
||||||
|
const maxForMe = item.remainingQuantity + (myClaim?.quantity ?? 0);
|
||||||
|
const showQuantitySummary = item.quantity > 1;
|
||||||
|
const sold = item.remainingQuantity === 0 && !myClaim;
|
||||||
|
|
||||||
|
return (
|
||||||
<div
|
<div
|
||||||
key={item.id}
|
key={item.id}
|
||||||
className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-lg transition-all duration-300 hover:scale-105 overflow-hidden"
|
className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-lg transition-all duration-300 overflow-hidden"
|
||||||
>
|
>
|
||||||
<div className="flex flex-col md:flex-row">
|
<div className="flex flex-col md:flex-row">
|
||||||
{/* Left: Image */}
|
{/* Left: Image */}
|
||||||
@@ -224,14 +259,51 @@ export default function PublicWishlistPage() {
|
|||||||
|
|
||||||
{/* Middle: Item Details */}
|
{/* Middle: Item Details */}
|
||||||
<div className="flex-1 p-6">
|
<div className="flex-1 p-6">
|
||||||
<h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-3">
|
<h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-1">
|
||||||
{item.name}
|
{item.name}
|
||||||
</h3>
|
</h3>
|
||||||
|
{showQuantitySummary && (
|
||||||
|
<p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
|
||||||
|
{item.claimedQuantity} de {item.quantity} reservados
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
{item.description && (
|
{item.description && (
|
||||||
<p className="text-base text-gray-600 dark:text-gray-300 mb-4">
|
<p className="text-base text-gray-600 dark:text-gray-300 mb-4">
|
||||||
{item.description}
|
{item.description}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Existing claims list */}
|
||||||
|
{item.claims.length > 0 && (
|
||||||
|
<ul className="text-sm text-gray-700 dark:text-gray-300 space-y-1 mt-4 border-t border-gray-200 dark:border-gray-700 pt-3">
|
||||||
|
{item.claims.map((c) => {
|
||||||
|
const isMine = c.guest.id === currentGuestId;
|
||||||
|
const canCancel = isMine || isAdmin;
|
||||||
|
return (
|
||||||
|
<li key={c.id} className="flex items-center justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
<span className="font-medium">{c.guest.name}</span>
|
||||||
|
<span className="text-gray-500"> · {c.quantity} un.</span>
|
||||||
|
{c.note && (
|
||||||
|
<span className="block text-xs italic text-gray-500">
|
||||||
|
"{c.note}"
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{canCancel && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleUnclaim(item.id, isMine ? undefined : c.guest.id)}
|
||||||
|
disabled={isUnclaiming}
|
||||||
|
className="text-xs text-red-600 hover:underline disabled:opacity-50 cursor-pointer"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right: Action Area */}
|
{/* Right: Action Area */}
|
||||||
@@ -259,53 +331,12 @@ export default function PublicWishlistPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Claimed Badge, Success Message, or Claim Button/Form */}
|
|
||||||
<div className="mt-auto">
|
<div className="mt-auto">
|
||||||
{justClaimedItemId === item.id ? (
|
{sold ? (
|
||||||
<div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
|
<div className="bg-gray-100 dark:bg-gray-700 rounded p-3 text-center text-sm text-gray-700 dark:text-gray-300">
|
||||||
<div className="flex items-center justify-center mb-2">
|
Esgotado
|
||||||
<div className="w-12 h-12 bg-green-500 dark:bg-green-600 rounded-full flex items-center justify-center">
|
|
||||||
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p className="text-center text-lg font-semibold text-gray-900 dark:text-white mb-1">
|
|
||||||
Item reservado!
|
|
||||||
</p>
|
|
||||||
<p className="text-center text-sm text-gray-600 dark:text-gray-400 mb-2">
|
|
||||||
O status está confirmado.
|
|
||||||
</p>
|
|
||||||
{justClaimedNote && (
|
|
||||||
<p className="text-center text-xs text-gray-600 dark:text-gray-400 italic">
|
|
||||||
Sua nota: "{justClaimedNote}"
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : item.claimedAt ? (
|
|
||||||
<div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded p-3">
|
|
||||||
{item.claimedByNote && (
|
|
||||||
<p className="text-xs text-green-700 dark:text-green-300 mt-1">
|
|
||||||
Nota: {item.claimedByNote}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{item.isPurchased && (
|
|
||||||
<p className="text-xs text-green-700 dark:text-green-300 mt-1 font-medium">
|
|
||||||
✓ Comprado
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{showClaimed && (
|
|
||||||
<button
|
|
||||||
onClick={() => handleUnclaim(item.id)}
|
|
||||||
disabled={isUnclaiming}
|
|
||||||
className="mt-3 w-full px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 font-medium disabled:opacity-50 transition-colors cursor-pointer text-sm"
|
|
||||||
>
|
|
||||||
{isUnclaiming ? 'Cancelando...' : 'Cancelar reserva'}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
) : claimingItemId === item.id ? (
|
) : claimingItemId === item.id ? (
|
||||||
<div className="space-y-3">
|
|
||||||
<form onSubmit={(e) => handleSubmitClaim(e, item.id)} className="space-y-3">
|
<form onSubmit={(e) => handleSubmitClaim(e, item.id)} className="space-y-3">
|
||||||
{claimError && (
|
{claimError && (
|
||||||
<div className="p-2 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-400 rounded text-xs">
|
<div className="p-2 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-400 rounded text-xs">
|
||||||
@@ -313,6 +344,23 @@ export default function PublicWishlistPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{item.quantity > 1 && (
|
||||||
|
<div>
|
||||||
|
<label htmlFor={`claim-qty-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
|
Quantidade (máx {maxForMe}):
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id={`claim-qty-${item.id}`}
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={maxForMe}
|
||||||
|
value={claimQty}
|
||||||
|
onChange={(e) => setClaimQty(Math.max(1, Math.min(maxForMe, Number(e.target.value) || 1)))}
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor={`claim-note-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
<label htmlFor={`claim-note-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
Deixe uma nota (opcional):
|
Deixe uma nota (opcional):
|
||||||
@@ -320,7 +368,6 @@ export default function PublicWishlistPage() {
|
|||||||
<textarea
|
<textarea
|
||||||
id={`claim-note-${item.id}`}
|
id={`claim-note-${item.id}`}
|
||||||
rows={3}
|
rows={3}
|
||||||
placeholder="Ex: 'Vou comprar na semana que vem' ou 'Achei uma boa promoção'"
|
|
||||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white resize-none"
|
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white resize-none"
|
||||||
value={claimNote}
|
value={claimNote}
|
||||||
onChange={(e) => setClaimNote(e.target.value)}
|
onChange={(e) => setClaimNote(e.target.value)}
|
||||||
@@ -332,28 +379,34 @@ export default function PublicWishlistPage() {
|
|||||||
disabled={isClaiming}
|
disabled={isClaiming}
|
||||||
className="w-full px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 font-medium disabled:opacity-50 transition-colors cursor-pointer"
|
className="w-full px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 font-medium disabled:opacity-50 transition-colors cursor-pointer"
|
||||||
>
|
>
|
||||||
{isClaiming ? 'Reservando...' : 'Confirmar reserva'}
|
{isClaiming ? 'Reservando...' : (myClaim ? 'Atualizar reserva' : 'Confirmar reserva')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setClaimingItemId(null)}
|
||||||
|
className="w-full px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<button
|
<button
|
||||||
onClick={() => handleClaimItem(item.id)}
|
onClick={() => handleStartClaim(item)}
|
||||||
className="w-full px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 font-medium transition-colors cursor-pointer"
|
className="w-full px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 font-medium transition-colors cursor-pointer"
|
||||||
>
|
>
|
||||||
Vou dar este presente
|
{myClaim ? 'Atualizar reserva' : 'Reservar'}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</PasswordLockGuard>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,140 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { useAuth } from '@/lib/auth-context';
|
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
import Link from 'next/link';
|
|
||||||
import type { ApiError } from '@/lib/api';
|
|
||||||
|
|
||||||
export default function AdminLoginPage() {
|
|
||||||
const [username, setUsername] = useState('');
|
|
||||||
const [password, setPassword] = useState('');
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const { login, isAuthenticated, isLoading: authLoading } = useAuth();
|
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
// Redirect if already logged in
|
|
||||||
useEffect(() => {
|
|
||||||
if (!authLoading && isAuthenticated) {
|
|
||||||
router.push('/admin');
|
|
||||||
}
|
|
||||||
}, [isAuthenticated, authLoading, router]);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError('');
|
|
||||||
setIsLoading(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await login(username, password);
|
|
||||||
router.push('/admin');
|
|
||||||
} catch (err) {
|
|
||||||
const apiError = err as ApiError;
|
|
||||||
setError(apiError.message || 'Login failed');
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Show loading while checking auth status
|
|
||||||
if (authLoading) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">Loading...</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't render login form if already authenticated (will redirect)
|
|
||||||
if (isAuthenticated) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
|
||||||
{/* Hero Section */}
|
|
||||||
<div className="bg-white dark:bg-gray-800 shadow-sm">
|
|
||||||
<div className="max-w-7xl mx-auto py-16 px-4 sm:py-24 sm:px-6 lg:px-8">
|
|
||||||
<div className="text-center">
|
|
||||||
<h1 className="text-5xl sm:text-6xl lg:text-7xl font-bold text-gray-900 dark:text-white mb-4">
|
|
||||||
Admin Login
|
|
||||||
</h1>
|
|
||||||
<p className="text-xl sm:text-2xl text-gray-600 dark:text-gray-300 max-w-3xl mx-auto mb-6">
|
|
||||||
Sign in to your account
|
|
||||||
</p>
|
|
||||||
<Link
|
|
||||||
href="/"
|
|
||||||
className="inline-flex items-center text-base font-medium text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 dark:hover:text-indigo-300 transition-colors"
|
|
||||||
>
|
|
||||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
|
|
||||||
</svg>
|
|
||||||
Back to Home
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Main Content */}
|
|
||||||
<div className="max-w-4xl mx-auto py-12 sm:px-6 lg:px-8">
|
|
||||||
<div className="px-4 sm:px-0">
|
|
||||||
<div className="max-w-md mx-auto">
|
|
||||||
<form className="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-100 dark:border-gray-700 p-8 space-y-6" onSubmit={handleSubmit}>
|
|
||||||
{error && (
|
|
||||||
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-4">
|
|
||||||
<p className="text-sm text-red-800 dark:text-red-400">{error}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<label htmlFor="username" className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
|
|
||||||
Username
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="username"
|
|
||||||
name="username"
|
|
||||||
type="text"
|
|
||||||
autoComplete="username"
|
|
||||||
required
|
|
||||||
className="appearance-none block w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white text-base"
|
|
||||||
placeholder="admin"
|
|
||||||
value={username}
|
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label htmlFor="password" className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
|
|
||||||
Password
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="password"
|
|
||||||
name="password"
|
|
||||||
type="password"
|
|
||||||
autoComplete="current-password"
|
|
||||||
required
|
|
||||||
className="appearance-none block w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-white text-base"
|
|
||||||
placeholder="Password"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={isLoading}
|
|
||||||
className="w-full flex justify-center px-6 py-3 border border-transparent text-base font-semibold rounded-lg text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg transition-all"
|
|
||||||
>
|
|
||||||
{isLoading ? 'Signing in...' : 'Sign In'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import ProtectedRoute from '@/components/protected-route';
|
import { useRouter } from 'next/navigation';
|
||||||
import { useAuth } from '@/lib/auth-context';
|
import AdminGuard from '@/components/admin-guard';
|
||||||
import { wishlistsApi, itemsApi, settingsApi, type Wishlist, type Settings } from '@/lib/api';
|
import { authApi, wishlistsApi, itemsApi, settingsApi, type Wishlist, type Settings } from '@/lib/api';
|
||||||
import Header from '@/components/header';
|
import Header from '@/components/header';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import StatsGrid from '@/components/admin/StatsGrid';
|
import StatsGrid from '@/components/admin/StatsGrid';
|
||||||
@@ -13,15 +13,27 @@ import CreateWishlistModal from '@/components/admin/CreateWishlistModal';
|
|||||||
import ShareButton from '@/components/share-button';
|
import ShareButton from '@/components/share-button';
|
||||||
|
|
||||||
export default function AdminPage() {
|
export default function AdminPage() {
|
||||||
const { logout } = useAuth();
|
return (
|
||||||
|
<AdminGuard>
|
||||||
|
<AdminPageContent />
|
||||||
|
</AdminGuard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AdminPageContent() {
|
||||||
|
const router = useRouter();
|
||||||
const [wishlists, setWishlists] = useState<Wishlist[]>([]);
|
const [wishlists, setWishlists] = useState<Wishlist[]>([]);
|
||||||
const [itemCounts, setItemCounts] = useState<Record<string, number>>({});
|
const [itemCounts, setItemCounts] = useState<Record<string, number>>({});
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [settings, setSettings] = useState<Settings>({
|
const [settings, setSettings] = useState<Settings>({
|
||||||
siteTitle: 'Wishlist',
|
siteTitle: 'Wishlist',
|
||||||
homepageSubtext: 'Browse and explore available wishlists',
|
homepageSubtext: 'Browse and explore available wishlists',
|
||||||
passwordLockEnabled: false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const logout = async () => {
|
||||||
|
await authApi.logout();
|
||||||
|
router.push('/');
|
||||||
|
};
|
||||||
const [showCreateModal, setShowCreateModal] = useState(false);
|
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||||
const [createError, setCreateError] = useState('');
|
const [createError, setCreateError] = useState('');
|
||||||
|
|
||||||
@@ -124,7 +136,7 @@ export default function AdminPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ProtectedRoute>
|
<>
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
||||||
<Header
|
<Header
|
||||||
title="Dashboard"
|
title="Dashboard"
|
||||||
@@ -230,6 +242,6 @@ export default function AdminPage() {
|
|||||||
error={createError}
|
error={createError}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</ProtectedRoute>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
|
||||||
import { eq } from 'drizzle-orm';
|
|
||||||
import { db, settings } from '@/lib/db';
|
|
||||||
import crypto from 'crypto';
|
|
||||||
import { isSecureCookie } from '@/lib/auth/utils';
|
|
||||||
|
|
||||||
// POST /api/lock - Verify password
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const body = await request.json();
|
|
||||||
const { password } = body;
|
|
||||||
|
|
||||||
if (!password) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Password is required' },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the stored password hash
|
|
||||||
const hashSetting = await db
|
|
||||||
.select()
|
|
||||||
.from(settings)
|
|
||||||
.where(eq(settings.key, 'passwordLockHash'))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (hashSetting.length === 0) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Password lock not configured' },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hash the provided password
|
|
||||||
const hash = crypto.createHash('sha256').update(password).digest('hex');
|
|
||||||
|
|
||||||
// Compare hashes
|
|
||||||
if (hash === hashSetting[0].value) {
|
|
||||||
// Password correct - set a cookie
|
|
||||||
const response = NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
message: 'Password verified',
|
|
||||||
});
|
|
||||||
|
|
||||||
response.cookies.set('site_unlocked', 'true', {
|
|
||||||
httpOnly: true,
|
|
||||||
secure: isSecureCookie(request),
|
|
||||||
sameSite: 'lax',
|
|
||||||
maxAge: 60 * 60 * 24,
|
|
||||||
path: '/',
|
|
||||||
});
|
|
||||||
|
|
||||||
return response;
|
|
||||||
} else {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Incorrect password' },
|
|
||||||
{ status: 401 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error verifying password:', error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Failed to verify password' },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import { AuthProvider } from "@/lib/auth-context";
|
|
||||||
import { db, settings } from "@/lib/db";
|
import { db, settings } from "@/lib/db";
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
|
|
||||||
async function getSettings() {
|
async function getSettings() {
|
||||||
try {
|
try {
|
||||||
@@ -51,9 +49,7 @@ export default function RootLayout({
|
|||||||
/>
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body className="font-sans antialiased bg-cosmic">
|
<body className="font-sans antialiased bg-cosmic">
|
||||||
<AuthProvider>
|
|
||||||
{children}
|
{children}
|
||||||
</AuthProvider>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
import Header from '@/components/header';
|
|
||||||
|
|
||||||
export default function LockPage() {
|
|
||||||
const router = useRouter();
|
|
||||||
const [password, setPassword] = useState('');
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError('');
|
|
||||||
setIsSubmitting(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/lock', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ password }),
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
// Password verified, redirect to home
|
|
||||||
router.push('/');
|
|
||||||
router.refresh();
|
|
||||||
} else {
|
|
||||||
setError(data.error || 'Senha incorreta');
|
|
||||||
setPassword('');
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setError('Erro ao verificar senha. Tente novamente.');
|
|
||||||
console.error('Lock verification error:', err);
|
|
||||||
} finally {
|
|
||||||
setIsSubmitting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-cosmic">
|
|
||||||
<Header
|
|
||||||
title="Senha necessária"
|
|
||||||
subtitle="Digite a senha para acessar o site"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="max-w-md mx-auto py-12 px-4 sm:px-6 lg:px-8">
|
|
||||||
<div className="bg-card rounded-2xl shadow-soft border border-[color:var(--border)] overflow-hidden">
|
|
||||||
<div className="p-6">
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
|
||||||
{error && (
|
|
||||||
<div className="p-3 bg-rose-50 dark:bg-rose-900/20 text-rose-700 dark:text-rose-300 rounded-xl text-base">
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label htmlFor="password" className="block text-base font-medium text-[color:var(--ink-soft)] mb-2">
|
|
||||||
Senha
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
id="password"
|
|
||||||
required
|
|
||||||
autoFocus
|
|
||||||
className="w-full px-4 py-3 border border-[color:var(--border)] rounded-xl focus:outline-none focus:ring-2 focus:ring-[color:var(--accent)] text-lg"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
placeholder="Digite a senha"
|
|
||||||
disabled={isSubmitting}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={isSubmitting}
|
|
||||||
className="w-full px-6 py-3 text-lg font-semibold text-white bg-[color:var(--accent)] hover:brightness-110 rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-soft"
|
|
||||||
>
|
|
||||||
{isSubmitting ? 'Verificando...' : 'Entrar'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
314
app/page.tsx
314
app/page.tsx
@@ -1,320 +1,12 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import DOMPurify from 'dompurify';
|
|
||||||
import { wishlistsApi, itemsApi, claimingApi, settingsApi, type Wishlist, type Item, type Settings } from '@/lib/api';
|
|
||||||
import Header from '@/components/header';
|
|
||||||
import PasswordLockGuard from '@/components/password-lock-guard';
|
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const [wishlist, setWishlist] = useState<Wishlist | null>(null);
|
|
||||||
const [items, setItems] = useState<Item[]>([]);
|
|
||||||
const [showClaimed, setShowClaimed] = useState(false);
|
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
|
||||||
const [settings, setSettings] = useState<Settings>({ siteTitle: 'Chá do Martin', homepageSubtext: 'Escolha um presente da lista!' });
|
|
||||||
|
|
||||||
const [claimingItemId, setClaimingItemId] = useState<string | null>(null);
|
|
||||||
const [claimNote, setClaimNote] = useState('');
|
|
||||||
const [isClaiming, setIsClaiming] = useState(false);
|
|
||||||
const [claimError, setClaimError] = useState('');
|
|
||||||
const [justClaimedItemId, setJustClaimedItemId] = useState<string | null>(null);
|
|
||||||
const [justClaimedNote, setJustClaimedNote] = useState('');
|
|
||||||
|
|
||||||
const [isUnclaiming, setIsUnclaiming] = useState(false);
|
|
||||||
const [unclaimError, setUnclaimError] = useState('');
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
bootstrap();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const bootstrap = async () => {
|
|
||||||
try {
|
|
||||||
const [settingsData, wishlists] = await Promise.all([
|
|
||||||
settingsApi.getSettings().catch(() => null),
|
|
||||||
wishlistsApi.getAllPublic(),
|
|
||||||
]);
|
|
||||||
if (settingsData) setSettings(settingsData);
|
|
||||||
|
|
||||||
if (wishlists.length === 0) {
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const primary = wishlists[0];
|
|
||||||
setWishlist(primary);
|
|
||||||
const itemsData = await itemsApi.getAll(primary.id);
|
|
||||||
setItems(itemsData.sort((a, b) => a.sortOrder - b.sortOrder));
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to load home page:', error);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const refetchItems = async () => {
|
|
||||||
if (!wishlist) return;
|
|
||||||
const itemsData = await itemsApi.getAll(wishlist.id);
|
|
||||||
setItems(itemsData.sort((a, b) => a.sortOrder - b.sortOrder));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleClaimItem = (itemId: string) => {
|
|
||||||
setClaimingItemId(itemId);
|
|
||||||
setClaimError('');
|
|
||||||
setClaimNote('');
|
|
||||||
setJustClaimedItemId(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmitClaim = async (e: React.FormEvent, itemId: string) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setIsClaiming(true);
|
|
||||||
setClaimError('');
|
|
||||||
try {
|
|
||||||
await claimingApi.claim(itemId, undefined, claimNote);
|
|
||||||
setJustClaimedItemId(itemId);
|
|
||||||
setJustClaimedNote(claimNote);
|
|
||||||
setClaimingItemId(null);
|
|
||||||
setClaimNote('');
|
|
||||||
await refetchItems();
|
|
||||||
} catch (err: any) {
|
|
||||||
setClaimError(err.message || 'Erro ao reservar item');
|
|
||||||
} finally {
|
|
||||||
setIsClaiming(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleUnclaim = async (itemId: string) => {
|
|
||||||
if (!confirm('Tem certeza que deseja cancelar a reserva deste item?')) return;
|
|
||||||
setIsUnclaiming(true);
|
|
||||||
setUnclaimError('');
|
|
||||||
try {
|
|
||||||
await claimingApi.unclaim(itemId);
|
|
||||||
await refetchItems();
|
|
||||||
} catch (err: any) {
|
|
||||||
setUnclaimError(err.message || 'Erro ao cancelar reserva');
|
|
||||||
} finally {
|
|
||||||
setIsUnclaiming(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const filteredItems = showClaimed
|
|
||||||
? items
|
|
||||||
: items.filter((item) => !item.claimedAt || item.id === justClaimedItemId);
|
|
||||||
|
|
||||||
const formatPrice = (price: number | null, currency: string) => {
|
|
||||||
if (!price) return null;
|
|
||||||
return new Intl.NumberFormat('pt-BR', {
|
|
||||||
style: 'currency',
|
|
||||||
currency: currency || 'BRL',
|
|
||||||
}).format(price);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PasswordLockGuard>
|
<div className="min-h-screen flex items-center justify-center text-center px-6">
|
||||||
<div className="min-h-screen bg-cosmic">
|
|
||||||
<Header
|
|
||||||
title={settings.siteTitle}
|
|
||||||
subtitle={wishlist?.description || settings.homepageSubtext}
|
|
||||||
imageUrl={wishlist?.imageUrl || undefined}
|
|
||||||
maxWidth="max-w-5xl"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="max-w-5xl mx-auto py-12 sm:px-6 lg:px-8">
|
|
||||||
<div className="px-4 sm:px-0">
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="text-center py-12">
|
|
||||||
<p className="text-[color:var(--muted)]">Carregando...</p>
|
|
||||||
</div>
|
|
||||||
) : !wishlist ? (
|
|
||||||
<div className="text-center py-12 bg-card rounded-2xl shadow-soft">
|
|
||||||
<p className="text-[color:var(--muted)]">Nenhuma lista disponível ainda</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{wishlist.preferences && (
|
|
||||||
<div className="mb-8 bg-card rounded-2xl shadow-soft p-6">
|
|
||||||
<h2 className="text-xl font-bold text-[color:var(--ink)] mb-3">
|
|
||||||
Interesses e Preferências
|
|
||||||
</h2>
|
|
||||||
<div
|
|
||||||
className="prose prose-indigo dark:prose-invert max-w-none text-[color:var(--ink-soft)] [&_a]:text-[color:var(--accent)] [&_a]:hover:underline"
|
|
||||||
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(wishlist.preferences) }}
|
|
||||||
onClick={(e) => {
|
|
||||||
const target = e.target as HTMLElement;
|
|
||||||
if (target.tagName === 'A') {
|
|
||||||
e.preventDefault();
|
|
||||||
window.open((target as HTMLAnchorElement).href, '_blank', 'noopener,noreferrer');
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="mb-6 flex items-center justify-between">
|
|
||||||
<label className="flex items-center">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={showClaimed}
|
|
||||||
onChange={(e) => setShowClaimed(e.target.checked)}
|
|
||||||
className="h-4 w-4 rounded border-[color:var(--border)] accent-[color:var(--accent)]"
|
|
||||||
/>
|
|
||||||
<span className="ml-2 text-sm text-[color:var(--ink-soft)]">Mostrar itens reservados</span>
|
|
||||||
</label>
|
|
||||||
<div className="text-sm text-[color:var(--muted)]">
|
|
||||||
{filteredItems.length} de {items.length} itens
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{filteredItems.length === 0 ? (
|
|
||||||
<div className="text-center py-12 bg-card rounded-2xl shadow-soft">
|
|
||||||
<p className="text-[color:var(--muted)]">
|
|
||||||
{showClaimed ? 'Nenhum item nesta lista ainda' : 'Todos os itens já foram reservados!'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-6">
|
|
||||||
{filteredItems.map((item) => (
|
|
||||||
<div
|
|
||||||
key={item.id}
|
|
||||||
className="bg-card rounded-2xl shadow-soft hover:shadow-lifted transition-all duration-300 overflow-hidden"
|
|
||||||
>
|
|
||||||
<div className="flex flex-col md:flex-row">
|
|
||||||
{item.imageUrl && (
|
|
||||||
<div className="md:w-48 md:flex-shrink-0">
|
|
||||||
<img
|
|
||||||
src={item.imageUrl}
|
|
||||||
alt={item.name}
|
|
||||||
className="w-full h-48 md:h-full object-cover"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex-1 p-6">
|
|
||||||
<h3 className="text-2xl font-bold text-[color:var(--ink)] mb-3">
|
|
||||||
{item.name}
|
|
||||||
</h3>
|
|
||||||
{item.description && (
|
|
||||||
<p className="text-base text-[color:var(--ink-soft)] mb-4">
|
|
||||||
{item.description}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="md:w-80 md:flex-shrink-0 p-6 bg-card-soft border-t md:border-t-0 md:border-l border-[color:var(--border)] flex flex-col">
|
|
||||||
<div className="mb-4">
|
|
||||||
{item.purchaseUrls && item.purchaseUrls.length > 0 && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{item.purchaseUrls.map((url, idx) => (
|
|
||||||
<a
|
|
||||||
key={idx}
|
|
||||||
href={url.url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="flex items-center justify-between text-base px-4 py-3 rounded-xl hover:bg-[color:var(--accent-soft)] transition-colors cursor-pointer border border-[color:var(--border)]"
|
|
||||||
>
|
|
||||||
<span className="text-[color:var(--accent)] font-medium">
|
|
||||||
{url.label}
|
|
||||||
</span>
|
|
||||||
<span className="text-[color:var(--ink)] font-bold text-lg">
|
|
||||||
{item.price && formatPrice(item.price, item.currency)}
|
|
||||||
</span>
|
|
||||||
</a>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-auto">
|
|
||||||
{justClaimedItemId === item.id ? (
|
|
||||||
<div className="bg-[color:var(--success-soft)] border border-[color:var(--success-border)] rounded-xl p-4">
|
|
||||||
<div className="flex items-center justify-center mb-2">
|
|
||||||
<div className="w-12 h-12 bg-[color:var(--success)] rounded-full flex items-center justify-center">
|
|
||||||
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p className="text-center text-lg font-semibold text-[color:var(--ink)] mb-1">
|
|
||||||
Item reservado!
|
|
||||||
</p>
|
|
||||||
<p className="text-center text-sm text-[color:var(--ink-soft)] mb-2">
|
|
||||||
O status está confirmado.
|
|
||||||
</p>
|
|
||||||
{justClaimedNote && (
|
|
||||||
<p className="text-center text-xs text-[color:var(--ink-soft)] italic">
|
|
||||||
Sua nota: "{justClaimedNote}"
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : item.claimedAt ? (
|
|
||||||
<div className="bg-[color:var(--success-soft)] border border-[color:var(--success-border)] rounded-xl p-3">
|
|
||||||
{item.claimedByNote && (
|
|
||||||
<p className="text-xs text-[color:var(--success-ink)] mt-1">
|
|
||||||
Nota: {item.claimedByNote}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{item.isPurchased && (
|
|
||||||
<p className="text-xs text-[color:var(--success-ink)] mt-1 font-medium">
|
|
||||||
✓ Comprado
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{showClaimed && (
|
|
||||||
<button
|
|
||||||
onClick={() => handleUnclaim(item.id)}
|
|
||||||
disabled={isUnclaiming}
|
|
||||||
className="mt-3 w-full px-4 py-2 bg-rose-400 text-white rounded-xl hover:bg-rose-500 font-medium disabled:opacity-50 transition-colors cursor-pointer text-sm"
|
|
||||||
>
|
|
||||||
{isUnclaiming ? 'Cancelando...' : 'Cancelar reserva'}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : claimingItemId === item.id ? (
|
|
||||||
<form onSubmit={(e) => handleSubmitClaim(e, item.id)} className="space-y-3">
|
|
||||||
{claimError && (
|
|
||||||
<div className="p-2 bg-rose-50 dark:bg-rose-900/20 text-rose-700 dark:text-rose-300 rounded text-xs">
|
|
||||||
{claimError}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor={`claim-note-${item.id}`} className="block text-sm font-medium text-[color:var(--ink-soft)] mb-1">
|
<h1 className="text-3xl font-bold mb-2">Convite necessário</h1>
|
||||||
Deixe uma nota (opcional):
|
<p className="text-gray-500">Esta página é por convite. Use o link que recebeu.</p>
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
id={`claim-note-${item.id}`}
|
|
||||||
rows={3}
|
|
||||||
placeholder="Ex: 'Vou comprar na semana que vem' ou 'Achei uma boa promoção'"
|
|
||||||
className="w-full px-3 py-2 text-sm border border-[color:var(--border)] rounded-xl focus:outline-none focus:ring-2 focus:ring-[color:var(--accent)] resize-none"
|
|
||||||
value={claimNote}
|
|
||||||
onChange={(e) => setClaimNote(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={isClaiming}
|
|
||||||
className="w-full px-4 py-2 bg-[color:var(--success)] text-white rounded-xl hover:brightness-105 font-medium disabled:opacity-50 transition-all cursor-pointer"
|
|
||||||
>
|
|
||||||
{isClaiming ? 'Reservando...' : 'Confirmar reserva'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
onClick={() => handleClaimItem(item.id)}
|
|
||||||
className="w-full px-4 py-2 bg-[color:var(--accent)] text-white rounded-xl hover:brightness-110 font-medium transition-all cursor-pointer shadow-soft"
|
|
||||||
>
|
|
||||||
Vou dar este presente
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</PasswordLockGuard>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
42
components/admin-guard.tsx
Normal file
42
components/admin-guard.tsx
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
import { authApi } from '@/lib/api';
|
||||||
|
|
||||||
|
export default function AdminGuard({ children }: { children: React.ReactNode }) {
|
||||||
|
const params = useSearchParams();
|
||||||
|
const [state, setState] = useState<'checking' | 'ok' | 'denied'>('checking');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
(async () => {
|
||||||
|
const adm = params.get('adm');
|
||||||
|
try {
|
||||||
|
if (adm) {
|
||||||
|
await authApi.session({ adm });
|
||||||
|
// strip the param from URL but keep route
|
||||||
|
const url = new URL(window.location.href);
|
||||||
|
url.searchParams.delete('adm');
|
||||||
|
window.history.replaceState({}, '', url.toString());
|
||||||
|
}
|
||||||
|
const who = await authApi.whoami();
|
||||||
|
if (cancelled) return;
|
||||||
|
if (who.role === 'admin') setState('ok');
|
||||||
|
else setState('denied');
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) setState('denied');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [params]);
|
||||||
|
|
||||||
|
if (state === 'checking') return <div className="min-h-screen flex items-center justify-center text-gray-500">Verificando…</div>;
|
||||||
|
if (state === 'denied') return <div className="min-h-screen flex items-center justify-center text-center px-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold mb-2">Acesso restrito</h1>
|
||||||
|
<p className="text-gray-500">Adicione <code>?adm=<token></code> à URL para entrar.</p>
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -97,44 +97,6 @@ export default function SettingsSection({ settings, onUpdate }: SettingsSectionP
|
|||||||
This appears below the title on the homepage
|
This appears below the title on the homepage
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="pt-4 border-t border-gray-200 dark:border-gray-700">
|
|
||||||
<div className="flex items-center mb-3">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
id="passwordLockEnabled"
|
|
||||||
className="h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
|
|
||||||
checked={settingsForm.passwordLockEnabled}
|
|
||||||
onChange={(e) =>
|
|
||||||
setSettingsForm((prev) => ({ ...prev, passwordLockEnabled: e.target.checked }))
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<label htmlFor="passwordLockEnabled" className="ml-2 block text-base font-medium text-gray-700 dark:text-gray-300">
|
|
||||||
Enable Password Lock
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
|
|
||||||
When enabled, visitors must enter a password to access the website
|
|
||||||
</p>
|
|
||||||
{settingsForm.passwordLockEnabled && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-base font-medium text-gray-700 dark:text-gray-300 mb-2">
|
|
||||||
Site Password
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-white"
|
|
||||||
value={settingsForm.passwordLock || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
setSettingsForm((prev) => ({ ...prev, passwordLock: e.target.value }))
|
|
||||||
}
|
|
||||||
placeholder="Enter password (leave blank to keep current)"
|
|
||||||
/>
|
|
||||||
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
|
||||||
Leave blank to keep the current password unchanged
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -161,20 +123,6 @@ export default function SettingsSection({ settings, onUpdate }: SettingsSectionP
|
|||||||
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">Homepage Subtext</p>
|
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">Homepage Subtext</p>
|
||||||
<p className="text-base text-gray-900 dark:text-white">{settings.homepageSubtext}</p>
|
<p className="text-base text-gray-900 dark:text-white">{settings.homepageSubtext}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="pt-3 border-t border-gray-200 dark:border-gray-700">
|
|
||||||
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">Password Lock</p>
|
|
||||||
<p className="text-base text-gray-900 dark:text-white">
|
|
||||||
{settings.passwordLockEnabled ? (
|
|
||||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-base font-medium bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200">
|
|
||||||
Enabled
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-base font-medium bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300">
|
|
||||||
Disabled
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
45
components/guest-guard.tsx
Normal file
45
components/guest-guard.tsx
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
import { authApi } from '@/lib/api';
|
||||||
|
|
||||||
|
type Status = 'checking' | { kind: 'ok'; guestName: string } | 'denied';
|
||||||
|
|
||||||
|
export default function GuestGuard({ children }: { children: React.ReactNode }) {
|
||||||
|
const params = useSearchParams();
|
||||||
|
const [status, setStatus] = useState<Status>('checking');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
(async () => {
|
||||||
|
const usr = params.get('usr');
|
||||||
|
try {
|
||||||
|
if (usr) {
|
||||||
|
await authApi.session({ usr });
|
||||||
|
// user said leaving the token in URL is fine — do NOT strip
|
||||||
|
}
|
||||||
|
const who = await authApi.whoami();
|
||||||
|
if (cancelled) return;
|
||||||
|
if (who.role === 'admin' || who.role === 'guest') {
|
||||||
|
setStatus({ kind: 'ok', guestName: who.guest?.name ?? 'admin' });
|
||||||
|
} else {
|
||||||
|
setStatus('denied');
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) setStatus('denied');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [params]);
|
||||||
|
|
||||||
|
if (status === 'checking') return <div className="min-h-screen flex items-center justify-center text-gray-500">Verificando convite…</div>;
|
||||||
|
if (status === 'denied') return <div className="min-h-screen flex items-center justify-center text-center px-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold mb-2">Convite necessário</h1>
|
||||||
|
<p className="text-gray-500">Esta lista é por convite. Use o link que recebeu.</p>
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useAuth } from '@/lib/auth-context';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { authApi } from '@/lib/api';
|
||||||
|
|
||||||
interface HeaderProps {
|
interface HeaderProps {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -11,11 +12,24 @@ interface HeaderProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function Header({ title, subtitle, imageUrl, actions, maxWidth = 'max-w-7xl' }: HeaderProps) {
|
export default function Header({ title, subtitle, imageUrl, actions, maxWidth = 'max-w-7xl' }: HeaderProps) {
|
||||||
const { isAuthenticated } = useAuth();
|
const [isAdmin, setIsAdmin] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const who = await authApi.whoami();
|
||||||
|
if (!cancelled) setIsAdmin(who.role === 'admin');
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) setIsAdmin(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{isAuthenticated && (
|
{isAdmin && (
|
||||||
<div className="sticky top-0 z-50 bg-amber-50 dark:bg-amber-900/40 border-b border-amber-200/70 dark:border-amber-800/60 backdrop-blur">
|
<div className="sticky top-0 z-50 bg-amber-50 dark:bg-amber-900/40 border-b border-amber-200/70 dark:border-amber-800/60 backdrop-blur">
|
||||||
<div className={`${maxWidth} mx-auto py-3 px-4 sm:px-6 lg:px-8`}>
|
<div className={`${maxWidth} mx-auto py-3 px-4 sm:px-6 lg:px-8`}>
|
||||||
<p className="text-center text-sm text-amber-900 dark:text-amber-100">
|
<p className="text-center text-sm text-amber-900 dark:text-amber-100">
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { useRouter, usePathname } from 'next/navigation';
|
|
||||||
|
|
||||||
export default function PasswordLockGuard({ children }: { children: React.ReactNode }) {
|
|
||||||
const router = useRouter();
|
|
||||||
const pathname = usePathname();
|
|
||||||
const [isChecking, setIsChecking] = useState(true);
|
|
||||||
const [isLocked, setIsLocked] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
// Skip check for admin and lock pages
|
|
||||||
if (pathname.startsWith('/admin') || pathname === '/lock') {
|
|
||||||
setIsChecking(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkPasswordLock = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/settings');
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (data.success && data.settings.passwordLockEnabled) {
|
|
||||||
setIsLocked(true);
|
|
||||||
// Redirect to lock page
|
|
||||||
router.push('/lock');
|
|
||||||
} else {
|
|
||||||
setIsChecking(false);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error checking password lock:', error);
|
|
||||||
// On error, allow access to prevent site lockout
|
|
||||||
setIsChecking(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
checkPasswordLock();
|
|
||||||
}, [pathname, router]);
|
|
||||||
|
|
||||||
// Show loading or nothing while checking
|
|
||||||
if (isChecking) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">Loading...</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// If locked, don't render children (redirect is happening)
|
|
||||||
if (isLocked) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return <>{children}</>;
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useAuth } from '@/lib/auth-context';
|
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
import { useEffect } from 'react';
|
|
||||||
|
|
||||||
export default function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
|
||||||
const { isAuthenticated, isLoading } = useAuth();
|
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isLoading && !isAuthenticated) {
|
|
||||||
router.push('/admin/login');
|
|
||||||
}
|
|
||||||
}, [isAuthenticated, isLoading, router]);
|
|
||||||
|
|
||||||
if (isLoading) {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen flex items-center justify-center">
|
|
||||||
<div className="text-gray-600">Loading...</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isAuthenticated) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return <>{children}</>;
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
|
||||||
import { authApi } from './api';
|
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
|
|
||||||
interface AuthContextType {
|
|
||||||
isAuthenticated: boolean;
|
|
||||||
isLoading: boolean;
|
|
||||||
username: string | null;
|
|
||||||
login: (username: string, password: string) => Promise<void>;
|
|
||||||
logout: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
||||||
|
|
||||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
||||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
|
||||||
const [username, setUsername] = useState<string | null>(null);
|
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
// Check authentication on mount using httpOnly cookies
|
|
||||||
useEffect(() => {
|
|
||||||
const initAuth = async () => {
|
|
||||||
try {
|
|
||||||
// Call /api/auth/me - cookies are sent automatically
|
|
||||||
const user = await authApi.me();
|
|
||||||
setIsAuthenticated(true);
|
|
||||||
setUsername(user.username);
|
|
||||||
} catch (error) {
|
|
||||||
// Not authenticated or session expired
|
|
||||||
setIsAuthenticated(false);
|
|
||||||
setUsername(null);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
initAuth();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const login = async (username: string, password: string) => {
|
|
||||||
// Server sets httpOnly cookies automatically
|
|
||||||
await authApi.login(username, password);
|
|
||||||
setIsAuthenticated(true);
|
|
||||||
setUsername(username);
|
|
||||||
};
|
|
||||||
|
|
||||||
const logout = async () => {
|
|
||||||
try {
|
|
||||||
// Server clears httpOnly cookies
|
|
||||||
await authApi.logout();
|
|
||||||
} catch (error) {
|
|
||||||
// Continue with logout even if API call fails
|
|
||||||
}
|
|
||||||
setIsAuthenticated(false);
|
|
||||||
setUsername(null);
|
|
||||||
router.push('/');
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AuthContext.Provider
|
|
||||||
value={{
|
|
||||||
isAuthenticated,
|
|
||||||
isLoading,
|
|
||||||
username,
|
|
||||||
login,
|
|
||||||
logout,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</AuthContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useAuth() {
|
|
||||||
const context = useContext(AuthContext);
|
|
||||||
if (context === undefined) {
|
|
||||||
throw new Error('useAuth must be used within an AuthProvider');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
@@ -1,143 +0,0 @@
|
|||||||
import jwt from 'jsonwebtoken';
|
|
||||||
import crypto from 'crypto';
|
|
||||||
import fs from 'fs';
|
|
||||||
import path from 'path';
|
|
||||||
|
|
||||||
// Initialize secrets (auto-generate if not provided)
|
|
||||||
const secrets = initializeSecrets();
|
|
||||||
|
|
||||||
// Token expiry times
|
|
||||||
const TOKEN_EXPIRY = '72h';
|
|
||||||
const REFRESH_TOKEN_EXPIRY = '30d';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initialize JWT secrets - auto-generate and persist if not provided in environment
|
|
||||||
*/
|
|
||||||
function initializeSecrets(): { secret: string; refreshSecret: string } {
|
|
||||||
const dataDir = path.join(process.cwd(), 'data');
|
|
||||||
const secretsFile = path.join(dataDir, 'secrets.json');
|
|
||||||
|
|
||||||
// If provided in environment, use those
|
|
||||||
if (process.env.SECRET) {
|
|
||||||
return {
|
|
||||||
secret: process.env.SECRET,
|
|
||||||
refreshSecret: process.env.REFRESH_SECRET || process.env.SECRET, // Use same secret if refresh not provided
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure data directory exists
|
|
||||||
if (!fs.existsSync(dataDir)) {
|
|
||||||
fs.mkdirSync(dataDir, { recursive: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to load existing secrets
|
|
||||||
if (fs.existsSync(secretsFile)) {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(fs.readFileSync(secretsFile, 'utf-8'));
|
|
||||||
return data;
|
|
||||||
} catch {
|
|
||||||
// Failed to load, will generate new ones
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate new cryptographically secure secrets (512 bits each)
|
|
||||||
const newSecrets = {
|
|
||||||
secret: crypto.randomBytes(64).toString('hex'),
|
|
||||||
refreshSecret: crypto.randomBytes(64).toString('hex'),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Save to file with restricted permissions
|
|
||||||
try {
|
|
||||||
fs.writeFileSync(secretsFile, JSON.stringify(newSecrets, null, 2), { mode: 0o600 });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('⚠️ Failed to save secrets file:', error);
|
|
||||||
console.error('⚠️ WARNING: Using in-memory secrets - tokens will be invalid after restart!');
|
|
||||||
}
|
|
||||||
|
|
||||||
return newSecrets;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TokenPayload {
|
|
||||||
username: string;
|
|
||||||
type: 'access' | 'refresh';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate an access token
|
|
||||||
*/
|
|
||||||
export function generateAccessToken(username: string): string {
|
|
||||||
return jwt.sign(
|
|
||||||
{ username, type: 'access' } as TokenPayload,
|
|
||||||
secrets.secret,
|
|
||||||
{ expiresIn: TOKEN_EXPIRY } as jwt.SignOptions
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate a refresh token
|
|
||||||
*/
|
|
||||||
export function generateRefreshToken(username: string): string {
|
|
||||||
return jwt.sign(
|
|
||||||
{ username, type: 'refresh' } as TokenPayload,
|
|
||||||
secrets.refreshSecret,
|
|
||||||
{ expiresIn: REFRESH_TOKEN_EXPIRY } as jwt.SignOptions
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verify an access token
|
|
||||||
*/
|
|
||||||
export function verifyAccessToken(token: string): TokenPayload | null {
|
|
||||||
try {
|
|
||||||
const payload = jwt.verify(token, secrets.secret) as TokenPayload;
|
|
||||||
if (payload.type !== 'access') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return payload;
|
|
||||||
} catch (error) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verify a refresh token
|
|
||||||
*/
|
|
||||||
export function verifyRefreshToken(token: string): TokenPayload | null {
|
|
||||||
try {
|
|
||||||
const payload = jwt.verify(token, secrets.refreshSecret) as TokenPayload;
|
|
||||||
if (payload.type !== 'refresh') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return payload;
|
|
||||||
} catch (error) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate admin credentials against environment variables
|
|
||||||
*/
|
|
||||||
export function validateAdminCredentials(username: string, password: string): boolean {
|
|
||||||
const adminUsername = process.env.ADMIN_USERNAME || 'admin';
|
|
||||||
const adminPassword = process.env.ADMIN_PASSWORD;
|
|
||||||
|
|
||||||
if (!adminPassword) {
|
|
||||||
console.error('❌ ADMIN_PASSWORD not set in environment variables');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return username === adminUsername && password === adminPassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isSecureCookie(request: { headers: { get(name: string): string | null }; url: string }): boolean {
|
|
||||||
if (process.env.COOKIE_SECURE !== undefined) {
|
|
||||||
return process.env.COOKIE_SECURE === 'true';
|
|
||||||
}
|
|
||||||
if (process.env.NODE_ENV === 'production') {
|
|
||||||
return (
|
|
||||||
request.headers.get('x-forwarded-proto') === 'https' ||
|
|
||||||
request.url.startsWith('https://')
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user