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.services.user_service import auth_backend, fastapi_users
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/*
router.include_router(
fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]

View File

@@ -1,42 +1 @@
#root {
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;
}
/* App-level styles moved to ui.css for a cleaner layout. */

View File

@@ -8,6 +8,18 @@ function App() {
const [hasToken, setHasToken] = useState<boolean>(!!localStorage.getItem('token'));
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) => {
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[]> {
const res = await fetch(`${getBaseUrl()}/transactions/`, {
const res = await fetch(`${getBaseUrl()}/transactions/`, {
headers: { 'Content-Type': 'application/json', ...authHeaders() },
});
if (!res.ok) throw new Error('Failed to load transactions');
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() {
localStorage.removeItem('token');
}

View File

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

View File

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

View File

@@ -1,5 +1,12 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
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 }) {
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 (
<div style={{ maxWidth: 420, margin: '4rem auto', padding: 24, border: '1px solid #ddd', borderRadius: 8 }}>
<h2 style={{ marginTop: 0 }}>{mode === 'login' ? 'Login' : 'Register'}</h2>
<div style={{ marginBottom: 16 }}>
<button onClick={() => setMode('login')} disabled={mode === 'login'}>Login</button>
<button onClick={() => setMode('register')} disabled={mode === 'register'} style={{ marginLeft: 8 }}>Register</button>
<div className="card" style={{ width: 420 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<h2 style={{ margin: 0 }}>{mode === 'login' ? 'Welcome back' : 'Create your account'}</h2>
<div className="segmented">
<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>
<form onSubmit={handleSubmit}>
<div style={{ marginBottom: 12 }}>
<label>Email<br />
<input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} style={{ width: '100%' }} />
</label>
</div>
<div style={{ marginBottom: 12 }}>
<label>Password<br />
<input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} style={{ width: '100%' }} />
</label>
</div>
{mode === 'register' && (
<>
<div style={{ marginBottom: 12 }}>
<label>First name (optional)<br />
<input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} style={{ width: '100%' }} />
</label>
<form onSubmit={handleSubmit} className="space-y">
<div>
<label className="muted">Email</label>
<input className="input" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div>
<label className="muted">Password</label>
<input className="input" type="password" required value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
{mode === 'register' && (
<div className="form-row">
<div>
<label className="muted">First name (optional)</label>
<input className="input" type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
</div>
<div>
<label className="muted">Last name (optional)</label>
<input className="input" type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} />
</div>
</div>
<div style={{ marginBottom: 12 }}>
<label>Last name (optional)<br />
<input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} style={{ width: '100%' }} />
</label>
)}
{error && <div style={{ color: 'crimson' }}>{error}</div>}
<div className="actions" style={{ justifyContent: 'space-between' }}>
<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>
</>
)}
{error && <div style={{ color: 'crimson', marginBottom: 12 }}>{error}</div>}
<button type="submit" disabled={loading}>{loading ? 'Please wait…' : (mode === 'login' ? 'Login' : 'Register')}</button>
</div>
</form>
</div>
);
}