2ee99ea463
Root cause of "still cannot find users": username was optional in better-auth's schema and no signup form or settings page ever set it, but search/profile/follow all key on username, not user id. Every account now gets a unique one auto-generated (from name/email) in the user.create.before hook — covers email/password and OAuth signups. Added a one-off db:backfill-usernames script for accounts created before this fix and ran it against the current database. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
34 lines
1.1 KiB
TypeScript
34 lines
1.1 KiB
TypeScript
import { db, users, eq } from "@epicure/db";
|
|
|
|
/** Lowercase alnum-and-underscore slug, at least 3 chars, at most 20. */
|
|
function slugify(seed: string): string {
|
|
const base = seed
|
|
.split("@")[0]! // if seed is an email, drop the domain
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9_]/g, "")
|
|
.slice(0, 20);
|
|
return base.length >= 3 ? base : `${base}user`.slice(0, 20);
|
|
}
|
|
|
|
/**
|
|
* Every user needs a username — it's the only thing profile pages, follows,
|
|
* and people-search key on, but there's no signup-time or settings UI to set
|
|
* one. Called from the user.create.before hook (lib/auth/server.ts) so every
|
|
* account gets one automatically, generated from their name or email.
|
|
*/
|
|
export async function generateUniqueUsername(seed: string): Promise<string> {
|
|
const base = slugify(seed);
|
|
let candidate = base;
|
|
let suffix = 0;
|
|
|
|
while (true) {
|
|
const existing = await db.query.users.findFirst({
|
|
where: eq(users.username, candidate),
|
|
columns: { id: true },
|
|
});
|
|
if (!existing) return candidate;
|
|
suffix += 1;
|
|
candidate = `${base}${suffix}`.slice(0, 20);
|
|
}
|
|
}
|