first
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import type { Handler } from 'hono';
|
||||
import { officerdb, count, Users } from 'officerdb';
|
||||
import { sign } from '@@/jwt';
|
||||
import { 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 result = await officerdb.select({ count: count() }).from(Users);
|
||||
const userCount = result[0]?.count ?? 0;
|
||||
if (userCount > 0) throw errors.FORBIDDEN('Registration is closed');
|
||||
|
||||
const newUser = {
|
||||
email: body.email as string,
|
||||
status: 'Unverified' as (typeof USER_STATUSES)[number],
|
||||
role: 'Admin' as (typeof USER_ROLES)[number],
|
||||
};
|
||||
|
||||
const insertedUsers = await officerdb.insert(Users).values(newUser).returning();
|
||||
if (!insertedUsers || insertedUsers.length === 0) throw errors.INTERNAL_SERVER_ERROR('Failed to create user');
|
||||
const dbUser = insertedUsers[0]!;
|
||||
|
||||
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 account',
|
||||
to: dbUser.email,
|
||||
data: { name: dbUser.email, url },
|
||||
});
|
||||
|
||||
return ctx.json({ ok: true, user: { id: dbUser.id, email: dbUser.email } });
|
||||
};
|
||||
Reference in New Issue
Block a user