Compare commits

...

3 Commits

Author SHA1 Message Date
ribardej
c21af2732e feat(backend): implemented self delete for users 2025-10-15 11:11:04 +02:00
ribardej
f208e73986 feat(frontend): added account and appearance tabs 2025-10-15 11:00:47 +02:00
ribardej
eb087e457c feat(frontend): improved and centered UI 2025-10-15 10:06:22 +02:00
7 changed files with 230 additions and 152 deletions

View File

@@ -1,10 +1,28 @@
from fastapi import APIRouter from fastapi import APIRouter, Depends, status
from fastapi_users import models
from fastapi_users.manager import BaseUserManager
from app.schemas.user import UserCreate, UserRead, UserUpdate from app.schemas.user import UserCreate, UserRead, UserUpdate
from app.services.user_service import auth_backend, fastapi_users from app.services.user_service import auth_backend, fastapi_users
router = APIRouter() router = APIRouter()
@router.delete(
"/users/me",
status_code=status.HTTP_204_NO_CONTENT,
tags=["users"],
summary="Delete current user",
response_description="The user has been successfully deleted.",
)
async def delete_me(
user: models.UserProtocol = Depends(fastapi_users.current_user(active=True)),
user_manager: BaseUserManager = Depends(fastapi_users.get_user_manager),
):
"""
Delete the currently authenticated user.
"""
await user_manager.delete(user)
# Keep existing paths as-is under /auth/* and /users/* # Keep existing paths as-is under /auth/* and /users/*
router.include_router( router.include_router(
fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"] fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]

View File

@@ -1,42 +1 @@
#root { /* App-level styles moved to ui.css for a cleaner layout. */
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View File

@@ -8,6 +8,18 @@ function App() {
const [hasToken, setHasToken] = useState<boolean>(!!localStorage.getItem('token')); const [hasToken, setHasToken] = useState<boolean>(!!localStorage.getItem('token'));
useEffect(() => { useEffect(() => {
// Handle OAuth callback: /oauth-callback?access_token=...&token_type=...
if (window.location.pathname === '/oauth-callback') {
const params = new URLSearchParams(window.location.search);
const token = params.get('access_token');
if (token) {
localStorage.setItem('token', token);
setHasToken(true);
}
// Clean URL and redirect to home
window.history.replaceState({}, '', '/');
}
const onStorage = (e: StorageEvent) => { const onStorage = (e: StorageEvent) => {
if (e.key === 'token') setHasToken(!!e.newValue); if (e.key === 'token') setHasToken(!!e.newValue);
}; };

View File

@@ -88,13 +88,56 @@ export async function createTransaction(input: CreateTransactionInput): Promise<
} }
export async function getTransactions(): Promise<Transaction[]> { export async function getTransactions(): Promise<Transaction[]> {
const res = await fetch(`${getBaseUrl()}/transactions/`, { const res = await fetch(`${getBaseUrl()}/transactions/`, {
headers: { 'Content-Type': 'application/json', ...authHeaders() }, headers: { 'Content-Type': 'application/json', ...authHeaders() },
}); });
if (!res.ok) throw new Error('Failed to load transactions'); if (!res.ok) throw new Error('Failed to load transactions');
return res.json(); return res.json();
} }
export type User = {
id: string;
email: string;
first_name?: string | null;
last_name?: string | null;
is_active: boolean;
is_superuser: boolean;
is_verified: boolean;
};
export async function getMe(): Promise<User> {
const res = await fetch(`${getBaseUrl()}/users/me`, {
headers: { 'Content-Type': 'application/json', ...authHeaders() },
});
if (!res.ok) throw new Error('Failed to load user');
return res.json();
}
export type UpdateMeInput = Partial<Pick<User, 'first_name' | 'last_name'>> & { password?: string };
export async function updateMe(input: UpdateMeInput): Promise<User> {
const res = await fetch(`${getBaseUrl()}/users/me`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...authHeaders() },
body: JSON.stringify(input),
});
if (!res.ok) {
const text = await res.text();
throw new Error(text || 'Failed to update user');
}
return res.json();
}
export async function deleteMe(): Promise<void> {
const res = await fetch(`${getBaseUrl()}/users/me`, {
method: 'DELETE',
headers: { ...authHeaders() },
});
if (!res.ok) {
const text = await res.text();
throw new Error(text || 'Failed to delete account');
}
}
export function logout() { export function logout() {
localStorage.removeItem('token'); localStorage.removeItem('token');
} }

View File

@@ -1,7 +1,11 @@
import { StrictMode } from 'react' import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import './index.css' import './index.css'
import './ui.css'
import App from './App.tsx' import App from './App.tsx'
import { applyAppearanceFromStorage } from './appearance'
applyAppearanceFromStorage()
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>

View File

@@ -1,11 +1,14 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { type Category, type Transaction, createTransaction, getCategories, getTransactions } from '../api'; import { type Category, type Transaction, createTransaction, getCategories, getTransactions } from '../api';
import AccountPage from './AccountPage';
import AppearancePage from './AppearancePage';
function formatAmount(n: number) { function formatAmount(n: number) {
return new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n); return new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n);
} }
export default function Dashboard({ onLogout }: { onLogout: () => void }) { export default function Dashboard({ onLogout }: { onLogout: () => void }) {
const [current, setCurrent] = useState<'home' | 'account' | 'appearance'>('home');
const [transactions, setTransactions] = useState<Transaction[]>([]); const [transactions, setTransactions] = useState<Transaction[]>([]);
const [categories, setCategories] = useState<Category[]>([]); const [categories, setCategories] = useState<Category[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -36,9 +39,7 @@ export default function Dashboard({ onLogout }: { onLogout: () => void }) {
} }
} }
useEffect(() => { useEffect(() => { loadAll(); }, []);
loadAll();
}, []);
const last10 = useMemo(() => { const last10 = useMemo(() => {
const sorted = [...transactions].sort((a, b) => b.id - a.id); const sorted = [...transactions].sort((a, b) => b.id - a.id);
@@ -56,9 +57,7 @@ export default function Dashboard({ onLogout }: { onLogout: () => void }) {
return arr; return arr;
}, [last10, minAmount, maxAmount, filterCategoryId, searchText]); }, [last10, minAmount, maxAmount, filterCategoryId, searchText]);
function categoryNameById(id: number) { function categoryNameById(id: number) { return categories.find(c => c.id === id)?.name || `#${id}`; }
return categories.find(c => c.id === id)?.name || `#${id}`;
}
async function handleCreate(e: React.FormEvent) { async function handleCreate(e: React.FormEvent) {
e.preventDefault(); e.preventDefault();
@@ -71,85 +70,103 @@ export default function Dashboard({ onLogout }: { onLogout: () => void }) {
try { try {
const created = await createTransaction(payload); const created = await createTransaction(payload);
setTransactions(prev => [created, ...prev]); setTransactions(prev => [created, ...prev]);
// reset form setAmount(''); setDescription(''); setSelectedCategoryId('');
setAmount('');
setDescription('');
setSelectedCategoryId('');
} catch (err: any) { } catch (err: any) {
alert(err?.message || 'Failed to create transaction'); alert(err?.message || 'Failed to create transaction');
} }
} }
return ( return (
<div style={{ maxWidth: 900, margin: '2rem auto', padding: 16 }}> <div className="app-layout">
<header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}> <aside className="sidebar">
<h2 style={{ margin: 0 }}>Dashboard</h2> <div className="logo">7Project</div>
<button onClick={onLogout}>Logout</button> <nav className="nav">
</header> <button className={current === 'home' ? 'active' : ''} onClick={() => setCurrent('home')}>Home</button>
<button className={current === 'account' ? 'active' : ''} onClick={() => setCurrent('account')}>Account</button>
<section style={{ border: '1px solid #eee', padding: 12, borderRadius: 8, marginBottom: 16 }}> <button className={current === 'appearance' ? 'active' : ''} onClick={() => setCurrent('appearance')}>Appearance</button>
<h3 style={{ marginTop: 0 }}>Add Transaction</h3> </nav>
<form onSubmit={handleCreate} style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}> </aside>
<input type="number" step="0.01" placeholder="Amount" value={amount} onChange={(e) => setAmount(e.target.value)} required /> <div className="content">
<input type="text" placeholder="Description (optional)" value={description} onChange={(e) => setDescription(e.target.value)} /> <div className="topbar">
<select value={selectedCategoryId} onChange={(e) => setSelectedCategoryId(e.target.value ? Number(e.target.value) : '')}> <h2 style={{ margin: 0 }}>{current === 'home' ? 'Dashboard' : current === 'account' ? 'Account' : 'Appearance'}</h2>
<option value="">No category</option> <div className="actions">
{categories.map(c => ( <span className="user muted">Signed in</span>
<option key={c.id} value={c.id}>{c.name}</option> <button className="btn" onClick={onLogout}>Logout</button>
))} </div>
</select>
<button type="submit">Add</button>
</form>
</section>
<section style={{ border: '1px solid #eee', padding: 12, borderRadius: 8, marginBottom: 16 }}>
<h3 style={{ marginTop: 0 }}>Filters</h3>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<input type="number" step="0.01" placeholder="Min amount" value={minAmount} onChange={(e) => setMinAmount(e.target.value)} />
<input type="number" step="0.01" placeholder="Max amount" value={maxAmount} onChange={(e) => setMaxAmount(e.target.value)} />
<select value={filterCategoryId} onChange={(e) => setFilterCategoryId(e.target.value ? Number(e.target.value) : '')}>
<option value="">All categories</option>
{categories.map(c => (
<option key={c.id} value={c.id}>{c.name}</option>
))}
</select>
<input type="text" placeholder="Search in description" value={searchText} onChange={(e) => setSearchText(e.target.value)} />
</div> </div>
</section> <main className="page space-y">
{current === 'home' && (
<>
<section className="card">
<h3>Add Transaction</h3>
<form onSubmit={handleCreate} className="form-row">
<input className="input" type="number" step="0.01" placeholder="Amount" value={amount} onChange={(e) => setAmount(e.target.value)} required />
<input className="input" type="text" placeholder="Description (optional)" value={description} onChange={(e) => setDescription(e.target.value)} />
<select className="input" value={selectedCategoryId} onChange={(e) => setSelectedCategoryId(e.target.value ? Number(e.target.value) : '')}>
<option value="">No category</option>
{categories.map(c => (<option key={c.id} value={c.id}>{c.name}</option>))}
</select>
<button className="btn primary" type="submit">Add</button>
</form>
</section>
<section style={{ border: '1px solid #eee', padding: 12, borderRadius: 8 }}> <section className="card">
<h3 style={{ marginTop: 0 }}>Latest Transactions (last 10)</h3> <h3>Filters</h3>
{loading ? ( <div className="form-row">
<div>Loading</div> <input className="input" type="number" step="0.01" placeholder="Min amount" value={minAmount} onChange={(e) => setMinAmount(e.target.value)} />
) : error ? ( <input className="input" type="number" step="0.01" placeholder="Max amount" value={maxAmount} onChange={(e) => setMaxAmount(e.target.value)} />
<div style={{ color: 'crimson' }}>{error}</div> <select className="input" value={filterCategoryId} onChange={(e) => setFilterCategoryId(e.target.value ? Number(e.target.value) : '')}>
) : filtered.length === 0 ? ( <option value="">All categories</option>
<div>No transactions</div> {categories.map(c => (<option key={c.id} value={c.id}>{c.name}</option>))}
) : ( </select>
<table style={{ width: '100%', borderCollapse: 'collapse' }}> <input className="input" type="text" placeholder="Search in description" value={searchText} onChange={(e) => setSearchText(e.target.value)} />
<thead> </div>
<tr> </section>
<th style={{ textAlign: 'left', borderBottom: '1px solid #ddd' }}>ID</th>
<th style={{ textAlign: 'right', borderBottom: '1px solid #ddd' }}>Amount</th> <section className="card">
<th style={{ textAlign: 'left', borderBottom: '1px solid #ddd' }}>Description</th> <h3>Latest Transactions (last 10)</h3>
<th style={{ textAlign: 'left', borderBottom: '1px solid #ddd' }}>Categories</th> {loading ? (
</tr> <div>Loading</div>
</thead> ) : error ? (
<tbody> <div style={{ color: 'crimson' }}>{error}</div>
{filtered.map(t => ( ) : filtered.length === 0 ? (
<tr key={t.id}> <div>No transactions</div>
<td style={{ padding: '6px 4px' }}>{t.id}</td> ) : (
<td style={{ padding: '6px 4px', textAlign: 'right' }}>{formatAmount(t.amount)}</td> <table className="table">
<td style={{ padding: '6px 4px' }}>{t.description || ''}</td> <thead>
<td style={{ padding: '6px 4px' }}> <tr>
{t.category_ids.map(id => categoryNameById(id)).join(', ')} <th>ID</th>
</td> <th style={{ textAlign: 'right' }}>Amount</th>
</tr> <th>Description</th>
))} <th>Categories</th>
</tbody> </tr>
</table> </thead>
)} <tbody>
</section> {filtered.map(t => (
<tr key={t.id}>
<td>{t.id}</td>
<td className="amount">{formatAmount(t.amount)}</td>
<td>{t.description || ''}</td>
<td>{t.category_ids.map(id => categoryNameById(id)).join(', ')}</td>
</tr>
))}
</tbody>
</table>
)}
</section>
</>
)}
{current === 'account' && (
// lazy import avoided for simplicity
<AccountPage onDeleted={onLogout} />
)}
{current === 'appearance' && (
<AppearancePage />
)}
</main>
</div>
</div> </div>
); );
} }

