mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-19 04:09:26 +00:00
started migration of user domain to ts
This commit is contained in:
5
backend/src/@types/express.d.ts
vendored
Normal file
5
backend/src/@types/express.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
declare namespace Express {
|
||||
export interface Request {
|
||||
user: { id: string; profile: string };
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
require("dotenv/config");
|
||||
|
||||
module.exports = {
|
||||
define: {
|
||||
charset: "utf8mb4",
|
||||
collate: "utf8mb4_bin",
|
||||
},
|
||||
dialect: "mysql",
|
||||
timezone: "-03:00",
|
||||
host: process.env.DB_HOST,
|
||||
database: process.env.DB_NAME,
|
||||
username: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
logging: false,
|
||||
seederStorage: "sequelize",
|
||||
};
|
||||
17
backend/src/config/database.ts
Normal file
17
backend/src/config/database.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import "dotenv/config";
|
||||
|
||||
const dbConfig = {
|
||||
define: {
|
||||
charset: "utf8mb4",
|
||||
collate: "utf8mb4_bin"
|
||||
},
|
||||
dialect: "mysql",
|
||||
timezone: "-03:00",
|
||||
host: process.env.DB_HOST,
|
||||
database: process.env.DB_NAME,
|
||||
username: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
logging: false
|
||||
};
|
||||
|
||||
export default dbConfig;
|
||||
181
backend/src/controllers/OldUserController.js
Normal file
181
backend/src/controllers/OldUserController.js
Normal file
@@ -0,0 +1,181 @@
|
||||
// const Sequelize = require("sequelize");
|
||||
// const Yup = require("yup");
|
||||
// const { Op } = require("sequelize");
|
||||
|
||||
// const User = require("../models/User");
|
||||
// const Setting = require("../models/Setting");
|
||||
|
||||
// const { getIO } = require("../libs/socket");
|
||||
|
||||
// exports.index = async (req, res) => {
|
||||
// if (req.user.profile !== "admin") {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "Only administrators can access this route." });
|
||||
// }
|
||||
|
||||
// const { searchParam = "", pageNumber = 1 } = req.query;
|
||||
|
||||
// const whereCondition = {
|
||||
// [Op.or]: [
|
||||
// {
|
||||
// name: Sequelize.where(
|
||||
// Sequelize.fn("LOWER", Sequelize.col("name")),
|
||||
// "LIKE",
|
||||
// "%" + searchParam.toLowerCase() + "%"
|
||||
// ),
|
||||
// },
|
||||
// { email: { [Op.like]: `%${searchParam.toLowerCase()}%` } },
|
||||
// ],
|
||||
// };
|
||||
|
||||
// let limit = 20;
|
||||
// let offset = limit * (pageNumber - 1);
|
||||
|
||||
// const { count, rows: users } = await User.findAndCountAll({
|
||||
// attributes: ["name", "id", "email", "profile"],
|
||||
// where: whereCondition,
|
||||
// limit,
|
||||
// offset,
|
||||
// order: [["createdAt", "DESC"]],
|
||||
// });
|
||||
|
||||
// const hasMore = count > offset + users.length;
|
||||
|
||||
// return res.status(200).json({ users, count, hasMore });
|
||||
// };
|
||||
|
||||
export default async (req, res, next) => {
|
||||
console.log(req.url);
|
||||
const schema = Yup.object().shape({
|
||||
name: Yup.string().required().min(2),
|
||||
email: Yup.string()
|
||||
.email()
|
||||
.required()
|
||||
.test(
|
||||
"Check-email",
|
||||
"An user with this email already exists",
|
||||
async value => {
|
||||
const userFound = await User.findOne({ where: { email: value } });
|
||||
return !Boolean(userFound);
|
||||
}
|
||||
),
|
||||
password: Yup.string().required().min(5)
|
||||
});
|
||||
|
||||
if (req.url === "/signup") {
|
||||
const { value: userCreation } = await Setting.findByPk("userCreation");
|
||||
|
||||
if (userCreation === "disabled") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "User creation is disabled by administrator." });
|
||||
}
|
||||
} else if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can create users." });
|
||||
}
|
||||
|
||||
try {
|
||||
await schema.validate(req.body);
|
||||
} catch (err) {
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
|
||||
const io = getIO();
|
||||
|
||||
const { name, id, email, profile } = await User.create(req.body);
|
||||
|
||||
io.emit("user", {
|
||||
action: "create",
|
||||
user: { name, id, email, profile }
|
||||
});
|
||||
|
||||
return res.status(201).json({ message: "User created!", userId: id });
|
||||
};
|
||||
|
||||
// exports.show = async (req, res) => {
|
||||
// const { userId } = req.params;
|
||||
|
||||
// const user = await User.findByPk(userId, {
|
||||
// attributes: ["id", "name", "email", "profile"],
|
||||
// });
|
||||
|
||||
// if (!user) {
|
||||
// res.status(400).json({ error: "No user found with this id." });
|
||||
// }
|
||||
|
||||
// return res.status(200).json(user);
|
||||
// };
|
||||
|
||||
// exports.update = async (req, res) => {
|
||||
// const schema = Yup.object().shape({
|
||||
// name: Yup.string().min(2),
|
||||
// email: Yup.string().email(),
|
||||
// password: Yup.string(),
|
||||
// });
|
||||
|
||||
// if (req.user.profile !== "admin") {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "Only administrators can edit users." });
|
||||
// }
|
||||
|
||||
// await schema.validate(req.body);
|
||||
|
||||
// const io = getIO();
|
||||
// const { userId } = req.params;
|
||||
|
||||
// const user = await User.findByPk(userId, {
|
||||
// attributes: ["name", "id", "email", "profile"],
|
||||
// });
|
||||
|
||||
// if (!user) {
|
||||
// res.status(404).json({ error: "No user found with this id." });
|
||||
// }
|
||||
|
||||
// if (user.profile === "admin" && req.body.profile === "user") {
|
||||
// const adminUsers = await User.count({ where: { profile: "admin" } });
|
||||
// if (adminUsers <= 1) {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "There must be at leat one admin user." });
|
||||
// }
|
||||
// }
|
||||
|
||||
// await user.update(req.body);
|
||||
|
||||
// io.emit("user", {
|
||||
// action: "update",
|
||||
// user: user,
|
||||
// });
|
||||
|
||||
// return res.status(200).json(user);
|
||||
// };
|
||||
|
||||
// exports.delete = async (req, res) => {
|
||||
// const io = getIO();
|
||||
// const { userId } = req.params;
|
||||
|
||||
// const user = await User.findByPk(userId);
|
||||
|
||||
// if (!user) {
|
||||
// res.status(400).json({ error: "No user found with this id." });
|
||||
// }
|
||||
|
||||
// if (req.user.profile !== "admin") {
|
||||
// return res
|
||||
// .status(403)
|
||||
// .json({ error: "Only administrators can edit users." });
|
||||
// }
|
||||
|
||||
// await user.destroy();
|
||||
|
||||
// io.emit("user", {
|
||||
// action: "delete",
|
||||
// userId: userId,
|
||||
// });
|
||||
|
||||
// return res.status(200).json({ message: "User deleted" });
|
||||
// };
|
||||
@@ -1,181 +0,0 @@
|
||||
const Sequelize = require("sequelize");
|
||||
const Yup = require("yup");
|
||||
const { Op } = require("sequelize");
|
||||
|
||||
const User = require("../models/User");
|
||||
const Setting = require("../models/Setting");
|
||||
|
||||
const { getIO } = require("../libs/socket");
|
||||
|
||||
exports.index = async (req, res) => {
|
||||
if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can access this route." });
|
||||
}
|
||||
|
||||
const { searchParam = "", pageNumber = 1 } = req.query;
|
||||
|
||||
const whereCondition = {
|
||||
[Op.or]: [
|
||||
{
|
||||
name: Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("name")),
|
||||
"LIKE",
|
||||
"%" + searchParam.toLowerCase() + "%"
|
||||
),
|
||||
},
|
||||
{ email: { [Op.like]: `%${searchParam.toLowerCase()}%` } },
|
||||
],
|
||||
};
|
||||
|
||||
let limit = 20;
|
||||
let offset = limit * (pageNumber - 1);
|
||||
|
||||
const { count, rows: users } = await User.findAndCountAll({
|
||||
attributes: ["name", "id", "email", "profile"],
|
||||
where: whereCondition,
|
||||
limit,
|
||||
offset,
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
const hasMore = count > offset + users.length;
|
||||
|
||||
return res.status(200).json({ users, count, hasMore });
|
||||
};
|
||||
|
||||
exports.store = async (req, res, next) => {
|
||||
console.log(req.url);
|
||||
const schema = Yup.object().shape({
|
||||
name: Yup.string().required().min(2),
|
||||
email: Yup.string()
|
||||
.email()
|
||||
.required()
|
||||
.test(
|
||||
"Check-email",
|
||||
"An user with this email already exists",
|
||||
async value => {
|
||||
const userFound = await User.findOne({ where: { email: value } });
|
||||
return !Boolean(userFound);
|
||||
}
|
||||
),
|
||||
password: Yup.string().required().min(5),
|
||||
});
|
||||
|
||||
if (req.url === "/signup") {
|
||||
const { value: userCreation } = await Setting.findByPk("userCreation");
|
||||
|
||||
if (userCreation === "disabled") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "User creation is disabled by administrator." });
|
||||
}
|
||||
} else if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can create users." });
|
||||
}
|
||||
|
||||
try {
|
||||
await schema.validate(req.body);
|
||||
} catch (err) {
|
||||
return res.status(400).json({ error: err.message });
|
||||
}
|
||||
|
||||
const io = getIO();
|
||||
|
||||
const { name, id, email, profile } = await User.create(req.body);
|
||||
|
||||
io.emit("user", {
|
||||
action: "create",
|
||||
user: { name, id, email, profile },
|
||||
});
|
||||
|
||||
return res.status(201).json({ message: "User created!", userId: id });
|
||||
};
|
||||
|
||||
exports.show = async (req, res) => {
|
||||
const { userId } = req.params;
|
||||
|
||||
const user = await User.findByPk(userId, {
|
||||
attributes: ["id", "name", "email", "profile"],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
res.status(400).json({ error: "No user found with this id." });
|
||||
}
|
||||
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
|
||||
exports.update = async (req, res) => {
|
||||
const schema = Yup.object().shape({
|
||||
name: Yup.string().min(2),
|
||||
email: Yup.string().email(),
|
||||
password: Yup.string(),
|
||||
});
|
||||
|
||||
if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can edit users." });
|
||||
}
|
||||
|
||||
await schema.validate(req.body);
|
||||
|
||||
const io = getIO();
|
||||
const { userId } = req.params;
|
||||
|
||||
const user = await User.findByPk(userId, {
|
||||
attributes: ["name", "id", "email", "profile"],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
res.status(404).json({ error: "No user found with this id." });
|
||||
}
|
||||
|
||||
if (user.profile === "admin" && req.body.profile === "user") {
|
||||
const adminUsers = await User.count({ where: { profile: "admin" } });
|
||||
if (adminUsers <= 1) {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "There must be at leat one admin user." });
|
||||
}
|
||||
}
|
||||
|
||||
await user.update(req.body);
|
||||
|
||||
io.emit("user", {
|
||||
action: "update",
|
||||
user: user,
|
||||
});
|
||||
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
|
||||
exports.delete = async (req, res) => {
|
||||
const io = getIO();
|
||||
const { userId } = req.params;
|
||||
|
||||
const user = await User.findByPk(userId);
|
||||
|
||||
if (!user) {
|
||||
res.status(400).json({ error: "No user found with this id." });
|
||||
}
|
||||
|
||||
if (req.user.profile !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only administrators can edit users." });
|
||||
}
|
||||
|
||||
await user.destroy();
|
||||
|
||||
io.emit("user", {
|
||||
action: "delete",
|
||||
userId: userId,
|
||||
});
|
||||
|
||||
return res.status(200).json({ message: "User deleted" });
|
||||
};
|
||||
69
backend/src/controllers/UserController.ts
Normal file
69
backend/src/controllers/UserController.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
// import CheckSettingsHelper from "../helpers/CheckSettingsHelper";
|
||||
import AppError from "../errors/AppError";
|
||||
|
||||
import CreateUserService from "../services/CreateUserService";
|
||||
// import UpdateUserService from "../services/UpdateUserService";
|
||||
// import ListUsersService from "../services/ListUsersService";
|
||||
// import FindUserService from "../services/FindUserService";
|
||||
|
||||
export const index = async (req: Request, res: Response): Promise<Response> => {
|
||||
if (req.user.profile !== "admin") {
|
||||
throw new AppError("Only administrators can access this route.", 403); // should be handled better.
|
||||
}
|
||||
const { searchParam, pageNumber } = req.query as any;
|
||||
|
||||
const { users, count, hasMore } = await ListUsersService({
|
||||
searchParam,
|
||||
pageNumber
|
||||
});
|
||||
|
||||
return res.json({ users, count, hasMore });
|
||||
};
|
||||
|
||||
export const store = async (req: Request, res: Response): Promise<Response> => {
|
||||
const { email, password, name, profile } = req.body;
|
||||
|
||||
// if (
|
||||
// req.url === "/signup" &&
|
||||
// (await CheckSettingsHelper("userCreation")) === "disabled"
|
||||
// ) {
|
||||
// throw new AppError("User creation is disabled by administrator.", 403);
|
||||
// } else if (req.user.profile !== "admin") {
|
||||
// throw new AppError("Only administrators can create users.", 403);
|
||||
// }
|
||||
|
||||
const user = await CreateUserService({
|
||||
email,
|
||||
password,
|
||||
name,
|
||||
profile
|
||||
});
|
||||
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
|
||||
export const show = async (req: Request, res: Response): Promise<Response> => {
|
||||
const { userId } = req.params;
|
||||
|
||||
const user = await FindUserService(userId);
|
||||
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
|
||||
export const update = async (
|
||||
req: Request,
|
||||
res: Response
|
||||
): Promise<Response> => {
|
||||
if (req.user.profile !== "admin") {
|
||||
throw new AppError("Only administrators can edit users.", 403);
|
||||
}
|
||||
|
||||
const { userId } = req.params;
|
||||
const userData = req.body;
|
||||
|
||||
const user = await UpdateUserService({ userData, userId });
|
||||
|
||||
return res.status(200).json(user);
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
const Sequelize = require("sequelize");
|
||||
const dbConfig = require("../config/database");
|
||||
|
||||
const User = require("../models/User");
|
||||
const Contact = require("../models/Contact");
|
||||
const Ticket = require("../models/Ticket");
|
||||
const Message = require("../models/Message");
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const ContactCustomField = require("../models/ContactCustomField");
|
||||
const Setting = require("../models/Setting");
|
||||
|
||||
const models = [
|
||||
User,
|
||||
Contact,
|
||||
Ticket,
|
||||
Message,
|
||||
Whatsapp,
|
||||
ContactCustomField,
|
||||
Setting,
|
||||
];
|
||||
|
||||
class Database {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.sequelize = new Sequelize(dbConfig);
|
||||
|
||||
models
|
||||
.map(model => model.init(this.sequelize))
|
||||
.map(model => model.associate && model.associate(this.sequelize.models));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new Database();
|
||||
53
backend/src/database/index.ts
Normal file
53
backend/src/database/index.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { Sequelize } from "sequelize-typescript";
|
||||
import { resolve } from "path";
|
||||
// import dbConfig from "../config/database";
|
||||
import "dotenv/config";
|
||||
|
||||
// import User from "../models/User";
|
||||
// const Contact = require("../models/Contact");
|
||||
// const Ticket = require("../models/Ticket");
|
||||
// const Message = require("../models/Message");
|
||||
// const Whatsapp = require("../models/Whatsapp");
|
||||
// const ContactCustomField = require("../models/ContactCustomField");
|
||||
// const Setting = require("../models/Setting");
|
||||
|
||||
const sequelize = new Sequelize({
|
||||
define: {
|
||||
charset: "utf8mb4",
|
||||
collate: "utf8mb4_bin"
|
||||
},
|
||||
dialect: "mysql",
|
||||
timezone: "-03:00",
|
||||
host: process.env.DB_HOST,
|
||||
database: process.env.DB_NAME,
|
||||
username: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
models: [resolve(__dirname, "..", "models")],
|
||||
logging: false
|
||||
});
|
||||
|
||||
// const models = [
|
||||
// User
|
||||
// // Contact,
|
||||
// // Ticket,
|
||||
// // Message,
|
||||
// // Whatsapp,
|
||||
// // ContactCustomField,
|
||||
// // Setting,
|
||||
// ];
|
||||
|
||||
// class Database {
|
||||
// constructor() {
|
||||
// this.init();
|
||||
// }
|
||||
|
||||
// init() {
|
||||
// this.sequelize = new Sequelize(dbConfig);
|
||||
|
||||
// models
|
||||
// .map(model => model.init(this.sequelize))
|
||||
// .map(model => model.associate && model.associate(this.sequelize.models));
|
||||
// }
|
||||
// }
|
||||
|
||||
export default sequelize;
|
||||
11
backend/src/errors/AppError.ts
Normal file
11
backend/src/errors/AppError.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
class AppError {
|
||||
public readonly message: string;
|
||||
public readonly statusCode: number;
|
||||
|
||||
constructor(message: string, statusCode = 400) {
|
||||
this.message = message;
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
}
|
||||
|
||||
export default AppError;
|
||||
18
backend/src/helpers/CheckSettingsHelper.ts
Normal file
18
backend/src/helpers/CheckSettingsHelper.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import AppError from "../errors/AppError";
|
||||
import Setting from "../models/Setting";
|
||||
|
||||
const CheckSettings = async (key: string): Promise<string> => {
|
||||
const settingsRepository = getRepository(Setting);
|
||||
|
||||
const setting = await settingsRepository.findOne({
|
||||
where: { key }
|
||||
});
|
||||
|
||||
if (!setting) {
|
||||
throw new AppError("No setting found with this id.", 404);
|
||||
}
|
||||
|
||||
return setting.value;
|
||||
};
|
||||
|
||||
export default CheckSettings;
|
||||
@@ -1,32 +0,0 @@
|
||||
const Sequelize = require("sequelize");
|
||||
const bcrypt = require("bcryptjs");
|
||||
|
||||
class User extends Sequelize.Model {
|
||||
static init(sequelize) {
|
||||
super.init(
|
||||
{
|
||||
name: { type: Sequelize.STRING },
|
||||
password: { type: Sequelize.VIRTUAL },
|
||||
profile: { type: Sequelize.STRING, defaultValue: "admin" },
|
||||
passwordHash: { type: Sequelize.STRING },
|
||||
email: { type: Sequelize.STRING },
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
}
|
||||
);
|
||||
|
||||
this.addHook("beforeSave", async user => {
|
||||
if (user.password) {
|
||||
user.passwordHash = await bcrypt.hash(user.password, 8);
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
checkPassword(password) {
|
||||
return bcrypt.compare(password, this.passwordHash);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = User;
|
||||
82
backend/src/models/User.ts
Normal file
82
backend/src/models/User.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
Table,
|
||||
Column,
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
Model,
|
||||
DataType
|
||||
} from "sequelize-typescript";
|
||||
|
||||
@Table
|
||||
class User extends Model<User> {
|
||||
@Column({
|
||||
defaultValue: DataType.UUIDV4,
|
||||
primaryKey: true,
|
||||
type: DataType.UUID
|
||||
})
|
||||
id: string;
|
||||
|
||||
@Column
|
||||
name: string;
|
||||
|
||||
@Column
|
||||
email: string;
|
||||
|
||||
@Column
|
||||
passwordHash: string;
|
||||
|
||||
@Column({
|
||||
defaultValue: "admin"
|
||||
})
|
||||
profile: string;
|
||||
|
||||
@CreatedAt
|
||||
createdAt: Date;
|
||||
|
||||
@UpdatedAt
|
||||
updatedAt: Date;
|
||||
|
||||
// @BeforeUpdate
|
||||
// @BeforeInsert
|
||||
// hashPassword = async () => {
|
||||
// if (this.passwordHash) {
|
||||
// this.passwordHash = await hash(this.passwordHash, 8);
|
||||
// }
|
||||
// };
|
||||
|
||||
// checkPassword = async (password: string) => {
|
||||
// return await compare(password, this.passwordHash);
|
||||
// };
|
||||
}
|
||||
|
||||
export default User;
|
||||
|
||||
// const bcrypt = require("bcryptjs");
|
||||
// @Table
|
||||
// class User extends Model<User> {
|
||||
// static init(sequelize) {
|
||||
// super.init(
|
||||
// {
|
||||
// name: { type: Sequelize.STRING },
|
||||
// password: { type: Sequelize.VIRTUAL },
|
||||
// profile: { type: Sequelize.STRING, defaultValue: "admin" },
|
||||
// passwordHash: { type: Sequelize.STRING },
|
||||
// email: { type: Sequelize.STRING }
|
||||
// },
|
||||
// {
|
||||
// sequelize
|
||||
// }
|
||||
// );
|
||||
|
||||
// this.addHook("beforeSave", async user => {
|
||||
// if (user.password) {
|
||||
// user.passwordHash = await bcrypt.hash(user.password, 8);
|
||||
// }
|
||||
// });
|
||||
// return this;
|
||||
// }
|
||||
|
||||
// checkPassword(password) {
|
||||
// return bcrypt.compare(password, this.passwordHash);
|
||||
// }
|
||||
// }
|
||||
32
backend/src/modelsOld/User.js
Normal file
32
backend/src/modelsOld/User.js
Normal file
@@ -0,0 +1,32 @@
|
||||
const Sequelize = require("sequelize");
|
||||
const bcrypt = require("bcryptjs");
|
||||
|
||||
class User extends Sequelize.Model {
|
||||
static init(sequelize) {
|
||||
super.init(
|
||||
{
|
||||
name: { type: Sequelize.STRING },
|
||||
password: { type: Sequelize.VIRTUAL },
|
||||
profile: { type: Sequelize.STRING, defaultValue: "admin" },
|
||||
passwordHash: { type: Sequelize.STRING },
|
||||
email: { type: Sequelize.STRING }
|
||||
},
|
||||
{
|
||||
sequelize
|
||||
}
|
||||
);
|
||||
|
||||
this.addHook("beforeSave", async user => {
|
||||
if (user.password) {
|
||||
user.passwordHash = await bcrypt.hash(user.password, 8);
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
checkPassword(password) {
|
||||
return bcrypt.compare(password, this.passwordHash);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = User;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Router } from "express";
|
||||
|
||||
// const isAuth = require("../../middleware/is-auth");
|
||||
// const UserController = require("../../controllers/UserController");
|
||||
import * as UserController from "../controllers/UserController";
|
||||
|
||||
const userRoutes = Router();
|
||||
|
||||
@@ -9,12 +9,12 @@ userRoutes.get("/users", (req, res) =>
|
||||
res.json({ meessage: "lets do some prettier shit here" })
|
||||
);
|
||||
|
||||
// routes.post("/users", isAuth, UserController.store);
|
||||
userRoutes.post("/users", UserController.store);
|
||||
|
||||
// routes.put("/users/:userId", isAuth, UserController.update);
|
||||
// userRoutes.put("/users/:userId", isAuth, UserController.update);
|
||||
|
||||
// routes.get("/users/:userId", isAuth, UserController.show);
|
||||
// userRoutes.get("/users/:userId", isAuth, UserController.show);
|
||||
|
||||
// routes.delete("/users/:userId", isAuth, UserController.delete);
|
||||
// userRoutes.delete("/users/:userId", isAuth, UserController.delete);
|
||||
|
||||
export default userRoutes;
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import "dotenv/config";
|
||||
import "express-async-errors";
|
||||
import express from "express";
|
||||
import cors from "cors";
|
||||
|
||||
import routes from "./routes";
|
||||
|
||||
// import path from "path";
|
||||
// import cors from "cors";
|
||||
// import multer from "multer";
|
||||
// import Sentry from "@sentry/node";
|
||||
// require("./database");
|
||||
import "./database";
|
||||
|
||||
// const { initWbot } = require("./libs/wbot");
|
||||
// const wbotMessageListener = require("./services/wbotMessageListener");
|
||||
@@ -17,14 +19,13 @@ import routes from "./routes";
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(routes);
|
||||
app.listen(8080, () => {
|
||||
console.log("stated");
|
||||
});
|
||||
|
||||
// const server = app.listen(process.env.PORT, () => {
|
||||
// console.log(`Server started on port: ${process.env.PORT}`);
|
||||
// });
|
||||
const server = app.listen(process.env.PORT, () => {
|
||||
console.log(`Server started on port: ${process.env.PORT}`);
|
||||
});
|
||||
|
||||
// Sentry.init({ dsn: process.env.SENTRY_DSN });
|
||||
|
||||
@@ -38,8 +39,6 @@ app.listen(8080, () => {
|
||||
// });
|
||||
|
||||
// app.use(Sentry.Handlers.requestHandler());
|
||||
// app.use(cors());
|
||||
// app.use(express.json());
|
||||
// app.use(multer({ storage: fileStorage }).single("media"));
|
||||
// app.use("/public", express.static(path.join(__dirname, "..", "public")));
|
||||
// app.use(Router);
|
||||
|
||||
53
backend/src/services/CreateUserService.ts
Normal file
53
backend/src/services/CreateUserService.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import * as Yup from "yup";
|
||||
|
||||
import AppError from "../errors/AppError";
|
||||
import User from "../models/User";
|
||||
|
||||
interface Request {
|
||||
email: string;
|
||||
password: string;
|
||||
name: string;
|
||||
profile?: string;
|
||||
}
|
||||
|
||||
const CreateUserService = async ({
|
||||
email,
|
||||
password,
|
||||
name,
|
||||
profile = "admin"
|
||||
}: Request): Promise<User> => {
|
||||
// const schema = Yup.object().shape({
|
||||
// name: Yup.string().required().min(2),
|
||||
// email: Yup.string()
|
||||
// .email()
|
||||
// .required()
|
||||
// .test(
|
||||
// "Check-email",
|
||||
// "An user with this email already exists.",
|
||||
// async value => {
|
||||
// const emailExists = await User.findOne({
|
||||
// where: { email: value }
|
||||
// });
|
||||
// return !Boolean(emailExists);
|
||||
// }
|
||||
// ),
|
||||
// password: Yup.string().required().min(5)
|
||||
// });
|
||||
|
||||
// try {
|
||||
// await schema.validate({ email, password, name });
|
||||
// } catch (err) {
|
||||
// throw new AppError(err.message);
|
||||
// }
|
||||
|
||||
const user = User.create({
|
||||
email,
|
||||
passwordHash: password,
|
||||
name,
|
||||
profile
|
||||
});
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
export default CreateUserService;
|
||||
21
backend/src/services/FindUserService.ts
Normal file
21
backend/src/services/FindUserService.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { getRepository, Raw } from "typeorm";
|
||||
|
||||
import User from "../models/User";
|
||||
import AppError from "../errors/AppError";
|
||||
|
||||
const FindUserService = async (id: string): Promise<User | undefined> => {
|
||||
const usersRepository = getRepository(User);
|
||||
|
||||
const user = await usersRepository.findOne({
|
||||
where: { id },
|
||||
select: ["name", "id", "email", "profile"],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new AppError("No user found with this ID.", 404);
|
||||
}
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
export default FindUserService;
|
||||
54
backend/src/services/ListUsersService.ts
Normal file
54
backend/src/services/ListUsersService.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { getRepository, Raw } from "typeorm";
|
||||
|
||||
import User from "../models/User";
|
||||
|
||||
interface Request {
|
||||
searchParam?: string;
|
||||
pageNumber?: number;
|
||||
}
|
||||
|
||||
interface Response {
|
||||
users: User[];
|
||||
count: number;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
const ListUsersService = async ({
|
||||
searchParam = "",
|
||||
pageNumber = 1,
|
||||
}: Request): Promise<Response> => {
|
||||
const usersRepository = getRepository(User);
|
||||
|
||||
const whereCondition = [
|
||||
{
|
||||
name: Raw(
|
||||
alias => `LOWER(${alias}) Like '%${searchParam.toLowerCase()}%'`
|
||||
),
|
||||
},
|
||||
{
|
||||
email: Raw(
|
||||
alias => `LOWER(${alias}) Like '%${searchParam.toLowerCase()}%'`
|
||||
),
|
||||
},
|
||||
];
|
||||
const take = 20;
|
||||
const skip = take * (pageNumber - 1);
|
||||
|
||||
const [users, count] = await usersRepository.findAndCount({
|
||||
where: whereCondition,
|
||||
select: ["name", "id", "email", "profile"],
|
||||
skip,
|
||||
take,
|
||||
order: { createdAt: "DESC" },
|
||||
});
|
||||
|
||||
const hasMore = count > skip + users.length;
|
||||
|
||||
return {
|
||||
users,
|
||||
count,
|
||||
hasMore,
|
||||
};
|
||||
};
|
||||
|
||||
export default ListUsersService;
|
||||
61
backend/src/services/UpdateUserService.ts
Normal file
61
backend/src/services/UpdateUserService.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { getRepository } from "typeorm";
|
||||
import * as Yup from "yup";
|
||||
|
||||
import AppError from "../errors/AppError";
|
||||
import User from "../models/User";
|
||||
|
||||
interface UserData {
|
||||
email?: string;
|
||||
password?: string;
|
||||
name?: string;
|
||||
profile?: string;
|
||||
}
|
||||
|
||||
interface Request {
|
||||
userData: UserData;
|
||||
userId: string;
|
||||
}
|
||||
|
||||
const UpdateUserService = async ({
|
||||
userData,
|
||||
userId,
|
||||
}: Request): Promise<User | undefined> => {
|
||||
const usersRepository = getRepository(User);
|
||||
|
||||
const schema = Yup.object().shape({
|
||||
name: Yup.string().min(2),
|
||||
email: Yup.string().email(),
|
||||
password: Yup.string(),
|
||||
});
|
||||
|
||||
const { email, password, name } = userData;
|
||||
|
||||
try {
|
||||
await schema.validate({ email, password, name });
|
||||
} catch (err) {
|
||||
throw new AppError(err.message);
|
||||
}
|
||||
|
||||
const user = await usersRepository.findOne({
|
||||
where: { id: userId },
|
||||
select: ["name", "id", "email", "profile"],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new AppError("No user found with this ID.", 404);
|
||||
}
|
||||
|
||||
const teste = await usersRepository.update(userId, {
|
||||
email,
|
||||
passwordHash: password,
|
||||
name,
|
||||
});
|
||||
|
||||
console.log(teste);
|
||||
|
||||
delete user.passwordHash;
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
export default UpdateUserService;
|
||||
Reference in New Issue
Block a user