@opengis/fastify-table
Version:
core-plugins
125 lines (124 loc) • 5.38 kB
JavaScript
const q1 = 'select count(*) > 0 as "userExists" from admin.users where $1 in (email,login)';
const q2 = 'select count(*) > 0 as "contactExists" from crm_acc.crm_contact where email=$1';
const q3 = "select contact_id as uid from crm_acc.crm_contact where email=$1";
const qUser = "select * from admin.users where email = $1 and enabled";
import config from "../../../../../config.js";
import dataInsert from "../../../../plugins/crud/funcs/dataInsert.js";
import pgClients from "../../../../plugins/pg/pgClients.js";
import authorizeUser from "../../../../plugins/auth/funcs/authorizeUser.js";
/**
* АПІ призначене для реєстрації нового користувача на сайті
*
* @method POST
* @summary Реєстрація нового користувача
* @priority 3
* @alias registration
* @type api
* @tag auth
* @param {String} email Пошта користувача
* @param {String} first_name Ім`я користувача
* @param {String} last_name Прізвище користувача
* @param {String|Number} phone Телефон користувача
* @errors 400, 500
* @returns {Number} status Номер помилки
* @returns {String|Object} error Опис помилки
* @returns {String|Object} message Повідомлення про успішну реєстрацію
*/
export default async function registration(req, reply) {
const { pg = pgClients.client, body = {} } = req;
const { password, email } = body;
if (!password || (!email && !body.login)) {
return reply.status(400).send({
error: "Недостатньо параметрів",
code: 400,
});
}
const regularExp = /^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/;
if (email && !regularExp.test(email)) {
return reply.status(400).send({
error: "Параметр E-mail невалідний",
code: 400,
});
}
if (body?.first_name &&
!/[А-Яа-яA-Za-zёЁЇїІіЄєҐґ '-]+/.test(body?.first_name)) {
return reply.status(400).send({
error: "Параметр Ім'я невалідний",
code: 400,
});
}
if (body?.last_name &&
!/[А-Яа-яA-Za-zёЁЇїІіЄєҐґ '-]+/.test(body?.last_name)) {
return reply.status(400).send({
error: "Параметр Прізвище невалідний",
code: 400,
});
}
if (body?.phone &&
!/^\+\d{3}\s?\d{2}\s?\d{3}\s?\d{2}\s?\d{2}$/.test(body?.phone)) {
return reply.status(400).send({
error: "Параметр Телефон невалідний",
code: 400,
});
}
const login = body.login || email;
const data = {
...body,
user_name: body?.first_name,
sur_name: body?.last_name,
login,
email: login,
uid: undefined,
user_rnokpp: undefined,
social_auth_id: undefined,
user_type: undefined,
enabled: true,
};
const { userExists } = config.pg
? await pg.query(q1, [login]).then((el) => el.rows?.[0] || {})
: {};
if (userExists) {
const txt = !body.login
? "Даний адрес електронної пошти вже прив'язаний до іншого облікового запису"
: "Даний логін вже використовується";
return reply.status(409).send({ error: txt, code: 409 });
}
if (pg.pk?.["crm_acc.crm_contact"]) {
// insert crm contact
const { contactExists } = await pg
.query(q2, [login])
.then((el) => el.rows?.[0] || {});
if (contactExists) {
const txt = !body.login
? "Користувача за даною адресою вже зареєстровано"
: "Даний логін вже використовується";
return reply.status(409).send({ error: txt, code: 409 });
}
await dataInsert({ pg, table: "crm_acc.crm_contact", data });
const { uid } = await pg
.query(q3, [login])
.then((el) => el.rows?.[0] || {});
await pg.query(`insert into admin.users (uid, login, password, user_name, sur_name, father_name, email,phone, enabled, user_personal_code )
select contact_id, $4, $3, first_name, last_name, middle_name, $2, phone, true, md5(random()::text)
from crm_acc.crm_contact where contact_id = $1 and contact_id not in (select uid from admin.users)`, [uid, email, password, login]);
}
else {
// if crm_contact not exists
await dataInsert({
pg,
table: "admin.users",
data,
});
}
const newUser = await pg
.query(qUser, [login])
.then((res) => res.rows?.[0]);
if (!newUser) {
return { message: "Помилка завершення реєстрації, спробуйте увійти", status: 500 };
}
const authType = "creds-" + (newUser.user_type === "admin" ? "admin" : "user");
const result = await authorizeUser(newUser, req, authType);
return req.method === "GET"
? reply.status(302).redirect(result)
: reply.status(200).send(result);
}