Merge pull request #1723 from AymanAlSuleihi/fix/create-admin-user-seed-validation
fix: Create admin user seed validation
This commit is contained in:
@@ -3,7 +3,12 @@
|
||||
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
|
||||
*/
|
||||
|
||||
/* eslint-disable no-console */
|
||||
|
||||
const bcrypt = require('bcrypt');
|
||||
const validator = require('validator');
|
||||
|
||||
const USERNAME_REGEX = /^[a-zA-Z0-9]+((_|\.)?[a-zA-Z0-9])*$/;
|
||||
|
||||
const buildUserData = () => {
|
||||
const data = {
|
||||
@@ -15,10 +20,23 @@ const buildUserData = () => {
|
||||
data.password = bcrypt.hashSync(process.env.DEFAULT_ADMIN_PASSWORD, 10);
|
||||
}
|
||||
if (process.env.DEFAULT_ADMIN_NAME) {
|
||||
data.name = process.env.DEFAULT_ADMIN_NAME;
|
||||
if (process.env.DEFAULT_ADMIN_NAME.length > 128) {
|
||||
console.warn('Warning: DEFAULT_ADMIN_NAME exceeds 128 characters; truncating.');
|
||||
data.name = process.env.DEFAULT_ADMIN_NAME.slice(0, 128);
|
||||
} else {
|
||||
data.name = process.env.DEFAULT_ADMIN_NAME;
|
||||
}
|
||||
}
|
||||
if (process.env.DEFAULT_ADMIN_USERNAME) {
|
||||
data.username = process.env.DEFAULT_ADMIN_USERNAME.toLowerCase();
|
||||
const username = process.env.DEFAULT_ADMIN_USERNAME.toLowerCase();
|
||||
|
||||
if (username.length < 3 || username.length > 32 || !USERNAME_REGEX.test(username)) {
|
||||
console.warn(
|
||||
`Warning: DEFAULT_ADMIN_USERNAME "${process.env.DEFAULT_ADMIN_USERNAME}" is invalid; skipping.`,
|
||||
);
|
||||
} else {
|
||||
data.username = username;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
@@ -45,8 +63,36 @@ exports.seed = async (knex) => {
|
||||
process.env.DEFAULT_ADMIN_EMAIL && process.env.DEFAULT_ADMIN_EMAIL.toLowerCase();
|
||||
|
||||
if (defaultAdminEmail) {
|
||||
if (!validator.isEmail(defaultAdminEmail)) {
|
||||
throw new Error(
|
||||
`DEFAULT_ADMIN_EMAIL "${process.env.DEFAULT_ADMIN_EMAIL}" is not a valid e-mail address.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (defaultAdminEmail.length > 256) {
|
||||
throw new Error(
|
||||
`DEFAULT_ADMIN_EMAIL "${process.env.DEFAULT_ADMIN_EMAIL}" exceeds 256 characters.`,
|
||||
);
|
||||
}
|
||||
|
||||
const existingEmailUser = await knex('user_account').where('email', defaultAdminEmail).first();
|
||||
|
||||
if (existingEmailUser) {
|
||||
throw new Error(`User with DEFAULT_ADMIN_EMAIL "${defaultAdminEmail}" already exists.`);
|
||||
}
|
||||
|
||||
const userData = buildUserData();
|
||||
|
||||
if (userData.username) {
|
||||
const existingUsernameUser = await knex('user_account')
|
||||
.where('username', userData.username)
|
||||
.first();
|
||||
|
||||
if (existingUsernameUser) {
|
||||
throw new Error(`User with DEFAULT_ADMIN_USERNAME "${userData.username}" already exists.`);
|
||||
}
|
||||
}
|
||||
|
||||
let userId;
|
||||
try {
|
||||
[{ id: userId }] = await knex('user_account').insert(
|
||||
|
||||
Reference in New Issue
Block a user