Files

64 lines
1.7 KiB
TypeScript

import * as z from 'zod';
import { auth } from '~~/lib/auth';
/**
* Creates an account for someone, without a password. Nobody can sign in to
* it until its owner opens the setup link returned here and picks one, so the
* admin never knows a password of theirs. The link is only returned here.
*/
export default defineEventHandler(async (event) => {
await protectAdminRoute(event);
const result = await readValidatedBody(event, (body) =>
z
.object({
name: z.string().trim().min(1).max(128),
email: z.email(),
})
.safeParse(body),
);
if (!result.success) {
throw createError({
statusCode: 400,
message: result.error.issues[0]!.message,
data: {
code: 'INVALID_BODY',
},
});
}
const { name, email } = result.data;
let userId: string;
try {
// called without the request, the admin check already happened above
const { user } = await auth.api.createUser({
body: {
name,
email,
role: 'user',
},
});
userId = user.id;
} catch (error: any) {
const code = error?.body?.code as string | undefined;
if (code === undefined) {
console.error('Failed to create user:', error);
}
throw createError({
statusCode: code === undefined ? 500 : 400,
statusMessage: 'Failed to create user',
data: {
code: code ?? 'INTERNAL_ERROR',
},
});
}
return await createRecoveryLink(userId, false);
});