62 lines
2.3 KiB
TypeScript
62 lines
2.3 KiB
TypeScript
import useDatabase from '~/composables/useDatabase';
|
|
import { schema } from '~/schemas/registration';
|
|
|
|
export default defineEventHandler(async (e) => {
|
|
try
|
|
{
|
|
const { sessionPassword } = useRuntimeConfig();
|
|
const body = await readValidatedBody(e, schema.safeParse);
|
|
|
|
if (!body.success)
|
|
{
|
|
setResponseStatus(e, 406);
|
|
return { success: false, error: body.error };
|
|
}
|
|
|
|
const db = useDatabase();
|
|
|
|
const usernameQuery = db.query(`SELECT COUNT(*) as count FROM users WHERE username = ?1`);
|
|
const checkUsername = usernameQuery.get(body.data.username) as any;
|
|
|
|
const emailQuery = db.query(`SELECT COUNT(*) as count FROM users WHERE email = ?1`);
|
|
const checkEmail = emailQuery.get(body.data.email) as any;
|
|
|
|
const errors = [];
|
|
if(checkUsername.count !== 0)
|
|
errors.push({ path: ['username'], message: "Ce nom d'utilisateur est déjà utilisé" });
|
|
if(checkEmail.count !== 0)
|
|
errors.push({ path: ['email'], message: "Cette adresse mail est déjà utilisée" });
|
|
|
|
if(errors.length > 0)
|
|
{
|
|
setResponseStatus(e, 406);
|
|
return { success: false, error: errors };
|
|
}
|
|
else
|
|
{
|
|
const hash = await Bun.password.hash(body.data.password);
|
|
const registration = db.query(`INSERT INTO users(username, email, hash, email_valid) VALUES(?1, ?2, ?3, 0)`);
|
|
registration.get(body.data.username, body.data.email, hash) as any;
|
|
|
|
const userIdQuery = db.query(`SELECT id FROM users WHERE username = ?1`);
|
|
const id = (userIdQuery.get(body.data.username) as any).id;
|
|
|
|
const registeringData = db.query(`INSERT INTO users_data(user_id) VALUES(?1)`);
|
|
registeringData.get(id);
|
|
|
|
const session = await useSession(e, {
|
|
password: sessionPassword,
|
|
});
|
|
|
|
const loggingIn = db.query(`INSERT INTO user_sessions(id, user_id, ip, agent, lastRefresh) VALUES(?1, ?2, ?3, ?4, ?5)`);
|
|
loggingIn.get(session.id, id, getRequestIP(e), getRequestHeader(e, 'User-Agent'), Date.now());
|
|
|
|
setResponseStatus(e, 201);
|
|
return { success: true, id: id, sessionId: session.id };
|
|
}
|
|
}
|
|
catch(e)
|
|
{
|
|
return { success: false, error: e };
|
|
}
|
|
}); |