implement better-auth auth with postgres and route protection
This commit is contained in:
9
app/api/auth/[...all]/route.ts
Normal file
9
app/api/auth/[...all]/route.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { toNextJsHandler } from 'better-auth/next-js';
|
||||
import { ensureAuthSchema } from '@/lib/auth';
|
||||
|
||||
const authHandler = toNextJsHandler(async (request: Request) => {
|
||||
const auth = await ensureAuthSchema();
|
||||
return auth.handler(request);
|
||||
});
|
||||
|
||||
export const { GET, POST, PATCH, PUT, DELETE } = authHandler;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
type Context = {
|
||||
@@ -6,6 +7,11 @@ type Context = {
|
||||
};
|
||||
|
||||
export async function POST(_request: Request, context: Context) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
try {
|
||||
const { accessionNumber } = await context.params;
|
||||
|
||||
@@ -14,6 +20,7 @@ export async function POST(_request: Request, context: Context) {
|
||||
}
|
||||
|
||||
const task = await enqueueTask({
|
||||
userId: session.user.id,
|
||||
taskType: 'analyze_filing',
|
||||
payload: { accessionNumber: accessionNumber.trim() },
|
||||
priority: 65
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { getStoreSnapshot } from '@/lib/server/store';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const tickerFilter = url.searchParams.get('ticker')?.trim().toUpperCase();
|
||||
const limitValue = Number(url.searchParams.get('limit') ?? 50);
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await request.json() as {
|
||||
ticker?: string;
|
||||
@@ -13,6 +19,7 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
const task = await enqueueTask({
|
||||
userId: session.user.id,
|
||||
taskType: 'sync_filings',
|
||||
payload: {
|
||||
ticker: payload.ticker.trim().toUpperCase(),
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
return Response.json({
|
||||
user: {
|
||||
id: 1,
|
||||
email: 'operator@local.fiscal',
|
||||
name: 'Local Operator',
|
||||
image: null
|
||||
id: session.user.id,
|
||||
email: session.user.email,
|
||||
name: session.user.name,
|
||||
image: session.user.image
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { recalculateHolding } from '@/lib/server/portfolio';
|
||||
import { withStore } from '@/lib/server/store';
|
||||
|
||||
@@ -16,6 +17,12 @@ function asPositiveNumber(value: unknown) {
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, context: Context) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
const { id } = await context.params;
|
||||
const numericId = Number(id);
|
||||
|
||||
@@ -33,7 +40,7 @@ export async function PATCH(request: Request, context: Context) {
|
||||
let updated: unknown = null;
|
||||
|
||||
await withStore((store) => {
|
||||
const index = store.holdings.findIndex((entry) => entry.id === numericId);
|
||||
const index = store.holdings.findIndex((entry) => entry.id === numericId && entry.user_id === userId);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
@@ -66,6 +73,12 @@ export async function PATCH(request: Request, context: Context) {
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: Context) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
const { id } = await context.params;
|
||||
const numericId = Number(id);
|
||||
|
||||
@@ -76,7 +89,7 @@ export async function DELETE(_request: Request, context: Context) {
|
||||
let removed = false;
|
||||
|
||||
await withStore((store) => {
|
||||
const next = store.holdings.filter((holding) => holding.id !== numericId);
|
||||
const next = store.holdings.filter((holding) => !(holding.id === numericId && holding.user_id === userId));
|
||||
removed = next.length !== store.holdings.length;
|
||||
store.holdings = next;
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Holding } from '@/lib/types';
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { recalculateHolding } from '@/lib/server/portfolio';
|
||||
import { getStoreSnapshot, withStore } from '@/lib/server/store';
|
||||
|
||||
@@ -13,8 +14,15 @@ function asPositiveNumber(value: unknown) {
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const holdings = snapshot.holdings
|
||||
.filter((holding) => holding.user_id === userId)
|
||||
.slice()
|
||||
.sort((a, b) => Number(b.market_value) - Number(a.market_value));
|
||||
|
||||
@@ -22,6 +30,13 @@ export async function GET() {
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
|
||||
try {
|
||||
const payload = await request.json() as {
|
||||
ticker?: string;
|
||||
@@ -50,7 +65,7 @@ export async function POST(request: Request) {
|
||||
let holding: Holding | null = null;
|
||||
|
||||
await withStore((store) => {
|
||||
const existingIndex = store.holdings.findIndex((entry) => entry.ticker === ticker);
|
||||
const existingIndex = store.holdings.findIndex((entry) => entry.user_id === userId && entry.ticker === ticker);
|
||||
const currentPrice = asPositiveNumber(payload.currentPrice) ?? avgCost;
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
@@ -73,7 +88,7 @@ export async function POST(request: Request) {
|
||||
store.counters.holdings += 1;
|
||||
const created = recalculateHolding({
|
||||
id: store.counters.holdings,
|
||||
user_id: 1,
|
||||
user_id: userId,
|
||||
ticker,
|
||||
shares: shares.toFixed(6),
|
||||
avg_cost: avgCost.toFixed(6),
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
export async function POST() {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
try {
|
||||
const task = await enqueueTask({
|
||||
userId: session.user.id,
|
||||
taskType: 'portfolio_insights',
|
||||
payload: {},
|
||||
priority: 70
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { getStoreSnapshot } from '@/lib/server/store';
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const insight = snapshot.insights
|
||||
.filter((entry) => entry.user_id === userId)
|
||||
.slice()
|
||||
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))[0] ?? null;
|
||||
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { enqueueTask } from '@/lib/server/tasks';
|
||||
|
||||
export async function POST() {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
try {
|
||||
const task = await enqueueTask({
|
||||
userId: session.user.id,
|
||||
taskType: 'refresh_prices',
|
||||
payload: {},
|
||||
priority: 80
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { buildPortfolioSummary } from '@/lib/server/portfolio';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { getStoreSnapshot } from '@/lib/server/store';
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const summary = buildPortfolioSummary(snapshot.holdings);
|
||||
const summary = buildPortfolioSummary(snapshot.holdings.filter((holding) => holding.user_id === userId));
|
||||
return Response.json({ summary });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { getTaskById } from '@/lib/server/tasks';
|
||||
|
||||
type Context = {
|
||||
@@ -6,8 +7,13 @@ type Context = {
|
||||
};
|
||||
|
||||
export async function GET(_request: Request, context: Context) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const { taskId } = await context.params;
|
||||
const task = await getTaskById(taskId);
|
||||
const task = await getTaskById(taskId, session.user.id);
|
||||
|
||||
if (!task) {
|
||||
return jsonError('Task not found', 404);
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import type { TaskStatus } from '@/lib/types';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { listRecentTasks } from '@/lib/server/tasks';
|
||||
|
||||
const ALLOWED_STATUSES: TaskStatus[] = ['queued', 'running', 'completed', 'failed'];
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const limitValue = Number(url.searchParams.get('limit') ?? 20);
|
||||
const limit = Number.isFinite(limitValue)
|
||||
@@ -15,6 +21,6 @@ export async function GET(request: Request) {
|
||||
return ALLOWED_STATUSES.includes(status as TaskStatus);
|
||||
});
|
||||
|
||||
const tasks = await listRecentTasks(limit, statuses.length > 0 ? statuses : undefined);
|
||||
const tasks = await listRecentTasks(session.user.id, limit, statuses.length > 0 ? statuses : undefined);
|
||||
return Response.json({ tasks });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { withStore } from '@/lib/server/store';
|
||||
|
||||
type Context = {
|
||||
@@ -6,6 +7,12 @@ type Context = {
|
||||
};
|
||||
|
||||
export async function DELETE(_request: Request, context: Context) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
const { id } = await context.params;
|
||||
const numericId = Number(id);
|
||||
|
||||
@@ -16,7 +23,7 @@ export async function DELETE(_request: Request, context: Context) {
|
||||
let removed = false;
|
||||
|
||||
await withStore((store) => {
|
||||
const next = store.watchlist.filter((item) => item.id !== numericId);
|
||||
const next = store.watchlist.filter((item) => !(item.id === numericId && item.user_id === userId));
|
||||
removed = next.length !== store.watchlist.length;
|
||||
store.watchlist = next;
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { WatchlistItem } from '@/lib/types';
|
||||
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
||||
import { requireAuthenticatedSession } from '@/lib/server/auth-session';
|
||||
import { getStoreSnapshot, withStore } from '@/lib/server/store';
|
||||
|
||||
function nowIso() {
|
||||
@@ -7,8 +8,15 @@ function nowIso() {
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
const snapshot = await getStoreSnapshot();
|
||||
const items = snapshot.watchlist
|
||||
.filter((item) => item.user_id === userId)
|
||||
.slice()
|
||||
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));
|
||||
|
||||
@@ -16,6 +24,13 @@ export async function GET() {
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { session, response } = await requireAuthenticatedSession();
|
||||
if (response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
|
||||
try {
|
||||
const payload = await request.json() as {
|
||||
ticker?: string;
|
||||
@@ -35,7 +50,7 @@ export async function POST(request: Request) {
|
||||
|
||||
await withStore((store) => {
|
||||
const ticker = payload.ticker!.trim().toUpperCase();
|
||||
const existingIndex = store.watchlist.findIndex((entry) => entry.ticker === ticker);
|
||||
const existingIndex = store.watchlist.findIndex((entry) => entry.user_id === userId && entry.ticker === ticker);
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
const existing = store.watchlist[existingIndex];
|
||||
@@ -53,7 +68,7 @@ export async function POST(request: Request) {
|
||||
store.counters.watchlist += 1;
|
||||
const created: WatchlistItem = {
|
||||
id: store.counters.watchlist,
|
||||
user_id: 1,
|
||||
user_id: userId,
|
||||
ticker,
|
||||
company_name: payload.companyName!.trim(),
|
||||
sector: payload.sector?.trim() || null,
|
||||
|
||||
@@ -1,32 +1,151 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { Suspense, type FormEvent, useEffect, useMemo, useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { AuthShell } from '@/components/auth/auth-shell';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
|
||||
function sanitizeNextPath(value: string | null) {
|
||||
if (!value || !value.startsWith('/')) {
|
||||
return '/';
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export default function SignInPage() {
|
||||
return (
|
||||
<Suspense fallback={<div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading sign in...</div>}>
|
||||
<SignInPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function SignInPageContent() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const nextPath = useMemo(() => sanitizeNextPath(searchParams.get('next')), [searchParams]);
|
||||
const { data: rawSession, isPending } = authClient.useSession();
|
||||
const session = (rawSession ?? null) as { user?: { id?: string } } | null;
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [busyAction, setBusyAction] = useState<'password' | 'magic' | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && session?.user?.id) {
|
||||
router.replace(nextPath);
|
||||
}
|
||||
}, [isPending, nextPath, router, session]);
|
||||
|
||||
const signInWithPassword = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setMessage(null);
|
||||
setBusyAction('password');
|
||||
|
||||
const { error: signInError } = await authClient.signIn.email({
|
||||
email: email.trim(),
|
||||
password,
|
||||
callbackURL: nextPath
|
||||
});
|
||||
|
||||
setBusyAction(null);
|
||||
|
||||
if (signInError) {
|
||||
setError(signInError.message || 'Sign in failed.');
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(nextPath);
|
||||
};
|
||||
|
||||
const signInWithMagicLink = async () => {
|
||||
const targetEmail = email.trim();
|
||||
if (!targetEmail) {
|
||||
setError('Email is required for magic link sign in.');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setMessage(null);
|
||||
setBusyAction('magic');
|
||||
|
||||
const { error: magicError } = await authClient.signIn.magicLink({
|
||||
email: targetEmail,
|
||||
callbackURL: nextPath
|
||||
});
|
||||
|
||||
setBusyAction(null);
|
||||
|
||||
if (magicError) {
|
||||
setError(magicError.message || 'Unable to send magic link.');
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage('Magic link sent. Check your inbox and open the link on this device.');
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthShell
|
||||
title="Local Runtime Mode"
|
||||
subtitle="Authentication is disabled in this rebuilt local-first environment."
|
||||
title="Secure Sign In"
|
||||
subtitle="Use email/password or request a magic link."
|
||||
footer={(
|
||||
<>
|
||||
Need multi-user auth later?{' '}
|
||||
<Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
Open command center
|
||||
Need an account?{' '}
|
||||
<Link href={`/auth/signup${nextPath !== '/' ? `?next=${encodeURIComponent(nextPath)}` : ''}`} className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
Create one
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">
|
||||
Continue directly into the fiscal terminal. API routes are same-origin and task execution is fully local with OpenClaw support.
|
||||
</p>
|
||||
<form className="space-y-4" onSubmit={signInWithPassword}>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Email</label>
|
||||
<Input
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Link href="/" className="mt-6 block">
|
||||
<Button type="button" className="w-full">
|
||||
Enter terminal
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Password</label>
|
||||
<Input
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}
|
||||
{message ? <p className="text-sm text-[#9fffcf]">{message}</p> : null}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={busyAction !== null}>
|
||||
{busyAction === 'password' ? 'Signing in...' : 'Sign in with password'}
|
||||
</Button>
|
||||
</Link>
|
||||
</form>
|
||||
|
||||
<div className="mt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="w-full"
|
||||
disabled={busyAction !== null}
|
||||
onClick={() => void signInWithMagicLink()}
|
||||
>
|
||||
{busyAction === 'magic' ? 'Sending link...' : 'Send magic link'}
|
||||
</Button>
|
||||
</div>
|
||||
</AuthShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,143 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { Suspense, type FormEvent, useEffect, useMemo, useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { AuthShell } from '@/components/auth/auth-shell';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
|
||||
function sanitizeNextPath(value: string | null) {
|
||||
if (!value || !value.startsWith('/')) {
|
||||
return '/';
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export default function SignUpPage() {
|
||||
return (
|
||||
<Suspense fallback={<div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading sign up...</div>}>
|
||||
<SignUpPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function SignUpPageContent() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const nextPath = useMemo(() => sanitizeNextPath(searchParams.get('next')), [searchParams]);
|
||||
const { data: rawSession, isPending } = authClient.useSession();
|
||||
const session = (rawSession ?? null) as { user?: { id?: string } } | null;
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPending && session?.user?.id) {
|
||||
router.replace(nextPath);
|
||||
}
|
||||
}, [isPending, nextPath, router, session]);
|
||||
|
||||
const signUp = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
|
||||
const { error: signUpError } = await authClient.signUp.email({
|
||||
name: name.trim(),
|
||||
email: email.trim(),
|
||||
password,
|
||||
callbackURL: nextPath
|
||||
});
|
||||
|
||||
setBusy(false);
|
||||
|
||||
if (signUpError) {
|
||||
setError(signUpError.message || 'Unable to create account.');
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(nextPath);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthShell
|
||||
title="Workspace Provisioned"
|
||||
subtitle="This clone now runs in local-operator mode and does not require account creation."
|
||||
title="Create Account"
|
||||
subtitle="Set up your operator profile to access portfolio and filings intelligence."
|
||||
footer={(
|
||||
<>
|
||||
Already set?{' '}
|
||||
<Link href="/" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
Launch dashboard
|
||||
Already registered?{' '}
|
||||
<Link href={`/auth/signin${nextPath !== '/' ? `?next=${encodeURIComponent(nextPath)}` : ''}`} className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
|
||||
Sign in
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<p className="text-sm text-[color:var(--terminal-muted)]">
|
||||
For production deployment you can reintroduce full multi-user authentication, but this rebuild is intentionally self-contained for fast iteration.
|
||||
</p>
|
||||
<form className="space-y-4" onSubmit={signUp}>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Name</label>
|
||||
<Input
|
||||
type="text"
|
||||
autoComplete="name"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Link href="/" className="mt-6 block">
|
||||
<Button type="button" className="w-full">
|
||||
Open fiscal desk
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Email</label>
|
||||
<Input
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Password</label>
|
||||
<Input
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Confirm Password</label>
|
||||
<Input
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={confirmPassword}
|
||||
onChange={(event) => setConfirmPassword(event.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={busy}>
|
||||
{busy ? 'Creating account...' : 'Create account'}
|
||||
</Button>
|
||||
</Link>
|
||||
</form>
|
||||
</AuthShell>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user