Files
CatoandClaude Opus 5.5 ebe51fa38e feat(auth): every way in on AccountKit's own screens (#289)
* feat(auth): every way in on AccountKit's own screens

Botsmann signed people in against OrangeCat's GoTrue (auth.users). It now
runs on AccountKit (@bitbaum/accountkit 0.23) with AccountKit's own forms:
/auth/signin offers email and password, an emailed sign-in link, a
passkey, recovery through the mailed link and the second factor;
/auth/signup is sign-up; /account carries the account panel ("Sign-in and
security" in the account menu). "Continue with OrangeCat" and the shared
sign-in show when their clients are set, the link and recovery when mail
is. The GoTrue routes (/api/auth/signin, signup, forgot-password,
resend-verification, profile) and pages (callback, forgot-password,
reset-password, verify-email) and the cookie-session client are gone.

AccountKit's tables live in a host accounts database (drizzle/, loki
accounts-db.conf); the data stays in the botsmann supabase schema, which
every route already read with the service-role client. verifyUser now reads
AccountKit's session; /api/user/profile moves onto it too. New accounts get
uuid ids, and migration 013 drops the person columns' keys to auth.users,
which a new person's id is not in. Nothing is deleted. The profile editor
writes AccountKit's name and image.

Existing people keep their rows: scripts/db/accountkit-people.sql lists
everyone who owns rows with their OrangeCat actor id, and
scripts/db/accountkit-import.sql gives each an account under the same id,
linked to OrangeCat by that actor id, never by address (loki
accountkit-supabase.yml rehearses it rolled back, then imports).

Pages were served with public, max-age=3600 to every browser, account pages
included: after sign-out the browser showed its cached /account. /account
and /auth/* are now private, no-store. The account menu's trigger has a name.

tests/__tests__/accounts runs the ways in and the import on the committed
migration; browser-smoke.yml's account job rehearses the import and runs
the browser journey against the production build with AccountKit's real
mail caught by a sink.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* fix(auth): send a signed-out visitor to sign in with the router

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* ci(auth): the shared sign-in's button is matched by how it starts

AccountKit 0.24 names only the providers Morulia publishes, so the label
changes with Morulia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* ci(auth): expect the shared sign-in only once Morulia publishes a provider

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* ci: run the checks on the journey change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-02 23:27:16 +01:00

141 lines
4.3 KiB
TypeScript

/**
* User Profile API Route
*
* GET /api/user/profile - Get or create user profile from user_profiles table
* PATCH /api/user/profile - Update user profile preferences
*
* The person comes from AccountKit's session (verifyUser); the row is read with
* the service-role client and scoped to their id. This route manages the
* user_profiles table for domain preferences and stats.
*/
import { type NextRequest } from 'next/server';
import { getServiceClient } from '@/lib/supabase';
import { verifyUser } from '@/lib/api-utils';
import {
jsonSuccess,
jsonError,
jsonUnauthorized,
validateBody,
hasValidationError,
HTTP_STATUS,
} from '@/lib/api/responses';
import { UpdateUserProfileSchema } from '@/lib/validations/user-profile';
import { logger } from '@/lib/logger';
/**
* GET - Get or create user profile
* Uses the ensure_user_profile database function to create if doesn't exist
*/
export async function GET(request: NextRequest) {
try {
const user = await verifyUser(request);
if (!user) {
return jsonUnauthorized();
}
const supabase = getServiceClient();
// Call database function to get or create profile
const { data: profile, error: profileError } = await supabase.rpc('ensure_user_profile', {
p_user_id: user.id,
});
if (profileError) {
logger.error('Error fetching user profile:', profileError);
return jsonError('Failed to fetch profile', 'DATABASE_ERROR', HTTP_STATUS.INTERNAL_ERROR);
}
return jsonSuccess(profile);
} catch (error) {
logger.error('User profile GET error:', error);
return jsonError('An error occurred', 'INTERNAL_ERROR', HTTP_STATUS.INTERNAL_ERROR);
}
}
/**
* PATCH - Update user profile
*/
export async function PATCH(request: NextRequest) {
try {
const user = await verifyUser(request);
if (!user) {
return jsonUnauthorized();
}
const supabase = getServiceClient();
// Validate request body
const validation = await validateBody(request, UpdateUserProfileSchema);
if (hasValidationError(validation)) {
return validation.error;
}
const updates = validation.data;
// Build update object (only include provided fields)
const updateData: Record<string, unknown> = {};
if (updates.display_name !== undefined) {
updateData.display_name = updates.display_name;
}
if (updates.preferred_language !== undefined) {
updateData.preferred_language = updates.preferred_language;
}
if (updates.timezone !== undefined) {
updateData.timezone = updates.timezone;
}
if (updates.active_domains !== undefined) {
updateData.active_domains = updates.active_domains;
}
// Update profile
const { data: profile, error: updateError } = await supabase
.from('user_profiles')
.update(updateData)
.eq('id', user.id)
.select()
.single();
if (updateError) {
// If profile doesn't exist, create it first then update
if (updateError.code === 'PGRST116') {
// No rows returned - profile doesn't exist
const { error: insertError } = await supabase.from('user_profiles').insert({
id: user.id,
...updateData,
});
if (insertError) {
logger.error('Error creating user profile:', insertError);
return jsonError(
'Failed to create profile',
'DATABASE_ERROR',
HTTP_STATUS.INTERNAL_ERROR,
);
}
// Fetch the created profile
const { data: newProfile, error: fetchError } = await supabase
.from('user_profiles')
.select()
.eq('id', user.id)
.single();
if (fetchError) {
logger.error('Error fetching created profile:', fetchError);
return jsonError('Failed to fetch profile', 'DATABASE_ERROR', HTTP_STATUS.INTERNAL_ERROR);
}
return jsonSuccess(newProfile, 'Profile created');
}
logger.error('Error updating user profile:', updateError);
return jsonError('Failed to update profile', 'DATABASE_ERROR', HTTP_STATUS.INTERNAL_ERROR);
}
return jsonSuccess(profile, 'Profile updated');
} catch (error) {
logger.error('User profile PATCH error:', error);
return jsonError('An error occurred', 'INTERNAL_ERROR', HTTP_STATUS.INTERNAL_ERROR);
}
}