index.js 11 KB

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