Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from "~/utils/encryption";
import { parseUA, DEVICE_SALT_COOKIE_NAME } from "~/utils/devices";
import { normalizeEmail } from "~/utils/email";
import { isRunningInDocker } from "~/utils/docker";
import { sendMailWithTemplate } from "~/utils/mail";
import { MailTemplateKey } from "~/utils/enums";
import { parse } from "cookie";
Expand Down Expand Up @@ -516,6 +517,24 @@ export async function onUserCreateBefore(
};
}

// Keep Better Auth-created users consistent with users created through
// ztnet's regular registration flow, which creates UserOptions eagerly.
export async function onUserCreateAfter(user: Record<string, unknown>): Promise<void> {
if (typeof user.id !== "string" || !user.id) {
throw new Error("Cannot create UserOptions: user ID is missing");
}

const localControllerUrl = isRunningInDocker()
? "http://zerotier:9993"
: "http://127.0.0.1:9993";

await prisma.userOptions.upsert({
where: { userId: user.id },
update: {},
create: { userId: user.id, localControllerUrl },
});
}

export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "postgresql",
Expand Down Expand Up @@ -608,6 +627,7 @@ export const auth = betterAuth({
user: {
create: {
before: onUserCreateBefore,
after: onUserCreateAfter,
},
},
session: {
Expand Down
17 changes: 16 additions & 1 deletion src/server/api/routers/authRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,10 +382,25 @@ export const authRouter = createTRPCRouter({
UserDevice?: UserDevice[];
currentDeviceId?: string;
};
user.options.localControllerUrlPlaceholder = isRunningInDocker()
const localControllerUrl = isRunningInDocker()
? "http://zerotier:9993"
: "http://127.0.0.1:9993";

// OAuth users created before UserOptions was added to the Better Auth
// creation hook may not have an options row. Backfill it on first access.
if (!user.options) {
user.options = await ctx.prisma.userOptions.upsert({
where: { userId: user.id },
update: {},
create: {
userId: user.id,
localControllerUrl,
},
});
}

user.options.localControllerUrlPlaceholder = localControllerUrl;

// Set secret environment status
user.options.urlFromEnv = !!process.env.ZT_ADDR;
user.options.secretFromEnv = !!process.env.ZT_SECRET;
Expand Down
Loading