mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 11:07:40 +01:00
fix(auth): heal onboarding for returning users with stale JWT cookies
Migrated/returning users with existing projects were stuck on /onboarding because their JWT cookie carried onboardedAt=null even though the DB had project data. The middleware then bounced them back every navigation. Heal them transparently in three places that all share the same primitive: - events.signIn: backfill username + onboardedAt when DB shows projects - jwt callback: re-heal on every refresh and carry onboardingComplete - /api/onboarding GET/POST: heal-on-read so a stale cookie self-corrects Onboarding page now calls session.update() on mount to sync JWT from DB, and auto-finishes for returning users instead of forcing them through the username step a second time. Session helpers gain resolveSessionUserId(): when JWT carries an OAuth provider id instead of our UUID, fall back to email lookup so getUserById queries don't poison API routes with invalid-uuid errors.
This commit is contained in:
8 files changed
+178
-28
No files matched your search
@@ -6,6 +6,8 @@ import { getRuntimeSnapshot } from "@/db/queries/runtime-snapshots";
|
||||
import { getProjectStatesByUserId } from "@/db/queries/project-states";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { hasValidUsername, isOnboardingComplete, suggestUsername } from "@/lib/onboarding";
|
||||
import { healReturningUserOnboarding } from "@/lib/onboarding-heal";
|
||||
import { countActiveProjects } from "@/db/queries/user-projects";
|
||||
|
||||
async function getDaemonConnectionStatus(userId: string) {
|
||||
const [snapshot, states] = await Promise.all([
|
||||
@@ -29,25 +31,33 @@ export async function GET() {
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const user = await getUserById(userId);
|
||||
let user = await getUserById(userId);
|
||||
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const [teamInvitee, daemon] = await Promise.all([
|
||||
user = await healReturningUserOnboarding(user);
|
||||
|
||||
const [teamInvitee, daemon, projectCount] = await Promise.all([
|
||||
isTeamInvitee(userId),
|
||||
isRuntimeAvailable()
|
||||
? Promise.resolve({ connected: true, live: true, lastPushedAt: new Date().toISOString() })
|
||||
: getDaemonConnectionStatus(userId),
|
||||
countActiveProjects(userId),
|
||||
]);
|
||||
|
||||
const complete = isOnboardingComplete(user);
|
||||
|
||||
return NextResponse.json({
|
||||
complete: isOnboardingComplete(user),
|
||||
complete,
|
||||
username: user.username,
|
||||
suggestedUsername: suggestUsername(user.name, user.email),
|
||||
isTeamInvitee: teamInvitee,
|
||||
isReturningUser: projectCount > 0,
|
||||
runtimeAvailable: isRuntimeAvailable(),
|
||||
daemonConnected: daemon.connected,
|
||||
daemonLive: daemon.live,
|
||||
daemonLastPushedAt: daemon.lastPushedAt,
|
||||
/** Client should call session.update() when true so middleware JWT catches up. */
|
||||
needsSessionRefresh: complete,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -55,9 +65,11 @@ export async function POST() {
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const user = await getUserById(userId);
|
||||
let user = await getUserById(userId);
|
||||
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
user = await healReturningUserOnboarding(user);
|
||||
|
||||
if (!hasValidUsername(user.username)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Choose a username before finishing onboarding." },
|
||||
|
||||
@@ -29,6 +29,8 @@ type OnboardingBootstrap = {
|
||||
complete?: boolean;
|
||||
suggestedUsername?: string;
|
||||
isTeamInvitee?: boolean;
|
||||
isReturningUser?: boolean;
|
||||
needsSessionRefresh?: boolean;
|
||||
};
|
||||
|
||||
function stepIndex(step: OnboardingStep): number {
|
||||
@@ -52,22 +54,48 @@ export default function OnboardingPage() {
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
getJson<OnboardingBootstrap>("/api/onboarding")
|
||||
.then((data) => {
|
||||
let cancelled = false;
|
||||
|
||||
async function bootstrap() {
|
||||
try {
|
||||
// Sync JWT from DB (fixes migrated accounts with stale cookies).
|
||||
await update();
|
||||
const data = await getJson<OnboardingBootstrap>("/api/onboarding");
|
||||
if (cancelled) return;
|
||||
|
||||
if (data.complete) {
|
||||
if (data.needsSessionRefresh) await update();
|
||||
router.replace(ROUTES.APP_HOME);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.isReturningUser) {
|
||||
await postJson("/api/onboarding", {});
|
||||
await update();
|
||||
router.replace(ROUTES.APP_HOME);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.suggestedUsername) {
|
||||
setUsername((prev) => prev || data.suggestedUsername || "");
|
||||
}
|
||||
if (data.isTeamInvitee) {
|
||||
setIsTeamInvitee(true);
|
||||
}
|
||||
})
|
||||
.catch(() => { /* stay on page */ })
|
||||
.finally(() => setBootstrapping(false));
|
||||
}, [router]);
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
setError(e instanceof Error ? e.message : "Could not load onboarding");
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setBootstrapping(false);
|
||||
}
|
||||
}
|
||||
|
||||
void bootstrap();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [router, update]);
|
||||
|
||||
async function finishOnboarding() {
|
||||
setSaving(true);
|
||||
|
||||
+4
-1
@@ -19,7 +19,10 @@ export default async function LandingPage() {
|
||||
|
||||
const session = await auth();
|
||||
if (session?.user) {
|
||||
redirect(session.user.onboardedAt ? ROUTES.APP_HOME : ROUTES.ONBOARDING);
|
||||
const done =
|
||||
session.user.onboardingComplete === true ||
|
||||
Boolean(session.user.onboardedAt && session.user.username);
|
||||
redirect(done ? ROUTES.APP_HOME : ROUTES.ONBOARDING);
|
||||
}
|
||||
|
||||
const stripeReady = isStripeReady();
|
||||
|
||||
+14
-1
@@ -1,6 +1,15 @@
|
||||
import type { NextAuthConfig } from "next-auth";
|
||||
import { ROUTES } from "@/config/auth";
|
||||
|
||||
function sessionOnboardingDone(user: {
|
||||
onboardingComplete?: boolean;
|
||||
onboardedAt?: Date | string | null;
|
||||
username?: string | null;
|
||||
}): boolean {
|
||||
if (user.onboardingComplete === true) return true;
|
||||
return Boolean(user.onboardedAt && user.username);
|
||||
}
|
||||
|
||||
// Edge-safe auth config — no DB adapter, no Node.js crypto.
|
||||
// Used by src/middleware.ts (Edge Runtime).
|
||||
// Full auth with DB adapter lives in src/auth.ts.
|
||||
@@ -16,7 +25,9 @@ export const authConfig = {
|
||||
// The jwt() callback in auth.ts stores this field on every sign-in/token refresh.
|
||||
session({ session, token }) {
|
||||
if (session.user) {
|
||||
session.user.username = (token.username as string | null) ?? null;
|
||||
session.user.onboardedAt = (token.onboardedAt as Date | null) ?? null;
|
||||
session.user.onboardingComplete = token.onboardingComplete === true;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
@@ -63,8 +74,10 @@ export const authConfig = {
|
||||
// Redirect authenticated-but-not-onboarded users to the onboarding flow.
|
||||
// API routes are excluded so onboarding page API calls (/api/me, /api/user-projects)
|
||||
// work normally. Sign-out is excluded to avoid a redirect loop on logout.
|
||||
// Gate until onboarding is complete in JWT (refreshed from DB on sign-in / session.update).
|
||||
const onboardingDone = sessionOnboardingDone(auth.user);
|
||||
if (
|
||||
!auth.user.onboardedAt &&
|
||||
!onboardingDone &&
|
||||
!pathname.startsWith(ROUTES.ONBOARDING) &&
|
||||
!pathname.startsWith("/api/") &&
|
||||
!pathname.startsWith(ROUTES.SIGN_OUT)
|
||||
|
||||
+31
-8
@@ -13,6 +13,8 @@ import { verifyPassword } from "@/lib/password";
|
||||
import { getDefaultUser, getUserById, getUserByEmail, updateUser } from "@/db/queries/users";
|
||||
import { getOrgMembershipCount, createPersonalOrg } from "@/db/queries/orgs";
|
||||
import { logDebug } from "@/db/queries/debug-logs";
|
||||
import { healReturningUserOnboarding, onboardingCompleteFlag } from "@/lib/onboarding-heal";
|
||||
import { isValidUuid } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Auth.js wraps every authorize()→null return in a generic CredentialsSignin
|
||||
@@ -64,10 +66,17 @@ declare module "next-auth" {
|
||||
image: string | null;
|
||||
username: string | null;
|
||||
onboardedAt: Date | null;
|
||||
onboardingComplete?: boolean;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
declare module "@auth/core/jwt" {
|
||||
interface JWT {
|
||||
onboardingComplete?: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
adapter: DrizzleAdapter(db, {
|
||||
@@ -150,6 +159,11 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
// queries that join on uuid columns are safe.
|
||||
try {
|
||||
if (message.user?.id) {
|
||||
const existing = await getUserById(message.user.id);
|
||||
if (existing) {
|
||||
await healReturningUserOnboarding(existing);
|
||||
}
|
||||
|
||||
const memberCount = await getOrgMembershipCount(message.user.id);
|
||||
if (memberCount === 0) {
|
||||
const displayName = message.user.name ?? message.user.email?.split("@")[0] ?? "user";
|
||||
@@ -290,15 +304,23 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
}
|
||||
return true;
|
||||
},
|
||||
async jwt({ token, user, trigger }) {
|
||||
async jwt({ token, user }) {
|
||||
const email = user?.email ?? (token.email as string | undefined);
|
||||
const userId = user?.id ?? (token.id as string | undefined);
|
||||
if (userId && (user?.id || trigger === "update")) {
|
||||
token.id = userId;
|
||||
const dbUser = await getUserById(userId);
|
||||
if (dbUser) {
|
||||
token.username = dbUser.username ?? null;
|
||||
token.onboardedAt = dbUser.onboardedAt ?? null;
|
||||
}
|
||||
|
||||
let dbUser = userId && isValidUuid(userId) ? await getUserById(userId) : null;
|
||||
if (!dbUser && email) {
|
||||
dbUser = await getUserByEmail(email);
|
||||
}
|
||||
if (dbUser) {
|
||||
dbUser = await healReturningUserOnboarding(dbUser);
|
||||
token.id = dbUser.id;
|
||||
token.email = dbUser.email ?? email ?? null;
|
||||
token.username = dbUser.username ?? null;
|
||||
token.onboardedAt = dbUser.onboardedAt ?? null;
|
||||
token.onboardingComplete = onboardingCompleteFlag(dbUser);
|
||||
} else if (email) {
|
||||
token.email = email;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
@@ -310,6 +332,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
id: (token.id as string) ?? "",
|
||||
username: (token.username as string | null) ?? null,
|
||||
onboardedAt: (token.onboardedAt as Date | null) ?? null,
|
||||
onboardingComplete: token.onboardingComplete === true,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { countActiveProjects } from "@/db/queries/user-projects";
|
||||
import { getUserByUsername, updateUser } from "@/db/queries/users";
|
||||
import type { users } from "@/db/schema";
|
||||
import {
|
||||
hasValidUsername,
|
||||
isOnboardingComplete,
|
||||
suggestUsername,
|
||||
} from "@/lib/onboarding";
|
||||
|
||||
type UserRow = typeof users.$inferSelect;
|
||||
|
||||
/**
|
||||
* Returning / migrated users: skip onboarding when they already have app data.
|
||||
* Sets username + onboarded_at when missing so JWT + middleware can unblock.
|
||||
*/
|
||||
export async function healReturningUserOnboarding(user: UserRow): Promise<UserRow> {
|
||||
const projectCount = await countActiveProjects(user.id);
|
||||
const isReturning = projectCount > 0 || user.onboardedAt != null;
|
||||
if (!isReturning) return user;
|
||||
|
||||
let username = user.username;
|
||||
if (!hasValidUsername(username)) {
|
||||
const suggested = suggestUsername(user.name, user.email);
|
||||
if (suggested) {
|
||||
const taken = await getUserByUsername(suggested);
|
||||
if (!taken || taken.id === user.id) username = suggested;
|
||||
}
|
||||
}
|
||||
|
||||
const needsUsername = !hasValidUsername(user.username) && hasValidUsername(username);
|
||||
const needsOnboarded = user.onboardedAt == null;
|
||||
|
||||
if (!needsUsername && !needsOnboarded) return user;
|
||||
|
||||
const updated = await updateUser(user.id, {
|
||||
...(needsUsername && username ? { username } : {}),
|
||||
...(needsOnboarded ? { onboardedAt: new Date() } : {}),
|
||||
});
|
||||
return updated ?? user;
|
||||
}
|
||||
|
||||
export function onboardingCompleteFlag(user: {
|
||||
username: string | null | undefined;
|
||||
onboardedAt: Date | null | undefined;
|
||||
}): boolean {
|
||||
return isOnboardingComplete(user);
|
||||
}
|
||||
+31
-7
@@ -4,7 +4,32 @@ import { auth } from "@/auth";
|
||||
import { DEFAULT_USER_NAME } from "@/lib/constants";
|
||||
import { ROUTES } from "@/config/auth";
|
||||
import { validateAgentToken } from "@/db/queries/agent-tokens";
|
||||
import { getUserByEmail, getUserById } from "@/db/queries/users";
|
||||
import { envAlias, envAliasBool } from "@/lib/brand-env";
|
||||
import { isValidUuid } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Resolve the DB user id from a session. OAuth JWTs may briefly carry the
|
||||
* provider id instead of our UUID — fall back to email lookup.
|
||||
*/
|
||||
export async function resolveSessionUserId(): Promise<string | null> {
|
||||
const session = await auth();
|
||||
if (!session?.user) return null;
|
||||
|
||||
const id = session.user.id;
|
||||
if (id && isValidUuid(id)) {
|
||||
const byId = await getUserById(id);
|
||||
if (byId) return byId.id;
|
||||
}
|
||||
|
||||
const email = session.user.email;
|
||||
if (email) {
|
||||
const byEmail = await getUserByEmail(email);
|
||||
if (byEmail) return byEmail.id;
|
||||
}
|
||||
|
||||
return id && isValidUuid(id) ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the authenticated user's ID, or null if there is no session.
|
||||
@@ -12,8 +37,7 @@ import { envAlias, envAliasBool } from "@/lib/brand-env";
|
||||
* Middleware already blocks browser clients without a session — this is defense-in-depth.
|
||||
*/
|
||||
export async function getSessionUserId(): Promise<string | null> {
|
||||
const session = await auth();
|
||||
return session?.user?.id ?? null;
|
||||
return resolveSessionUserId();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -22,9 +46,9 @@ export async function getSessionUserId(): Promise<string | null> {
|
||||
* Use in server components and server actions.
|
||||
*/
|
||||
export async function requirePageUserId(): Promise<string> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect(ROUTES.SIGN_IN);
|
||||
return session.user.id;
|
||||
const userId = await resolveSessionUserId();
|
||||
if (!userId) redirect(ROUTES.SIGN_IN);
|
||||
return userId;
|
||||
}
|
||||
|
||||
export async function getCurrentUserName(): Promise<string> {
|
||||
@@ -44,8 +68,8 @@ let warnedDeprecatedDaemonToken = false;
|
||||
*/
|
||||
export async function getApiUserId(): Promise<string | null> {
|
||||
// Cookie-based session (web UI).
|
||||
const session = await auth();
|
||||
if (session?.user?.id) return session.user.id;
|
||||
const userId = await resolveSessionUserId();
|
||||
if (userId) return userId;
|
||||
|
||||
// Bearer token (daemon / CLI agent).
|
||||
const headersList = await headers();
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import { authConfig } from "@/auth.config";
|
||||
//
|
||||
// What this activates:
|
||||
// • Unauthenticated users → redirect to /sign-in with callbackUrl
|
||||
// • Authenticated + onboardedAt null → redirect to /onboarding
|
||||
// • Authenticated + onboarding incomplete → redirect to /onboarding
|
||||
// • Daemon bearer-token requests → pass through to individual routes
|
||||
//
|
||||
// The matcher intentionally excludes public routes so they stay accessible
|
||||
|
||||
Reference in new issue
Block a user