118 lines
3.1 KiB
JavaScript
118 lines
3.1 KiB
JavaScript
// @ts-check
|
|
|
|
const addUsersTableToDb = require("../../backend/addUsersTableToDb");
|
|
const addDbEntry = require("../../backend/db/addDbEntry");
|
|
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
|
const hashPassword = require("../../dsql/hashPassword");
|
|
|
|
/** @type {import("../../../types").APICreateUserFunction} */
|
|
module.exports = async function apiCreateUser({
|
|
encryptionKey,
|
|
payload,
|
|
database,
|
|
userId,
|
|
}) {
|
|
const dbFullName = database;
|
|
|
|
const hashedPassword = hashPassword({
|
|
encryptionKey: encryptionKey,
|
|
password: String(payload.password),
|
|
});
|
|
|
|
payload.password = hashedPassword;
|
|
|
|
let fields = await varDatabaseDbHandler({
|
|
queryString: `SHOW COLUMNS FROM users`,
|
|
database: dbFullName,
|
|
});
|
|
|
|
if (!fields) {
|
|
const newTable = await addUsersTableToDb({
|
|
userId: Number(userId),
|
|
database: database,
|
|
});
|
|
|
|
fields = await varDatabaseDbHandler({
|
|
queryString: `SHOW COLUMNS FROM users`,
|
|
database: dbFullName,
|
|
});
|
|
}
|
|
|
|
if (!fields) {
|
|
return {
|
|
success: false,
|
|
msg: "Could not create users table",
|
|
};
|
|
}
|
|
|
|
const fieldsTitles = fields.map(
|
|
(/** @type {any} */ fieldObject) => fieldObject.Field
|
|
);
|
|
|
|
let invalidField = null;
|
|
|
|
for (let i = 0; i < Object.keys(payload).length; i++) {
|
|
const key = Object.keys(payload)[i];
|
|
if (!fieldsTitles.includes(key)) {
|
|
invalidField = key;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (invalidField) {
|
|
return {
|
|
success: false,
|
|
msg: `${invalidField} is not a valid field!`,
|
|
};
|
|
}
|
|
|
|
const existingUser = await varDatabaseDbHandler({
|
|
queryString: `SELECT * FROM users WHERE email = ?${
|
|
payload.username ? " OR username = ?" : ""
|
|
}`,
|
|
queryValuesArray: payload.username
|
|
? [payload.email, payload.username]
|
|
: [payload.email],
|
|
database: dbFullName,
|
|
});
|
|
|
|
if (existingUser?.[0]) {
|
|
return {
|
|
success: false,
|
|
msg: "User Already Exists",
|
|
payload: null,
|
|
};
|
|
}
|
|
|
|
const addUser = await addDbEntry({
|
|
dbContext: "Dsql User",
|
|
paradigm: "Full Access",
|
|
dbFullName: dbFullName,
|
|
tableName: "users",
|
|
data: {
|
|
...payload,
|
|
image: "/images/user-preset.png",
|
|
image_thumbnail: "/images/user-preset-thumbnail.png",
|
|
},
|
|
});
|
|
|
|
if (addUser?.insertId) {
|
|
const newlyAddedUser = await varDatabaseDbHandler({
|
|
queryString: `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`,
|
|
database: dbFullName,
|
|
});
|
|
|
|
return {
|
|
success: true,
|
|
payload: newlyAddedUser[0],
|
|
};
|
|
} else {
|
|
return {
|
|
success: false,
|
|
msg: "Could not create user",
|
|
sqlResult: addUser,
|
|
payload: null,
|
|
};
|
|
}
|
|
};
|