build auth modal
This commit is contained in:
@@ -6,3 +6,7 @@ PORT=3000
|
||||
|
||||
# Data directory inside the container (default: /data)
|
||||
DATA_DIR=/data
|
||||
|
||||
# Admin credentials for upload/edit/delete access (REQUIRED — change before deploying)
|
||||
ADMIN_USER=admin
|
||||
ADMIN_PASS=changeme
|
||||
|
||||
13
UNRAID.md
13
UNRAID.md
@@ -71,15 +71,18 @@ Add two path mappings (click **Add another Path** → select **Path** for each):
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Add three variables (click **Add another Path** → select **Variable** for each):
|
||||
Add five variables (click **Add another Path** → select **Variable** for each):
|
||||
|
||||
| Config Type | Name | Key | Value |
|
||||
|---|---|---|---|
|
||||
| Variable | Public URL | `PUBLIC_URL` | `https://meme.alwisp.com` |
|
||||
| Variable | Port | `PORT` | `3000` |
|
||||
| Variable | Data Dir | `DATA_DIR` | `/data` |
|
||||
| Variable | Admin Username | `ADMIN_USER` | `admin` |
|
||||
| Variable | Admin Password | `ADMIN_PASS` | *(your password)* |
|
||||
|
||||
> `PUBLIC_URL` is what gets embedded in share links (copy link, Telegram, SMS). Set it to your actual external URL.
|
||||
> `PUBLIC_URL` is what gets embedded in share links. Set it to your actual external URL.
|
||||
> `ADMIN_PASS` is **required** — the gallery is publicly viewable but upload/edit/delete require this password. Change it before exposing the container to the internet.
|
||||
|
||||
3. Click **Apply**. Unraid will pull/start the container.
|
||||
4. Check the container log (click the container name → **Log**) — you should see:
|
||||
@@ -115,6 +118,8 @@ docker run -d \
|
||||
-e PUBLIC_URL="https://meme.alwisp.com" \
|
||||
-e PORT="3000" \
|
||||
-e DATA_DIR="/data" \
|
||||
-e ADMIN_USER="admin" \
|
||||
-e ADMIN_PASS="yourpassword" \
|
||||
memer:latest
|
||||
```
|
||||
|
||||
@@ -174,6 +179,8 @@ docker run -d \
|
||||
-e PUBLIC_URL="https://meme.alwisp.com" \
|
||||
-e PORT="3000" \
|
||||
-e DATA_DIR="/data" \
|
||||
-e ADMIN_USER="admin" \
|
||||
-e ADMIN_PASS="yourpassword" \
|
||||
memer:latest
|
||||
```
|
||||
|
||||
@@ -206,3 +213,5 @@ The SQLite database file is `/mnt/user/appdata/memer/db/memer.db`. Image files a
|
||||
| `PUBLIC_URL` | `http://localhost:3000` | External URL embedded in share links — must match your domain |
|
||||
| `PORT` | `3000` | Port the Node server listens on inside the container |
|
||||
| `DATA_DIR` | `/data` | Root path for images and DB inside the container — do not change unless remapping volumes |
|
||||
| `ADMIN_USER` | `admin` | Username for admin login |
|
||||
| `ADMIN_PASS` | *(none)* | Password for admin login — **required**, set before exposing to the internet |
|
||||
|
||||
73
backend/src/auth.ts
Normal file
73
backend/src/auth.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import crypto from 'crypto';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
|
||||
const COOKIE_NAME = 'memer_session';
|
||||
const TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
|
||||
function secret(): string {
|
||||
const pass = process.env.ADMIN_PASS;
|
||||
if (!pass) throw new Error('ADMIN_PASS environment variable is not set');
|
||||
return pass;
|
||||
}
|
||||
|
||||
function b64url(str: string): string {
|
||||
return Buffer.from(str).toString('base64url');
|
||||
}
|
||||
|
||||
function fromB64url(str: string): string {
|
||||
return Buffer.from(str, 'base64url').toString('utf8');
|
||||
}
|
||||
|
||||
export function createToken(user: string): string {
|
||||
const payload = b64url(JSON.stringify({ user, exp: Date.now() + TOKEN_TTL_MS }));
|
||||
const sig = crypto.createHmac('sha256', secret()).update(payload).digest('hex');
|
||||
return `${payload}.${sig}`;
|
||||
}
|
||||
|
||||
export function verifyToken(token: string): { user: string } | null {
|
||||
try {
|
||||
const dot = token.lastIndexOf('.');
|
||||
if (dot === -1) return null;
|
||||
const payload = token.slice(0, dot);
|
||||
const sig = token.slice(dot + 1);
|
||||
const expected = crypto.createHmac('sha256', secret()).update(payload).digest('hex');
|
||||
if (!crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'))) return null;
|
||||
const data = JSON.parse(fromB64url(payload)) as { user: string; exp: number };
|
||||
if (Date.now() > data.exp) return null;
|
||||
return { user: data.user };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getTokenFromRequest(req: FastifyRequest): string | null {
|
||||
const raw = req.headers.cookie ?? '';
|
||||
for (const part of raw.split(';')) {
|
||||
const [key, ...rest] = part.trim().split('=');
|
||||
if (key === COOKIE_NAME) return rest.join('=');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function setSessionCookie(reply: FastifyReply, token: string): void {
|
||||
const secure = (process.env.PUBLIC_URL ?? '').startsWith('https');
|
||||
const maxAge = Math.floor(TOKEN_TTL_MS / 1000);
|
||||
reply.header(
|
||||
'Set-Cookie',
|
||||
`${COOKIE_NAME}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${secure ? '; Secure' : ''}`
|
||||
);
|
||||
}
|
||||
|
||||
export function clearSessionCookie(reply: FastifyReply): void {
|
||||
reply.header(
|
||||
'Set-Cookie',
|
||||
`${COOKIE_NAME}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`
|
||||
);
|
||||
}
|
||||
|
||||
export async function requireAuth(req: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
const token = getTokenFromRequest(req);
|
||||
if (!token || !verifyToken(token)) {
|
||||
await reply.status(401).send({ error: 'Unauthorized' });
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'url';
|
||||
import { ensureImagesDir, IMAGES_DIR } from './services/storage.js';
|
||||
import { memesRoutes } from './routes/memes.js';
|
||||
import { tagsRoutes } from './routes/tags.js';
|
||||
import { authRoutes } from './routes/auth.js';
|
||||
|
||||
// Ensure data dirs exist
|
||||
ensureImagesDir();
|
||||
@@ -35,6 +36,7 @@ await app.register(fastifyStatic, {
|
||||
});
|
||||
|
||||
// API routes
|
||||
await app.register(authRoutes);
|
||||
await app.register(memesRoutes);
|
||||
await app.register(tagsRoutes);
|
||||
|
||||
|
||||
35
backend/src/routes/auth.ts
Normal file
35
backend/src/routes/auth.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { createToken, verifyToken, getTokenFromRequest, setSessionCookie, clearSessionCookie } from '../auth.js';
|
||||
|
||||
export async function authRoutes(app: FastifyInstance) {
|
||||
app.post<{ Body: { username: string; password: string } }>('/api/auth/login', async (req, reply) => {
|
||||
const { username, password } = req.body ?? {};
|
||||
|
||||
const adminUser = process.env.ADMIN_USER ?? 'admin';
|
||||
const adminPass = process.env.ADMIN_PASS;
|
||||
|
||||
if (!adminPass) {
|
||||
return reply.status(500).send({ error: 'Server auth is not configured (ADMIN_PASS missing)' });
|
||||
}
|
||||
|
||||
if (username !== adminUser || password !== adminPass) {
|
||||
return reply.status(401).send({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
const token = createToken(username);
|
||||
setSessionCookie(reply, token);
|
||||
return { ok: true, user: username };
|
||||
});
|
||||
|
||||
app.post('/api/auth/logout', async (_req, reply) => {
|
||||
clearSessionCookie(reply);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
app.get('/api/auth/me', async (req) => {
|
||||
const token = getTokenFromRequest(req);
|
||||
const payload = token ? verifyToken(token) : null;
|
||||
if (!payload) return { authenticated: false };
|
||||
return { authenticated: true, user: payload.user };
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { v4 as uuidv4 } from 'uuid';
|
||||
import db from '../db.js';
|
||||
import { buildFilePath, deleteFile, getExtension } from '../services/storage.js';
|
||||
import { extractMeta, resizeImage, saveBuffer } from '../services/image.js';
|
||||
import { requireAuth } from '../auth.js';
|
||||
import type { ListQuery, UpdateBody, RescaleBody, Meme } from '../types.js';
|
||||
|
||||
const ALLOWED_MIMES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
|
||||
@@ -117,7 +118,7 @@ export async function memesRoutes(app: FastifyInstance) {
|
||||
});
|
||||
|
||||
// Upload meme
|
||||
app.post('/api/memes', async (req, reply) => {
|
||||
app.post('/api/memes', { preHandler: requireAuth }, async (req, reply) => {
|
||||
const data = await req.file();
|
||||
if (!data) return reply.status(400).send({ error: 'No file uploaded' });
|
||||
|
||||
@@ -155,7 +156,7 @@ export async function memesRoutes(app: FastifyInstance) {
|
||||
});
|
||||
|
||||
// Update meme metadata
|
||||
app.put<{ Params: { id: string }; Body: UpdateBody }>('/api/memes/:id', async (req, reply) => {
|
||||
app.put<{ Params: { id: string }; Body: UpdateBody }>('/api/memes/:id', { preHandler: requireAuth }, async (req, reply) => {
|
||||
const meme = getMemeById(req.params.id);
|
||||
if (!meme) return reply.status(404).send({ error: 'Not found' });
|
||||
|
||||
@@ -173,7 +174,7 @@ export async function memesRoutes(app: FastifyInstance) {
|
||||
});
|
||||
|
||||
// Delete meme (children cascade)
|
||||
app.delete<{ Params: { id: string } }>('/api/memes/:id', async (req, reply) => {
|
||||
app.delete<{ Params: { id: string } }>('/api/memes/:id', { preHandler: requireAuth }, async (req, reply) => {
|
||||
const meme = getMemeById(req.params.id);
|
||||
if (!meme) return reply.status(404).send({ error: 'Not found' });
|
||||
|
||||
@@ -194,6 +195,7 @@ export async function memesRoutes(app: FastifyInstance) {
|
||||
// Non-destructive rescale
|
||||
app.post<{ Params: { id: string }; Body: RescaleBody }>(
|
||||
'/api/memes/:id/rescale',
|
||||
{ preHandler: requireAuth },
|
||||
async (req, reply) => {
|
||||
const parent = getMemeById(req.params.id);
|
||||
if (!parent) return reply.status(404).send({ error: 'Not found' });
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import db from '../db.js';
|
||||
import { requireAuth } from '../auth.js';
|
||||
|
||||
export async function tagsRoutes(app: FastifyInstance) {
|
||||
app.get('/api/tags', async () => {
|
||||
@@ -34,7 +35,7 @@ export async function tagsRoutes(app: FastifyInstance) {
|
||||
}
|
||||
});
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/api/tags/:id', async (req, reply) => {
|
||||
app.delete<{ Params: { id: string } }>('/api/tags/:id', { preHandler: requireAuth }, async (req, reply) => {
|
||||
const id = Number(req.params.id);
|
||||
if (!id) return reply.status(400).send({ error: 'Invalid tag id' });
|
||||
db.prepare('DELETE FROM tags WHERE id = ?').run(id);
|
||||
|
||||
@@ -13,6 +13,8 @@ services:
|
||||
PORT: "3000"
|
||||
DATA_DIR: /data
|
||||
PUBLIC_URL: ${PUBLIC_URL:-http://localhost:3000}
|
||||
ADMIN_USER: ${ADMIN_USER:-admin}
|
||||
ADMIN_PASS: ${ADMIN_PASS:-changeme}
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:3000/api/tags"]
|
||||
interval: 30s
|
||||
|
||||
87
frontend/src/components/LoginModal.tsx
Normal file
87
frontend/src/components/LoginModal.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { X, Lock, LogIn } from 'lucide-react';
|
||||
import { useLogin } from '../hooks/useAuth';
|
||||
|
||||
interface Props {
|
||||
onClose: () => void;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
export function LoginModal({ onClose, onSuccess }: Props) {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const login = useLogin();
|
||||
const userRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
userRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
await login.mutateAsync({ username, password });
|
||||
onSuccess?.();
|
||||
onClose();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 animate-fade-in">
|
||||
<div className="bg-zinc-900 rounded-2xl shadow-2xl w-full max-w-sm border border-zinc-800 animate-scale-in">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-5 border-b border-zinc-800">
|
||||
<div className="flex items-center gap-2">
|
||||
<Lock size={16} className="text-accent" />
|
||||
<h2 className="text-base font-semibold">Admin Login</h2>
|
||||
</div>
|
||||
<button onClick={onClose} className="text-zinc-500 hover:text-zinc-300 transition-colors">
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-5 space-y-4">
|
||||
<p className="text-sm text-zinc-500">
|
||||
Sign in to upload, edit, and manage memes.
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs text-zinc-500 mb-1">Username</label>
|
||||
<input
|
||||
ref={userRef}
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
required
|
||||
className="w-full bg-zinc-800 border border-zinc-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-accent"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs text-zinc-500 mb-1">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="w-full bg-zinc-800 border border-zinc-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-accent"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{login.error && (
|
||||
<p className="text-red-400 text-sm">{(login.error as Error).message}</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!username || !password || login.isPending}
|
||||
className="w-full flex items-center justify-center gap-2 py-2.5 rounded-lg bg-accent hover:bg-accent-hover text-white text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<LogIn size={15} />
|
||||
{login.isPending ? 'Signing in…' : 'Sign In'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { X, Minimize2, Trash2, Edit2, Check, Layers } from 'lucide-react';
|
||||
import { useMeme, useDeleteMeme, useUpdateMeme } from '../hooks/useMemes';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { SharePanel } from './SharePanel';
|
||||
import { RescaleModal } from './RescaleModal';
|
||||
import { api, type Meme } from '../api/client';
|
||||
@@ -26,6 +27,8 @@ export function MemeDetail({ memeId, onClose }: Props) {
|
||||
const { data, isLoading, refetch } = useMeme(memeId);
|
||||
const deleteMeme = useDeleteMeme();
|
||||
const updateMeme = useUpdateMeme();
|
||||
const { data: auth } = useAuth();
|
||||
const isAdmin = auth?.authenticated === true;
|
||||
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [editTitle, setEditTitle] = useState('');
|
||||
@@ -94,24 +97,26 @@ export function MemeDetail({ memeId, onClose }: Props) {
|
||||
<h2 className="text-lg font-semibold truncate flex-1 mr-3">{meme.title}</h2>
|
||||
)}
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{editing ? (
|
||||
<button
|
||||
onClick={saveEdit}
|
||||
disabled={updateMeme.isPending}
|
||||
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg bg-accent hover:bg-accent-hover text-white transition-colors"
|
||||
>
|
||||
<Check size={14} /> Save
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={startEdit}
|
||||
className="text-zinc-500 hover:text-zinc-300 transition-colors p-1"
|
||||
title="Edit"
|
||||
>
|
||||
<Edit2 size={16} />
|
||||
</button>
|
||||
{isAdmin && (
|
||||
editing ? (
|
||||
<button
|
||||
onClick={saveEdit}
|
||||
disabled={updateMeme.isPending}
|
||||
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg bg-accent hover:bg-accent-hover text-white transition-colors"
|
||||
>
|
||||
<Check size={14} /> Save
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={startEdit}
|
||||
className="text-zinc-500 hover:text-zinc-300 transition-colors p-1"
|
||||
title="Edit"
|
||||
>
|
||||
<Edit2 size={16} />
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
{!meme.parent_id && (
|
||||
{isAdmin && !meme.parent_id && (
|
||||
<button
|
||||
onClick={() => setShowRescale(true)}
|
||||
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-300 transition-colors"
|
||||
@@ -121,14 +126,16 @@ export function MemeDetail({ memeId, onClose }: Props) {
|
||||
<span className="hidden sm:inline">Rescale</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={deleteMeme.isPending}
|
||||
className="text-zinc-500 hover:text-red-400 transition-colors p-1"
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
{isAdmin && (
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={deleteMeme.isPending}
|
||||
className="text-zinc-500 hover:text-red-400 transition-colors p-1"
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
)}
|
||||
<button onClick={onClose} className="text-zinc-500 hover:text-zinc-300 transition-colors p-1">
|
||||
<X size={20} />
|
||||
</button>
|
||||
@@ -164,7 +171,7 @@ export function MemeDetail({ memeId, onClose }: Props) {
|
||||
{/* Description */}
|
||||
<section>
|
||||
<h3 className="text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-2">Description</h3>
|
||||
{editing ? (
|
||||
{isAdmin && editing ? (
|
||||
<textarea
|
||||
value={editDesc}
|
||||
onChange={(e) => setEditDesc(e.target.value)}
|
||||
@@ -180,7 +187,7 @@ export function MemeDetail({ memeId, onClose }: Props) {
|
||||
{/* Tags */}
|
||||
<section>
|
||||
<h3 className="text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-2">Tags</h3>
|
||||
{editing ? (
|
||||
{isAdmin && editing ? (
|
||||
<input
|
||||
type="text"
|
||||
value={editTags}
|
||||
|
||||
52
frontend/src/hooks/useAuth.ts
Normal file
52
frontend/src/hooks/useAuth.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
interface AuthStatus {
|
||||
authenticated: boolean;
|
||||
user?: string;
|
||||
}
|
||||
|
||||
async function fetchMe(): Promise<AuthStatus> {
|
||||
const res = await fetch('/api/auth/me');
|
||||
return res.json() as Promise<AuthStatus>;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
return useQuery({
|
||||
queryKey: ['auth'],
|
||||
queryFn: fetchMe,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useLogin() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ username, password }: { username: string; password: string }) => {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: 'Login failed' }));
|
||||
throw new Error(err.error ?? 'Login failed');
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['auth'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useLogout() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['auth'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { Search, Upload as UploadIcon, X, Share2 } from 'lucide-react';
|
||||
import { Search, Upload as UploadIcon, X, Share2, Lock, LogOut } from 'lucide-react';
|
||||
import { useMemes, useTags } from '../hooks/useMemes';
|
||||
import { useAuth, useLogout } from '../hooks/useAuth';
|
||||
import { GalleryGrid } from '../components/GalleryGrid';
|
||||
import { MemeDetail } from '../components/MemeDetail';
|
||||
import { UploadModal } from '../components/UploadModal';
|
||||
import { LoginModal } from '../components/LoginModal';
|
||||
import { SharePanel } from '../components/SharePanel';
|
||||
import type { Meme } from '../api/client';
|
||||
|
||||
@@ -14,6 +16,11 @@ export function Gallery() {
|
||||
const [selectedMemeId, setSelectedMemeId] = useState<string | null>(null);
|
||||
const [quickShareMeme, setQuickShareMeme] = useState<Meme | null>(null);
|
||||
const [showUpload, setShowUpload] = useState(false);
|
||||
const [showLogin, setShowLogin] = useState(false);
|
||||
|
||||
const { data: auth } = useAuth();
|
||||
const logout = useLogout();
|
||||
const isAdmin = auth?.authenticated === true;
|
||||
|
||||
// Debounce search
|
||||
const [searchTimer, setSearchTimer] = useState<ReturnType<typeof setTimeout> | null>(null);
|
||||
@@ -40,6 +47,14 @@ export function Gallery() {
|
||||
setQuickShareMeme(meme);
|
||||
}, []);
|
||||
|
||||
function handleUploadClick() {
|
||||
if (isAdmin) {
|
||||
setShowUpload(true);
|
||||
} else {
|
||||
setShowLogin(true);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-zinc-950">
|
||||
{/* Topbar */}
|
||||
@@ -71,14 +86,37 @@ export function Gallery() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="ml-auto flex-shrink-0">
|
||||
{/* Right side actions */}
|
||||
<div className="ml-auto flex items-center gap-2 flex-shrink-0">
|
||||
{/* Upload button — always visible, gates on auth */}
|
||||
<button
|
||||
onClick={() => setShowUpload(true)}
|
||||
onClick={handleUploadClick}
|
||||
className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-accent hover:bg-accent-hover text-white text-sm font-medium transition-colors"
|
||||
title={isAdmin ? 'Upload meme' : 'Sign in to upload'}
|
||||
>
|
||||
<UploadIcon size={15} />
|
||||
<span className="hidden sm:inline">Upload</span>
|
||||
{isAdmin ? <UploadIcon size={15} /> : <Lock size={15} />}
|
||||
<span className="hidden sm:inline">{isAdmin ? 'Upload' : 'Upload'}</span>
|
||||
</button>
|
||||
|
||||
{/* Auth state */}
|
||||
{isAdmin ? (
|
||||
<button
|
||||
onClick={() => logout.mutate()}
|
||||
title={`Sign out (${auth?.user})`}
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-400 hover:text-zinc-200 text-sm transition-colors"
|
||||
>
|
||||
<LogOut size={15} />
|
||||
<span className="hidden sm:inline text-xs">{auth?.user}</span>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setShowLogin(true)}
|
||||
className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-400 hover:text-zinc-200 text-sm transition-colors"
|
||||
title="Admin login"
|
||||
>
|
||||
<Lock size={15} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -114,7 +152,6 @@ export function Gallery() {
|
||||
|
||||
{/* Gallery */}
|
||||
<main className="max-w-screen-2xl mx-auto px-4 py-6">
|
||||
{/* Status bar */}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<p className="text-sm text-zinc-500">
|
||||
{isLoading
|
||||
@@ -175,8 +212,16 @@ export function Gallery() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Upload modal */}
|
||||
{showUpload && <UploadModal onClose={() => setShowUpload(false)} />}
|
||||
{/* Upload modal (admin only) */}
|
||||
{showUpload && isAdmin && <UploadModal onClose={() => setShowUpload(false)} />}
|
||||
|
||||
{/* Login modal */}
|
||||
{showLogin && (
|
||||
<LoginModal
|
||||
onClose={() => setShowLogin(false)}
|
||||
onSuccess={() => setShowUpload(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user