feat(frontend): email+password auth, /signin + /signup pages, marketing consolidation, onboarding workspace naming + full data persistence
This commit is contained in:
61
app/api/auth/login/route.ts
Normal file
61
app/api/auth/login/route.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { queryOne } from "@/lib/db-postgres";
|
||||
import {
|
||||
verifyPassword,
|
||||
createDbSession,
|
||||
SESSION_COOKIE_NAME,
|
||||
sessionCookieOptions,
|
||||
} from "@/lib/auth/password";
|
||||
|
||||
// POST /api/auth/login { email, password }
|
||||
// Verifies the scrypt hash stored on the user's fs_users row and, on success,
|
||||
// creates a database session + sets the session cookie. Google-only accounts
|
||||
// have no password hash, so they fall through to the generic invalid message.
|
||||
export async function POST(request: Request) {
|
||||
let body: { email?: unknown; password?: unknown };
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
|
||||
}
|
||||
|
||||
const email = String(body.email ?? "").trim().toLowerCase();
|
||||
const password = String(body.password ?? "");
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json(
|
||||
{ error: "Enter your email and password." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const invalid = NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
|
||||
try {
|
||||
const row = await queryOne<{ user_id: string; hash: string | null }>(
|
||||
`SELECT user_id, data->>'passwordHash' AS hash
|
||||
FROM fs_users
|
||||
WHERE lower(data->>'email') = $1
|
||||
LIMIT 1`,
|
||||
[email],
|
||||
);
|
||||
if (!row || !row.hash) return invalid;
|
||||
|
||||
const ok = await verifyPassword(password, row.hash);
|
||||
if (!ok) return invalid;
|
||||
|
||||
const { token, expires } = await createDbSession(row.user_id);
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(SESSION_COOKIE_NAME, token, sessionCookieOptions(expires));
|
||||
return res;
|
||||
} catch (err) {
|
||||
console.error("[login] exception:", err);
|
||||
return NextResponse.json(
|
||||
{ error: "Could not sign you in. Please try again." },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
100
app/api/auth/register/route.ts
Normal file
100
app/api/auth/register/route.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { randomUUID } from "crypto";
|
||||
import { query, queryOne } from "@/lib/db-postgres";
|
||||
import { ensureWorkspaceForUser } from "@/lib/workspaces";
|
||||
import {
|
||||
hashPassword,
|
||||
createDbSession,
|
||||
SESSION_COOKIE_NAME,
|
||||
sessionCookieOptions,
|
||||
} from "@/lib/auth/password";
|
||||
|
||||
// POST /api/auth/register { email, password, name? }
|
||||
// Creates an email/password account: a NextAuth `users` row, the custom
|
||||
// `fs_users` row (with the scrypt password hash + workspace metadata, mirroring
|
||||
// the Google signIn callback), a Vibn workspace, and a database session — then
|
||||
// sets the session cookie so the user is signed in immediately.
|
||||
export async function POST(request: Request) {
|
||||
let body: { email?: unknown; password?: unknown; name?: unknown };
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
|
||||
}
|
||||
|
||||
const email = String(body.email ?? "").trim().toLowerCase();
|
||||
const password = String(body.password ?? "");
|
||||
const name = body.name ? String(body.name).trim() : null;
|
||||
|
||||
if (!/^\S+@\S+\.\S+$/.test(email)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Enter a valid email address." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (password.length < 8) {
|
||||
return NextResponse.json(
|
||||
{ error: "Password must be at least 8 characters." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const existing = await queryOne<{ id: string }>(
|
||||
`SELECT id FROM users WHERE lower(email) = $1 LIMIT 1`,
|
||||
[email],
|
||||
);
|
||||
if (existing) {
|
||||
return NextResponse.json(
|
||||
{ error: "An account with this email already exists. Try signing in." },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
// 1. NextAuth user row (id is normally a cuid; any unique string works).
|
||||
const userId = randomUUID();
|
||||
await query(
|
||||
`INSERT INTO users (id, name, email, email_verified)
|
||||
VALUES ($1, $2, $3, NOW())`,
|
||||
[userId, name, email],
|
||||
);
|
||||
|
||||
// 2. Custom fs_users row — same shape the Google signIn callback writes,
|
||||
// plus the password hash.
|
||||
const workspace =
|
||||
email.split("@")[0].replace(/[^a-z0-9]+/g, "-") + "-account";
|
||||
const passwordHash = await hashPassword(password);
|
||||
const data = JSON.stringify({ email, name, image: null, workspace, passwordHash });
|
||||
const fsRows = await query<{ id: string }>(
|
||||
`INSERT INTO fs_users (id, user_id, data)
|
||||
VALUES (gen_random_uuid()::text, $1, $2::jsonb)
|
||||
RETURNING id`,
|
||||
[userId, data],
|
||||
);
|
||||
const fsUserId = fsRows[0].id;
|
||||
|
||||
// 3. Ensure a Vibn workspace (no Coolify/Gitea provisioning yet — happens
|
||||
// lazily on first project create, same as the OAuth path).
|
||||
try {
|
||||
await ensureWorkspaceForUser({
|
||||
userId: fsUserId,
|
||||
email,
|
||||
displayName: name,
|
||||
});
|
||||
} catch (wsErr) {
|
||||
console.error("[register] ensureWorkspaceForUser failed:", wsErr);
|
||||
}
|
||||
|
||||
// 4. Sign them in: create a DB session + set the cookie.
|
||||
const { token, expires } = await createDbSession(userId);
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(SESSION_COOKIE_NAME, token, sessionCookieOptions(expires));
|
||||
return res;
|
||||
} catch (err) {
|
||||
console.error("[register] exception:", err);
|
||||
return NextResponse.json(
|
||||
{ error: "Could not create your account. Please try again." },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,13 +15,19 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { authSession } from "@/lib/auth/session-server";
|
||||
import {
|
||||
exchangeCodeForToken, getAuthenticatedUser, persistGithubIntegration,
|
||||
exchangeCodeForToken,
|
||||
getAuthenticatedUser,
|
||||
persistGithubIntegration,
|
||||
isGithubOauthConfigured,
|
||||
} from "@/lib/integrations/github";
|
||||
|
||||
const STATE_COOKIE = "gh_oauth_state";
|
||||
|
||||
function bounce(origin: string, returnTo: string, params: Record<string, string>): NextResponse {
|
||||
function bounce(
|
||||
origin: string,
|
||||
returnTo: string,
|
||||
params: Record<string, string>,
|
||||
): NextResponse {
|
||||
const dest = new URL(returnTo.startsWith("/") ? returnTo : "/", origin);
|
||||
for (const [k, v] of Object.entries(params)) dest.searchParams.set(k, v);
|
||||
const res = NextResponse.redirect(dest);
|
||||
@@ -35,40 +41,56 @@ export async function GET(req: Request) {
|
||||
const origin = (process.env.NEXTAUTH_URL ?? url.origin).replace(/\/$/, "");
|
||||
|
||||
// Recover the original target from the state cookie *before* any error path.
|
||||
const cookieState = req.headers.get("cookie")
|
||||
?.split(";").map(c => c.trim())
|
||||
.find(c => c.startsWith(`${STATE_COOKIE}=`))
|
||||
?.split("=")[1] ?? "";
|
||||
const [storedState, storedReturnTo = "/"] = decodeURIComponent(cookieState).split(":");
|
||||
const cookieState =
|
||||
req.headers
|
||||
.get("cookie")
|
||||
?.split(";")
|
||||
.map((c) => c.trim())
|
||||
.find((c) => c.startsWith(`${STATE_COOKIE}=`))
|
||||
?.split("=")[1] ?? "";
|
||||
const [storedState, storedReturnTo = "/"] =
|
||||
decodeURIComponent(cookieState).split(":");
|
||||
|
||||
if (!isGithubOauthConfigured()) {
|
||||
return bounce(origin, storedReturnTo, { gh_error: "GitHub OAuth not configured" });
|
||||
return bounce(origin, storedReturnTo, {
|
||||
gh_error: "GitHub OAuth not configured",
|
||||
});
|
||||
}
|
||||
|
||||
const session = await authSession();
|
||||
if (!session?.user?.email) {
|
||||
return bounce(origin, "/auth", { gh_error: "Sign in first" });
|
||||
return bounce(origin, "/signin", { gh_error: "Sign in first" });
|
||||
}
|
||||
|
||||
const code = url.searchParams.get("code");
|
||||
const state = url.searchParams.get("state");
|
||||
const errParam = url.searchParams.get("error_description") ?? url.searchParams.get("error");
|
||||
const errParam =
|
||||
url.searchParams.get("error_description") ?? url.searchParams.get("error");
|
||||
|
||||
if (errParam) {
|
||||
return bounce(origin, storedReturnTo, { gh_error: errParam });
|
||||
}
|
||||
if (!code || !state) {
|
||||
return bounce(origin, storedReturnTo, { gh_error: "Missing code or state" });
|
||||
return bounce(origin, storedReturnTo, {
|
||||
gh_error: "Missing code or state",
|
||||
});
|
||||
}
|
||||
if (!storedState || storedState !== state) {
|
||||
return bounce(origin, storedReturnTo, { gh_error: "State mismatch (try again)" });
|
||||
return bounce(origin, storedReturnTo, {
|
||||
gh_error: "State mismatch (try again)",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const callbackUrl = `${origin}/api/integrations/github/callback`;
|
||||
const tok = await exchangeCodeForToken(code, callbackUrl);
|
||||
const me = await getAuthenticatedUser(tok.accessToken);
|
||||
await persistGithubIntegration(session.user.email, me.login, tok.accessToken, tok.scope);
|
||||
await persistGithubIntegration(
|
||||
session.user.email,
|
||||
me.login,
|
||||
tok.accessToken,
|
||||
tok.scope,
|
||||
);
|
||||
return bounce(origin, storedReturnTo, { gh_connected: me.login });
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "GitHub connect failed";
|
||||
|
||||
@@ -3,11 +3,16 @@ import { authSession } from "../../../lib/auth/session-server";
|
||||
import { query, queryOne } from "../../../lib/db-postgres";
|
||||
import {
|
||||
ensureWorkspaceProvisioned,
|
||||
getWorkspaceByOwner,
|
||||
type VibnWorkspace,
|
||||
} from "../../../lib/workspaces";
|
||||
|
||||
// Generates a URL-safe slug from a business name, ensuring uniqueness in the database.
|
||||
async function generateUniqueSlug(name: string): Promise<string> {
|
||||
// URL-safe, unique slug from a name. Optionally exclude a workspace id so a
|
||||
// workspace can keep/rename to a slug it already owns.
|
||||
async function generateUniqueSlug(
|
||||
name: string,
|
||||
excludeWorkspaceId?: string,
|
||||
): Promise<string> {
|
||||
const base =
|
||||
name
|
||||
.toLowerCase()
|
||||
@@ -17,10 +22,15 @@ async function generateUniqueSlug(name: string): Promise<string> {
|
||||
let slug = base;
|
||||
let count = 0;
|
||||
while (true) {
|
||||
const existing = await queryOne(
|
||||
"SELECT id FROM vibn_workspaces WHERE slug = $1 LIMIT 1",
|
||||
[slug],
|
||||
);
|
||||
const existing = excludeWorkspaceId
|
||||
? await queryOne(
|
||||
"SELECT id FROM vibn_workspaces WHERE slug = $1 AND id <> $2 LIMIT 1",
|
||||
[slug, excludeWorkspaceId],
|
||||
)
|
||||
: await queryOne(
|
||||
"SELECT id FROM vibn_workspaces WHERE slug = $1 LIMIT 1",
|
||||
[slug],
|
||||
);
|
||||
if (!existing) return slug;
|
||||
count++;
|
||||
slug = `${base}-${count}`;
|
||||
@@ -28,8 +38,11 @@ async function generateUniqueSlug(name: string): Promise<string> {
|
||||
}
|
||||
|
||||
// POST /api/onboarding
|
||||
// Saves ALL onboarding choices (Agency or Personal) to the PostgreSQL database,
|
||||
// creates the workspace/tenant, links the user as owner, and triggers async provisioning.
|
||||
// Finalises onboarding. Every signed-in user already has a workspace (created
|
||||
// lazily at sign-in by ensureWorkspaceForUser), so this RENAMES that workspace
|
||||
// to the name chosen in onboarding rather than creating a second one. Onboarding
|
||||
// answers are stashed on the user's fs_users row. Returns the workspace slug so
|
||||
// the client can redirect straight into it.
|
||||
export async function POST(request: Request) {
|
||||
const session = await authSession();
|
||||
if (!session?.user?.email) {
|
||||
@@ -38,9 +51,10 @@ export async function POST(request: Request) {
|
||||
|
||||
try {
|
||||
const payload = await request.json();
|
||||
const { isAgency, profile, expertise, tools, data } = payload;
|
||||
const { isAgency, profile, expertise, tools, data, workspaceName } =
|
||||
payload;
|
||||
|
||||
// 1. Resolve User ID from email
|
||||
// 1. Resolve the user (fs_users.id is the workspace owner id).
|
||||
const userRow = await queryOne<{ id: string }>(
|
||||
"SELECT id FROM fs_users WHERE data->>'email' = $1 LIMIT 1",
|
||||
[session.user.email],
|
||||
@@ -50,50 +64,78 @@ export async function POST(request: Request) {
|
||||
}
|
||||
const userId = userRow.id;
|
||||
|
||||
// 2. Determine business name & create unique slug
|
||||
const businessName = isAgency
|
||||
? profile?.name || "My Agency"
|
||||
: data?.bizName || "My Workspace";
|
||||
const slug = await generateUniqueSlug(businessName);
|
||||
// 2. Determine the workspace name. An explicit name from the
|
||||
// "Name your workspace" step wins; otherwise fall back to what the flow
|
||||
// already collected.
|
||||
const explicitName =
|
||||
typeof workspaceName === "string" ? workspaceName.trim() : "";
|
||||
const businessName =
|
||||
explicitName ||
|
||||
(isAgency ? profile?.name : data?.bizName) ||
|
||||
"My Workspace";
|
||||
|
||||
// 3. Assemble GTM Metadata block to store in JSONB
|
||||
const onboardingMetadata = isAgency
|
||||
? {
|
||||
isAgency: true,
|
||||
city: profile?.city,
|
||||
hasWebsite: profile?.hasWebsite,
|
||||
websiteUrl: profile?.websiteUrl,
|
||||
hasSocials: profile?.hasSocials,
|
||||
hasBlog: profile?.hasBlog,
|
||||
hasCustomDomain: profile?.hasCustomDomain,
|
||||
hasExistingClients: profile?.hasExistingClients,
|
||||
expertise,
|
||||
tools,
|
||||
}
|
||||
: {
|
||||
isAgency: false,
|
||||
city: data?.bizCity,
|
||||
websiteUrl: data?.bizWebsite,
|
||||
bizType: data?.biz,
|
||||
tools: data?.tools,
|
||||
theme: data?.theme || "minimal",
|
||||
template: data?.template || "crm",
|
||||
buildDesc: data?.buildDesc,
|
||||
};
|
||||
// 3. Stash onboarding answers on the user (vibn_workspaces has no `data`
|
||||
// column; fs_users does). Non-fatal.
|
||||
// Persist EVERYTHING the flow collected (the full raw payload), not a
|
||||
// curated subset, so nothing the user chose is lost.
|
||||
const onboardingMetadata = {
|
||||
isAgency: !!isAgency,
|
||||
workspaceName: businessName,
|
||||
completedAt: new Date().toISOString(),
|
||||
...(isAgency
|
||||
? {
|
||||
profile: profile ?? null,
|
||||
expertise: expertise ?? null,
|
||||
tools: tools ?? null,
|
||||
}
|
||||
: { data: data ?? null }),
|
||||
};
|
||||
try {
|
||||
await query(
|
||||
"UPDATE fs_users SET data = data || $2::jsonb, updated_at = NOW() WHERE id = $1",
|
||||
[
|
||||
userId,
|
||||
JSON.stringify({
|
||||
onboardingComplete: true,
|
||||
onboarding: onboardingMetadata,
|
||||
}),
|
||||
],
|
||||
);
|
||||
} catch (metaErr) {
|
||||
console.error("Onboarding metadata save failed (non-fatal):", metaErr);
|
||||
}
|
||||
|
||||
// 4. Insert Workspace Row (logical multi-tenancy)
|
||||
const insertedWorkspaces = await query<VibnWorkspace>(
|
||||
`INSERT INTO vibn_workspaces (slug, name, owner_user_id, data, provision_status)
|
||||
VALUES ($1, $2, $3, $4, 'pending')
|
||||
RETURNING *`,
|
||||
[
|
||||
slug,
|
||||
businessName,
|
||||
userId,
|
||||
JSON.stringify({ onboarding: onboardingMetadata }),
|
||||
],
|
||||
);
|
||||
const workspace = insertedWorkspaces[0];
|
||||
// 4. Rename the user's existing workspace, or create one if (unexpectedly)
|
||||
// none exists yet.
|
||||
let workspace: VibnWorkspace | undefined;
|
||||
const existing = await getWorkspaceByOwner(userId);
|
||||
|
||||
if (existing) {
|
||||
const slug = await generateUniqueSlug(businessName, existing.id);
|
||||
const rows = await query<VibnWorkspace>(
|
||||
`UPDATE vibn_workspaces
|
||||
SET name = $2, slug = $3, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[existing.id, businessName, slug],
|
||||
);
|
||||
workspace = rows[0];
|
||||
} else {
|
||||
const slug = await generateUniqueSlug(businessName);
|
||||
const rows = await query<VibnWorkspace>(
|
||||
`INSERT INTO vibn_workspaces (slug, name, owner_user_id)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *`,
|
||||
[slug, businessName, userId],
|
||||
);
|
||||
workspace = rows[0];
|
||||
await query(
|
||||
`INSERT INTO vibn_workspace_members (workspace_id, user_id, role)
|
||||
VALUES ($1, $2, 'owner')
|
||||
ON CONFLICT (workspace_id, user_id) DO NOTHING`,
|
||||
[workspace.id, userId],
|
||||
);
|
||||
}
|
||||
|
||||
if (!workspace) {
|
||||
return NextResponse.json(
|
||||
@@ -102,15 +144,7 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
// 5. Insert Workspace Member Row (link user as Owner)
|
||||
await query(
|
||||
`INSERT INTO vibn_workspace_members (workspace_id, user_id, role)
|
||||
VALUES ($1, $2, 'owner')`,
|
||||
[workspace.id, userId],
|
||||
);
|
||||
|
||||
// 6. Trigger Async Tenant Provisioning (Coolify Project boundaries + Gitea org)
|
||||
// Runs in the background so the user's isolated fleet stands up instantly.
|
||||
// 5. Kick off provisioning in the background (Coolify project + Gitea org).
|
||||
try {
|
||||
ensureWorkspaceProvisioned(workspace).catch((err: unknown) => {
|
||||
console.error("Background workspace provisioning failed:", err);
|
||||
@@ -119,8 +153,7 @@ export async function POST(request: Request) {
|
||||
console.error("Failed to kick off provisioning:", e);
|
||||
}
|
||||
|
||||
// Return the workspace slug so the frontend can redirect they immediately!
|
||||
return NextResponse.json({ success: true, slug });
|
||||
return NextResponse.json({ success: true, slug: workspace.slug });
|
||||
} catch (err) {
|
||||
console.error("Onboarding GTM save exception:", err);
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -39,13 +39,15 @@ export async function GET(request: Request) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const userRow = await queryOne<{ id: string }>(
|
||||
`SELECT id FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
|
||||
const userRow = await queryOne<{ id: string; onboarded: string | null }>(
|
||||
`SELECT id, data->>'onboardingComplete' AS onboarded
|
||||
FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
|
||||
[session.user.email],
|
||||
);
|
||||
if (!userRow) {
|
||||
return NextResponse.json({ workspaces: [] });
|
||||
return NextResponse.json({ workspaces: [], onboarded: false });
|
||||
}
|
||||
const onboarded = userRow.onboarded === "true";
|
||||
|
||||
// Migration path: users who signed in before the signIn hook was
|
||||
// added (or before vibn_workspaces existed) have no row yet. Create
|
||||
@@ -104,10 +106,14 @@ export async function GET(request: Request) {
|
||||
return NextResponse.json({
|
||||
workspaces: list.map(serializeWorkspace),
|
||||
defaultToken,
|
||||
onboarded,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ workspaces: list.map(serializeWorkspace) });
|
||||
return NextResponse.json({
|
||||
workspaces: list.map(serializeWorkspace),
|
||||
onboarded,
|
||||
});
|
||||
}
|
||||
|
||||
function serializeWorkspace(w: import("@/lib/workspaces").VibnWorkspace) {
|
||||
|
||||
Reference in New Issue
Block a user