Add password-based auth with JWT and remember-me
This commit is contained in:
1 parent
89deb869ab
commit
0042e7150c
10 files changed
+280
-36
No files matched your search
@@ -0,0 +1,43 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const configService = require('../services/configService');
|
||||
|
||||
class AuthController {
|
||||
login(req, res) {
|
||||
const { password, remember } = req.body;
|
||||
const settings = configService.getSettings();
|
||||
const authPassword = settings.authPassword;
|
||||
const jwtSecret = settings.jwtSecret || 'showy-default-secret';
|
||||
|
||||
if (!authPassword) {
|
||||
return res.status(500).json({ error: 'Auth password not configured' });
|
||||
}
|
||||
|
||||
if (password !== authPassword) {
|
||||
return res.status(401).json({ error: 'Invalid password' });
|
||||
}
|
||||
|
||||
const expiresIn = remember ? '3650d' : '24h';
|
||||
const token = jwt.sign({ authed: true }, jwtSecret, { expiresIn });
|
||||
|
||||
res.json({ token, expiresIn });
|
||||
}
|
||||
|
||||
verify(req, res) {
|
||||
const auth = req.headers.authorization;
|
||||
if (!auth || !auth.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ valid: false });
|
||||
}
|
||||
|
||||
const settings = configService.getSettings();
|
||||
const jwtSecret = settings.jwtSecret || 'showy-default-secret';
|
||||
|
||||
try {
|
||||
jwt.verify(auth.slice(7), jwtSecret);
|
||||
res.json({ valid: true });
|
||||
} catch {
|
||||
res.status(401).json({ valid: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AuthController();
|
||||
@@ -0,0 +1,8 @@
|
||||
const express = require('express');
|
||||
const authRouter = express.Router();
|
||||
const authController = require('../controllers/authController');
|
||||
|
||||
authRouter.post('/login', authController.login);
|
||||
authRouter.get('/verify', authController.verify);
|
||||
|
||||
module.exports = authRouter;
|
||||
+31
-29
@@ -1,35 +1,37 @@
|
||||
const express = require("express");
|
||||
const collectionRouter = require("./collection.routes");
|
||||
const entrySeenRouter = require("./entry-seen.routes");
|
||||
const entryRouter = require("./entry.routes");
|
||||
const seasonRouter = require("./season.routes");
|
||||
const episodeSeenRouter = require("./episode-seen.routes");
|
||||
const settingsRouter = require("./settings.routes");
|
||||
const maintenanceRouter = require("./maintenance.routes");
|
||||
const statisticsRouter = require("./statistics.routes");
|
||||
const mediaRouter = require("./media.routes");
|
||||
const episodeRouter = require("./episode.routes");
|
||||
const pingRouter = require("./ping.routes");
|
||||
const importRouter = require("./import.routes");
|
||||
const peopleRouter = require("./people.routes");
|
||||
const aiQueryRouter = require("./ai-query.routes");
|
||||
const express = require('express');
|
||||
const collectionRouter = require('./collection.routes');
|
||||
const entrySeenRouter = require('./entry-seen.routes');
|
||||
const entryRouter = require('./entry.routes');
|
||||
const seasonRouter = require('./season.routes');
|
||||
const episodeSeenRouter = require('./episode-seen.routes');
|
||||
const settingsRouter = require('./settings.routes');
|
||||
const maintenanceRouter = require('./maintenance.routes');
|
||||
const statisticsRouter = require('./statistics.routes');
|
||||
const mediaRouter = require('./media.routes');
|
||||
const episodeRouter = require('./episode.routes');
|
||||
const pingRouter = require('./ping.routes');
|
||||
const importRouter = require('./import.routes');
|
||||
const peopleRouter = require('./people.routes');
|
||||
const aiQueryRouter = require('./ai-query.routes');
|
||||
const authRouter = require('./auth.routes');
|
||||
|
||||
const router = express.Router();
|
||||
router.use("/media", mediaRouter);
|
||||
router.use("/entries", entryRouter);
|
||||
router.use("/collections", collectionRouter);
|
||||
router.use("/entry-seen", entrySeenRouter);
|
||||
router.use('/auth', authRouter);
|
||||
router.use('/media', mediaRouter);
|
||||
router.use('/entries', entryRouter);
|
||||
router.use('/collections', collectionRouter);
|
||||
router.use('/entry-seen', entrySeenRouter);
|
||||
|
||||
router.use("/seasons", seasonRouter);
|
||||
router.use("/episodes", episodeRouter);
|
||||
router.use("/episode-seen", episodeSeenRouter);
|
||||
router.use('/seasons', seasonRouter);
|
||||
router.use('/episodes', episodeRouter);
|
||||
router.use('/episode-seen', episodeSeenRouter);
|
||||
|
||||
router.use("/import", importRouter);
|
||||
router.use("/statistics", statisticsRouter);
|
||||
router.use("/settings", settingsRouter);
|
||||
router.use("/maintenance", maintenanceRouter);
|
||||
router.use("/ping", pingRouter);
|
||||
router.use("/people", peopleRouter);
|
||||
router.use("/ai-query", aiQueryRouter);
|
||||
router.use('/import', importRouter);
|
||||
router.use('/statistics', statisticsRouter);
|
||||
router.use('/settings', settingsRouter);
|
||||
router.use('/maintenance', maintenanceRouter);
|
||||
router.use('/ping', pingRouter);
|
||||
router.use('/people', peopleRouter);
|
||||
router.use('/ai-query', aiQueryRouter);
|
||||
|
||||
module.exports = router;
|
||||
@@ -10,5 +10,8 @@
|
||||
"watchlistViewMode": "grid",
|
||||
"CollectionsViewMode": "",
|
||||
"CollectionItemsViewMode": "",
|
||||
"favoritsViewMode": ""
|
||||
"episodesViewMode": "grid-2",
|
||||
"favoritsViewMode": "",
|
||||
"authPassword": "",
|
||||
"jwtSecret": "change-me-to-a-random-string"
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
import { RouterProvider } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { router } from "./router";
|
||||
import { RouterProvider } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { useEffect } from 'react';
|
||||
import { useAuthStore } from '@/stores/useAuthStore';
|
||||
import { LoginPage } from '@/pages/LoginPage';
|
||||
import { router } from './router';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -15,6 +19,24 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
export function App() {
|
||||
const { isAuthenticated, isChecking, checkAuth } = useAuthStore();
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
if (isChecking) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <LoginPage />;
|
||||
}
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TooltipProvider>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
export const authApi = {
|
||||
login: (password: string, remember: boolean) =>
|
||||
api
|
||||
.post<{ token: string; expiresIn: string }>('/auth/login', {
|
||||
password,
|
||||
remember,
|
||||
})
|
||||
.then((r) => r.data),
|
||||
|
||||
verify: (token: string) =>
|
||||
api
|
||||
.get<{ valid: boolean }>('/auth/verify', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useState } from 'react';
|
||||
import { useAuthStore } from '@/stores/useAuthStore';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Loader2, Lock } from 'lucide-react';
|
||||
|
||||
export function LoginPage() {
|
||||
const [password, setPassword] = useState('');
|
||||
const [remember, setRemember] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const login = useAuthStore((s) => s.login);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!password.trim()) return;
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(password, remember);
|
||||
} catch {
|
||||
setError('Invalid password');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
<div className="w-full max-w-sm space-y-6 rounded-xl border border-border bg-card p-8 shadow-lg">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
|
||||
<Lock className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-xl font-bold">Showy</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Enter your password to continue
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={remember}
|
||||
onCheckedChange={setRemember}
|
||||
id="remember"
|
||||
/>
|
||||
<Label htmlFor="remember" className="text-sm cursor-pointer">
|
||||
Remember me
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-destructive text-center">{error}</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Unlock
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import type { Settings } from '@/types';
|
||||
const settingsSchema = z.object({
|
||||
tmdbApiKey: z.string().min(1, 'TMDB API key is required'),
|
||||
backPort: z.coerce.number().int().positive(),
|
||||
authPassword: z.string().optional(),
|
||||
});
|
||||
|
||||
function formatOrphanResult(result: OrphanResult): string {
|
||||
@@ -258,7 +259,11 @@ export function SettingsPage() {
|
||||
} = useForm({
|
||||
resolver: zodResolver(settingsSchema),
|
||||
values: settings
|
||||
? { tmdbApiKey: settings.tmdbApiKey, backPort: settings.backPort }
|
||||
? {
|
||||
tmdbApiKey: settings.tmdbApiKey,
|
||||
backPort: settings.backPort,
|
||||
authPassword: settings.authPassword || '',
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
@@ -320,6 +325,16 @@ export function SettingsPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="authPassword">Auth Password</Label>
|
||||
<Input
|
||||
id="authPassword"
|
||||
type="password"
|
||||
{...register('authPassword')}
|
||||
placeholder="Leave empty to disable"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!isDirty || updateSettings.isPending}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
import { authApi } from '@/api/auth';
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
isChecking: boolean;
|
||||
isAuthenticated: boolean;
|
||||
|
||||
login: (password: string, remember: boolean) => Promise<void>;
|
||||
logout: () => void;
|
||||
checkAuth: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
token: null,
|
||||
isChecking: true,
|
||||
isAuthenticated: false,
|
||||
|
||||
login: async (password, remember) => {
|
||||
const { token } = await authApi.login(password, remember);
|
||||
set({ token, isAuthenticated: true });
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
set({ token: null, isAuthenticated: false });
|
||||
},
|
||||
|
||||
checkAuth: async () => {
|
||||
const { token } = get();
|
||||
if (!token) {
|
||||
set({ isChecking: false, isAuthenticated: false });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await authApi.verify(token);
|
||||
set({ isChecking: false, isAuthenticated: true });
|
||||
} catch {
|
||||
set({ token: null, isChecking: false, isAuthenticated: false });
|
||||
}
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'showy-auth',
|
||||
partialize: (state) => ({ token: state.token }),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -204,6 +204,8 @@ export interface Settings {
|
||||
CollectionsViewMode: string;
|
||||
CollectionItemsViewMode: string;
|
||||
favoritsViewMode: string;
|
||||
authPassword?: string;
|
||||
jwtSecret?: string;
|
||||
}
|
||||
|
||||
export interface Statistics {
|
||||
|
||||
Reference in new issue
Block a user