View File

@@ -1,5 +1,12 @@
import { useState } from 'react'; import { useState, useEffect } from 'react';
import { login, register } from '../api'; import { login, register } from '../api';
import { BACKEND_URL } from '../config';
function oauthUrl(provider: 'mojeid' | 'bankid') {
const base = BACKEND_URL.replace(/\/$/, '');
const redirect = encodeURIComponent(window.location.origin + '/oauth-callback');
return `${base}/auth/${provider}/authorize?redirect_url=${redirect}`;
}
export default function LoginRegisterPage({ onLoggedIn }: { onLoggedIn: () => void }) { export default function LoginRegisterPage({ onLoggedIn }: { onLoggedIn: () => void }) {
const [mode, setMode] = useState<'login' | 'register'>('login'); const [mode, setMode] = useState<'login' | 'register'>('login');
@@ -31,41 +38,59 @@ export default function LoginRegisterPage({ onLoggedIn }: { onLoggedIn: () => vo
} }
} }
// Add this useEffect hook
useEffect(() => {
// When the component mounts, add a class to the body
document.body.classList.add('auth-page');
// When the component unmounts, remove the class
return () => {
document.body.classList.remove('auth-page');
};
}, []); // The empty array ensures this runs only once
// The JSX no longer needs the wrapper div
return ( return (
<div style={{ maxWidth: 420, margin: '4rem auto', padding: 24, border: '1px solid #ddd', borderRadius: 8 }}> <div className="card" style={{ width: 420 }}>
<h2 style={{ marginTop: 0 }}>{mode === 'login' ? 'Login' : 'Register'}</h2> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<div style={{ marginBottom: 16 }}> <h2 style={{ margin: 0 }}>{mode === 'login' ? 'Welcome back' : 'Create your account'}</h2>
<button onClick={() => setMode('login')} disabled={mode === 'login'}>Login</button> <div className="segmented">
<button onClick={() => setMode('register')} disabled={mode === 'register'} style={{ marginLeft: 8 }}>Register</button> <button className={mode === 'login' ? 'active' : ''} type="button" onClick={() => setMode('login')}>Login</button>
<button className={mode === 'register' ? 'active' : ''} type="button" onClick={() => setMode('register')}>Register</button>
</div>
</div> </div>
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit} className="space-y">
<div style={{ marginBottom: 12 }}> <div>
<label>Email<br /> <label className="muted">Email</label>
<input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} style={{ width: '100%' }} /> <input className="input" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
</label> </div>
</div> <div>
<div style={{ marginBottom: 12 }}> <label className="muted">Password</label>
<label>Password<br /> <input className="input" type="password" required value={password} onChange={(e) => setPassword(e.target.value)} />
<input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} style={{ width: '100%' }} /> </div>
</label> {mode === 'register' && (
</div> <div className="form-row">
{mode === 'register' && ( <div>
<> <label className="muted">First name (optional)</label>
<div style={{ marginBottom: 12 }}> <input className="input" type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
<label>First name (optional)<br /> </div>
<input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} style={{ width: '100%' }} /> <div>
</label> <label className="muted">Last name (optional)</label>
<input className="input" type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} />
</div>
</div> </div>
<div style={{ marginBottom: 12 }}> )}
<label>Last name (optional)<br /> {error && <div style={{ color: 'crimson' }}>{error}</div>}
<input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} style={{ width: '100%' }} /> <div className="actions" style={{ justifyContent: 'space-between' }}>
</label> <div className="muted">Or continue with</div>
<div className="actions">
<a className="btn" href={oauthUrl('mojeid')}>MojeID</a>
<a className="btn" href={oauthUrl('bankid')}>BankID</a>
<button className="btn primary" type="submit" disabled={loading}>{loading ? 'Please wait…' : (mode === 'login' ? 'Login' : 'Register')}</button>
</div> </div>
</> </div>
)}
{error && <div style={{ color: 'crimson', marginBottom: 12 }}>{error}</div>}
<button type="submit" disabled={loading}>{loading ? 'Please wait…' : (mode === 'login' ? 'Login' : 'Register')}</button>
</form> </form>
</div> </div>
); );
} }