index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. const express = require("express");
  2. const bodyParser = require("body-parser");
  3. const Sequelize = require("sequelize");
  4. const jwt = require("jsonwebtoken");
  5. const { Op } = Sequelize;
  6. const { graphqlHTTP } = require("express-graphql");
  7. const { buildSchema } = require("graphql");
  8. const cors = require("cors");
  9. const expressJwt = require("express-jwt");
  10. const sha1 = require("sha1");
  11. // const mailer = require("./smtpGmail");
  12. const app = express();
  13. app.use(bodyParser.json());
  14. app.use(express.static("myproject"));
  15. // app.use(errorHandler);
  16. app.use(bodyParser.urlencoded({ extended: false }));
  17. app.use(cors());
  18. const sequelize = new Sequelize("emrada2", "root", "Emmanuil2228125%", {
  19. timezone: "+03:00",
  20. host: "localhost",
  21. dialect: "mysql",
  22. });
  23. class User extends Sequelize.Model {
  24. get messages() {
  25. return (async () => {
  26. let autorForMessage = await this.getAutor();
  27. let partnerForMessage = await this.getPartner();
  28. return [...autorForMessage, ...partnerForMessage];
  29. })();
  30. }
  31. get chat_groups() {
  32. return (async () => {
  33. let autorForChatGroup = await this.getAutor();
  34. let partnerForChatGroup = await this.getPartner();
  35. return [...autorForChatGroup, ...partnerForChatGroup];
  36. })();
  37. }
  38. }
  39. User.init(
  40. {
  41. email: Sequelize.STRING,
  42. // password: Sequelize.STRING,
  43. login: Sequelize.STRING,
  44. password: {
  45. type: Sequelize.STRING,
  46. set(value) {
  47. this.setDataValue("password", sha1(value));
  48. },
  49. },
  50. },
  51. { sequelize, modelName: "user" }
  52. );
  53. class Message extends Sequelize.Model {
  54. get user() {
  55. return this.User();
  56. }
  57. }
  58. Message.init(
  59. { message: Sequelize.STRING },
  60. {
  61. scopes: {
  62. deleted: {
  63. where: {
  64. id: 1
  65. },
  66. },
  67. },
  68. sequelize,
  69. modelName: "message",
  70. }
  71. );
  72. class ChatGroup extends Sequelize.Model {}
  73. ChatGroup.init({}, { sequelize, modelName: "chat_group" });
  74. User.hasMany(Message, { as: "autorForMessage", foreignKey: "autorId" });
  75. User.hasMany(Message, { as: "partnerForMessage", foreignKey: "partnerId" });
  76. Message.belongsTo(User, { as: "autor", sourceKey: "autorId" });
  77. Message.belongsTo(User, { as: "partner", sourceKey: "partnerId" });
  78. User.hasMany(ChatGroup, { as: "autorForChatGroup", foreignKey: "autorId" });
  79. User.hasMany(ChatGroup, { as: "partnerForChatGroup", foreignKey: "partnerId" });
  80. ChatGroup.belongsTo(User, { as: "autor", sourceKey: "autorId" });
  81. ChatGroup.belongsTo(User, { as: "partner", sourceKey: "partnerId" });
  82. const secret = `7.!BMB?Y+Bc2vZE-Hb5YuCT6QvE^FN,JWN6M?_VtFXeC5dLtB!`;
  83. const authenticate = async ({ login, password }) => {
  84. const user = await User.findOne({ where: { login, password } });
  85. if (user) {
  86. const token = jwt.sign(
  87. { sub: { id: user.id, email: user.email, login: user.login } },
  88. secret
  89. );
  90. return token;
  91. }
  92. };
  93. var schema = buildSchema(`
  94. type Query {
  95. getLogin(login: String, password: String): String
  96. getUser(email: String): User
  97. getAllUsers: [User]
  98. getMessage(id: ID!): Message
  99. getAllMessages: [Message]
  100. getAllMessagesOneUser(id: ID!): [Message]
  101. getChatGroup(id: ID!): ChatGroup
  102. getAllChatGroups: [ChatGroup]
  103. getAllChatGroupsOneUser(id: ID!): [ChatGroup]
  104. }
  105. type Mutation {
  106. deleteUser(id: ID!): String
  107. createUser(email: String, login: String, password: String): User
  108. changePassword(email: String, password: String): User
  109. createMessage(message: String, autorId: String, partnerId: String): Message
  110. changeMessage(id: ID!, message: String): Message
  111. deleteMessage(id: ID!): String
  112. createChatGroup(autorId: String, partnerId: String): Message
  113. deleteChatGroup(id: ID!): String
  114. }
  115. type User {
  116. id: Int
  117. createdAt: String
  118. email: String
  119. login: String
  120. }
  121. type Message {
  122. id: Int
  123. createdAt: String
  124. message: String
  125. autorId: User
  126. partnerId: User
  127. }
  128. type ChatGroup {
  129. id: Int
  130. createdAt: String
  131. autorId: User
  132. partnerId: User
  133. }
  134. `);
  135. const getUser = async ({ email }) => await User.findOne({ where: { email } });
  136. const getLogin = async ({ login, password }) => {
  137. const passwordSha1 = sha1(password);
  138. const userFind = await User.findOne({
  139. where: { login, password: passwordSha1 },
  140. });
  141. return authenticate(userFind);
  142. };
  143. const createUser = async ({ email, login, password }) => {
  144. const wasUserCreated = await User.findOne({ where: { email } });
  145. if (!wasUserCreated) {
  146. const user = { email, login, password };
  147. const newUser = new User(user);
  148. await newUser.save();
  149. return await User.findOne({ where: { login } });
  150. } else console.error("error");
  151. };
  152. const deleteUser = async ({ id }) => {
  153. const userFind = await User.findByPk(id);
  154. if (userFind) {
  155. await User.destroy({ where: { id } });
  156. return "User deleted";
  157. } else return "User not find";
  158. };
  159. const changePassword = async ({ email, password }) => {
  160. var userFind = await User.findOne({ where: { email } });
  161. if (userFind) {
  162. const a = await User.update(
  163. { password, login: userFind.login },
  164. { where: { email } }
  165. );
  166. userFind.email = "The password has been change";
  167. console.log(a);
  168. return userFind;
  169. } else {
  170. userFind = { email: "Email not found" };
  171. return userFind;
  172. }
  173. };
  174. const getAllUsers = async () => await User.findAll();
  175. const getAllMessages = async () => {
  176. const foundAllMessages = await Message.findAll();
  177. for (var allMessages of foundAllMessages) {
  178. const autor = await User.findAll({ where: { id: allMessages.autorId } });
  179. const partner = await User.findAll({
  180. where: { id: allMessages.partnerId },
  181. });
  182. allMessages.autorId = autor[0];
  183. allMessages.partnerId = partner[0];
  184. }
  185. return foundAllMessages;
  186. };
  187. const getMessage = async ({ id }) => {
  188. const message = await Message.findOne({ where: { id } });
  189. const autor = await User.findOne({ where: { id: message.autorId } });
  190. const partner = await User.findOne({ where: { id: message.partnerId } });
  191. message.autorId = autor;
  192. message.partnerId = partner;
  193. return message;
  194. };
  195. const getAllMessagesOneUser = async ({ id }) => {
  196. const allMess = await Message.findAll();
  197. for (var key of allMess) {
  198. const autor = await User.findAll({ where: { id: key.autorId } });
  199. const partner = await User.findAll({ where: { id: key.partnerId } });
  200. const ma = autor[0].id === +id || partner[0].id === +id;
  201. if (ma === true) {
  202. const y = await Message.findAll({ where: { autorId: id } });
  203. const u = await Message.findAll({ where: { partnerId: id } });
  204. console.log(y);
  205. if ((y.length && u.length) !== 0) {
  206. const p = [...y, ...u];
  207. for (var key of p) {
  208. const r = await User.findAll({ where: { id: key.autorId } });
  209. const r1 = await User.findAll({ where: { id: key.partnerId } });
  210. key.autorId = r[0];
  211. key.partnerId = r1[0];
  212. }
  213. return p;
  214. } else if (y.length !== 0) {
  215. const pt = [...y];
  216. for (var key of pt) {
  217. const r = await User.findAll({ where: { id: key.partnerId } });
  218. key.autorId = autor[0];
  219. key.partnerId = r[0];
  220. }
  221. return pt;
  222. } else {
  223. const ptu = [...u];
  224. for (var key of ptu) {
  225. const r = await User.findAll({ where: { id: key.autorId } });
  226. key.autorId = r[0];
  227. key.partnerId = partner[0];
  228. }
  229. return ptu;
  230. }
  231. }
  232. }
  233. };
  234. const createMessage = async (obj) => {
  235. try {
  236. return await Message.create({ ...obj });
  237. } catch (e) {
  238. console.log(e);
  239. }
  240. };
  241. const changeMessage = async ({ id, message }) => {
  242. const putMess = await Message.findByPk(id);
  243. if (putMess) {
  244. await Message.update({ message }, { where: { id } });
  245. return await Message.findByPk(id);
  246. } else return { id: "Message not find" };
  247. };
  248. const deleteMessage = async ({ id }) => {
  249. // await Message.scope("deleted").findByPk(id);
  250. const messFind = await Message.findByPk(id);
  251. if (messFind) {
  252. await Message.destroy({ where: { id } });
  253. return "Message deleted";
  254. } else return "Message not find";
  255. };
  256. const getChatGroup = async ({id}) => {
  257. const chatGroup = await ChatGroup.findByPk(id)
  258. const autor = await User.findOne({ where: { id: chatGroup.autorId } });
  259. const partner = await User.findOne({ where: { id: chatGroup.partnerId } });
  260. chatGroup.autorId = autor;
  261. chatGroup.partnerId = partner;
  262. return chatGroup;
  263. }
  264. const getAllChatGroups = async () => {
  265. const foundAllChatGroups = await ChatGroup.findAll();
  266. for (var allUsers of foundAllChatGroups) {
  267. const autor = await User.findAll({ where: { id: allUsers.autorId } });
  268. const partner = await User.findAll({ where: { id: allUsers.partnerId } });
  269. allUsers.autorId = autor[0];
  270. allUsers.partnerId = partner[0];
  271. }
  272. return foundAllChatGroups;
  273. };
  274. const getAllChatGroupsOneUser = async ({ id }) => {
  275. const foundAllChatGroups = await ChatGroup.findAll();
  276. for (var allUsers of foundAllChatGroups) {
  277. const autor = await User.findAll({ where: { id: allUsers.autorId } });
  278. const partner = await User.findAll({ where: { id: allUsers.partnerId } });
  279. const ma = autor[0].id === +id || partner[0].id === +id;
  280. if (ma === true) {
  281. const y = await ChatGroup.findAll({ where: { autorId: id } });
  282. const u = await ChatGroup.findAll({ where: { partnerId: id } });
  283. if ((y.length && u.length) !== 0) {
  284. const p = [...y, ...u];
  285. for (var key of p) {
  286. const r = await User.findAll({ where: { id: key.autorId } });
  287. const r1 = await User.findAll({ where: { id: key.partnerId } });
  288. key.autorId = r[0];
  289. key.partnerId = r1[0];
  290. }
  291. return p;
  292. } else if (y.length !== 0) {
  293. const pt = [...y];
  294. for (var key of pt) {
  295. const r = await User.findAll({ where: { id: key.partnerId } });
  296. key.autorId = autor[0];
  297. key.partnerId = r[0];
  298. }
  299. return pt;
  300. } else {
  301. const ptu = [...u];
  302. for (var key of ptu) {
  303. const r = await User.findAll({ where: { id: key.autorId } });
  304. key.autorId = r[0];
  305. key.partnerId = partner[0];
  306. }
  307. return ptu;
  308. }
  309. } else console.log("bye");
  310. }
  311. };
  312. const createChatGroup = async (obj) => {
  313. try {
  314. const oneUserId = await ChatGroup.findOne({
  315. where: { autorId: obj.autorId, partnerId: obj.partnerId },
  316. });
  317. const twoUserId = await ChatGroup.findOne({
  318. where: { autorId: obj.partnerId, partnerId: obj.autorId },
  319. });
  320. if (!oneUserId && !twoUserId) {
  321. var newChatGroup = await ChatGroup.create({ ...obj });
  322. const autor = await User.findAll({ where: { id: newChatGroup.autorId } });
  323. const partner = await User.findAll({
  324. where: { id: newChatGroup.partnerId },
  325. });
  326. newChatGroup.autorId = autor[0];
  327. newChatGroup.partnerId = partner[0];
  328. return newChatGroup;
  329. }
  330. } catch (e) {
  331. return;
  332. }
  333. };
  334. const deleteChatGroup = async ({ id }) => {
  335. const messFind = await ChatGroup.findByPk(id);
  336. if (messFind) {
  337. await ChatGroup.destroy({ where: { id } });
  338. return "ChatGroup deleted";
  339. } else return "ChatGroup not find";
  340. };
  341. var root = {
  342. getUser,
  343. getLogin,
  344. createUser,
  345. deleteUser,
  346. getAllUsers,
  347. getMessage,
  348. changePassword,
  349. createMessage,
  350. changeMessage,
  351. deleteMessage,
  352. getAllMessages,
  353. getAllMessagesOneUser,
  354. getChatGroup,
  355. getAllChatGroups,
  356. getAllChatGroupsOneUser,
  357. createChatGroup,
  358. deleteChatGroup,
  359. };
  360. app.use(
  361. "/graphql",
  362. graphqlHTTP({
  363. schema: schema,
  364. rootValue: root,
  365. graphiql: true,
  366. })
  367. );
  368. app.get("/users", async (req, res) => res.send(await User.findAll()));
  369. app.get("/message", async (req, res) => res.send(await Message.findAll()));
  370. app.get("/chat-group", async (req, res) => res.send(await ChatGroup.findAll()));
  371. // function errorHandler(err, req, res, next) {
  372. // if (typeof err === "string") {
  373. // return res.status(400).json({ message: err });
  374. // }
  375. // if (err.name === "UnauthorizedError") {
  376. // return res.status(401).json({ message: "Invalid Token" });
  377. // }
  378. // return res.status(500).json({ message: err.message });
  379. // }
  380. app.post("/users/authenticate", async (req, res, next) => {
  381. authenticate(req.body)
  382. .then((user) => {
  383. user
  384. ? res.json(user)
  385. : res
  386. .status(400)
  387. .json({ message: "Username or password is incorrect" });
  388. })
  389. .catch((err) => next(err));
  390. });
  391. // app.use(jwtWare());
  392. // (async () => {
  393. // let persone =
  394. // // await User.findOne({ where: { login: "B" } }) ||
  395. // (await User.create({ email: "ljkd@gfd.gfd", password: "1", login: "A" }))
  396. // })()
  397. // createMessage({message: "Hello 1", autorId: 1, partnerId: 2})
  398. // createChatGroup({ autorId: 1, partnerId: 2})
  399. sequelize.sync();
  400. app.listen(3330, () => console.log("The server started on port 3330"));