fix: revise register

This commit is contained in:
abiyasa05 2024-08-14 10:36:14 +07:00
parent e6d5f61c70
commit 02961782e7

View File

@ -3,19 +3,19 @@ import { HTTPException } from "hono/http-exception";
import db from "../../drizzle"; import db from "../../drizzle";
import { respondents } from "../../drizzle/schema/respondents"; import { respondents } from "../../drizzle/schema/respondents";
import { users } from "../../drizzle/schema/users"; import { users } from "../../drizzle/schema/users";
import { rolesSchema } from "../../drizzle/schema/roles";
import { rolesToUsers } from "../../drizzle/schema/rolesToUsers"; import { rolesToUsers } from "../../drizzle/schema/rolesToUsers";
import { hashPassword } from "../../utils/passwordUtils"; import { hashPassword } from "../../utils/passwordUtils";
import requestValidator from "../../utils/requestValidator"; import requestValidator from "../../utils/requestValidator";
import authInfo from "../../middlewares/authInfo"; import authInfo from "../../middlewares/authInfo";
import checkPermission from "../../middlewares/checkPermission"; import { or, eq } from "drizzle-orm";
import { and, eq, or } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import HonoEnv from "../../types/HonoEnv"; import HonoEnv from "../../types/HonoEnv";
const registerFormSchema = z.object({ const registerFormSchema = z.object({
name: z.string().min(1).max(255), name: z.string().min(1).max(255),
username: z.string().min(1).max(255), username: z.string().min(1).max(255),
email: z.string().email().optional(), email: z.string().email(),
password: z.string().min(6), password: z.string().min(6),
companyName: z.string().min(1).max(255), companyName: z.string().min(1).max(255),
position: z.string().min(1).max(255), position: z.string().min(1).max(255),
@ -23,36 +23,15 @@ const registerFormSchema = z.object({
address: z.string().min(1), address: z.string().min(1),
phoneNumber: z.string().min(1).max(13), phoneNumber: z.string().min(1).max(13),
isEnabled: z.string().default("false"), isEnabled: z.string().default("false"),
roles: z
.string()
.refine(
(data) => {
try {
const parsed = JSON.parse(data);
return Array.isArray(parsed);
} catch {
return false;
}
},
{
message: "Roles must be an array",
}
)
.optional(),
}); });
const respondentsRoute = new Hono<HonoEnv>() const respondentsRoute = new Hono<HonoEnv>()
.use(authInfo) .use(authInfo)
.post( //post user
"/", .post("/", requestValidator("json", registerFormSchema), async (c) => {
checkPermission("register.create"),
requestValidator("json", registerFormSchema),
async (c) => {
const formData = c.req.valid("json"); const formData = c.req.valid("json");
console.log("Form Data:", formData); // Check if the provided email or username is already exists in database
// Build conditions based on available formData
const conditions = []; const conditions = [];
if (formData.email) { if (formData.email) {
conditions.push(eq(users.email, formData.email)); conditions.push(eq(users.email, formData.email));
@ -62,36 +41,34 @@ const respondentsRoute = new Hono<HonoEnv>()
const existingUser = await db const existingUser = await db
.select() .select()
.from(users) .from(users)
.where(or(...conditions)); .where(
or(
console.log("Existing Users:", existingUser); eq(users.email, formData.email),
eq(users.username, formData.username)
)
);
const existingRespondent = await db const existingRespondent = await db
.select() .select()
.from(respondents) .from(respondents)
.where(eq(respondents.phoneNumber, formData.phoneNumber)); .where(eq(respondents.phoneNumber, formData.phoneNumber));
console.log("Existing Respondents:", existingRespondent);
if (existingUser.length > 0) { if (existingUser.length > 0) {
throw new HTTPException(400, { throw new HTTPException(400, {
message: "Email atau username sudah terdaftar", message: "Email or username has been registered",
}); });
} }
if (existingRespondent.length > 0) { if (existingRespondent.length > 0) {
throw new HTTPException(400, { throw new HTTPException(400, {
message: "Nomor HP sudah terdaftar", message: "Phone number has been registered",
}); });
} }
// Hash the password // Hash the password
const hashedPassword = await hashPassword(formData.password); const hashedPassword = await hashPassword(formData.password);
console.log("Hashed Password:", hashedPassword);
// Start a transaction // Start a transaction
try {
const result = await db.transaction(async (trx) => { const result = await db.transaction(async (trx) => {
// Create user // Create user
const [newUser] = await trx const [newUser] = await trx
@ -103,55 +80,53 @@ const respondentsRoute = new Hono<HonoEnv>()
password: hashedPassword, password: hashedPassword,
isEnabled: formData.isEnabled?.toLowerCase() === "true" || true, isEnabled: formData.isEnabled?.toLowerCase() === "true" || true,
}) })
.returning(); .returning()
.catch(() => {
console.log("New User:", newUser); throw new HTTPException(500, { message: "Error creating user" });
});
// Create respondent // Create respondent
await trx.insert(respondents).values({ await trx
.insert(respondents)
.values({
companyName: formData.companyName, companyName: formData.companyName,
position: formData.position, position: formData.position,
workExperience: formData.workExperience, workExperience: formData.workExperience,
address: formData.address, address: formData.address,
phoneNumber: formData.phoneNumber, phoneNumber: formData.phoneNumber,
userId: newUser.id, userId: newUser.id,
})
.catch(() => {
throw new HTTPException(500, {
message: "Error creating respondent",
});
}); });
console.log("Respondent Created for User ID:", newUser.id); // Automatically assign "user" role to the new user
const [role] = await trx
.select()
.from(rolesSchema)
.where(eq(rolesSchema.code, "user"))
.limit(1);
// If roles are included in the request, add to rolesToUsers if (!role) {
if (formData.roles) { throw new HTTPException(500, { message: "Role 'user' not found" });
try { }
const roles = JSON.parse(formData.roles) as string[];
if (roles.length) { await trx.insert(rolesToUsers).values({
await trx.insert(rolesToUsers).values(
roles.map((role) => ({
userId: newUser.id, userId: newUser.id,
roleId: role, roleId: role.id,
}))
);
}
} catch (error) {
console.error("Error parsing roles:", error);
throw new HTTPException(400, {
message: "Invalid roles format",
}); });
}
}
return newUser; return newUser;
}); });
return c.json({ return c.json(
message: "User and respondent created successfully", {
}, 201); message: "User created successfully",
} catch (error) { },
console.error("Error creating user and respondent:", error); 201
throw new HTTPException(500, {
message: "Error creating user and respondent",
});
}
}
); );
});
export default respondentsRoute; export default respondentsRoute;