37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
import type { Handler } from 'hono';
|
|
import { getUserCount, createUser } from 'officerdb';
|
|
import { sign } from '@@/jwt';
|
|
import type { USER_ROLES, USER_STATUSES } from 'definitions';
|
|
import * as errors from '@@/custom-errors';
|
|
import { sendMail } from 'emailer';
|
|
|
|
export const signupHandler: Handler = async function (ctx) {
|
|
const body = ctx.get('body');
|
|
const origin = ctx.get('origin');
|
|
|
|
if (!body.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(body.email)) {
|
|
throw errors.BAD_REQUEST('Invalid email address');
|
|
}
|
|
|
|
const userCount = getUserCount();
|
|
if (userCount > 0) throw errors.FORBIDDEN('Registration is closed');
|
|
|
|
const dbUser = await createUser({
|
|
email: body.email as string,
|
|
status: 'Unverified' as (typeof USER_STATUSES)[number],
|
|
role: 'Admin' as (typeof USER_ROLES)[number],
|
|
});
|
|
|
|
const verificationCode = await sign({ id: dbUser.id, email: dbUser.email }, '24h');
|
|
const url = `${origin}/auth/verify?verificationCode=${verificationCode}`;
|
|
|
|
await sendMail({
|
|
template: 'VerifyAdmin',
|
|
subject: 'Verify your officer.dev account',
|
|
to: dbUser.email,
|
|
data: { name: dbUser.email, url },
|
|
});
|
|
|
|
return ctx.json({ ok: true, user: { id: dbUser.id, email: dbUser.email } });
|
|
};
|