index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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(id: ID!): 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 ({ id }) => await User.findByPk(id);
  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 m =
  200. allUsers.autorId === autor[0].id || allUsers.autorId === partner[0].id;
  201. const ma = autor[0].id === +id || partner[0].id === +id;
  202. if ((m === ma) === true) {
  203. const y = await ChatGroup.findAll({ where: { autorId: id } });
  204. const u = await ChatGroup.findAll({ where: { partnerId: id } });
  205. if (y && u) {
  206. const p = [...y, ...u];
  207. for (var key of p) {
  208. key.autorId = autor[0];
  209. key.partnerId = partner[0];
  210. }
  211. return p;
  212. } else if (y) return y;
  213. else return u;
  214. } else console.log("bye");
  215. }
  216. };
  217. const createChatGroup = async (obj) => {
  218. try {
  219. const oneUserId = await ChatGroup.findOne({
  220. where: { autorId: obj.autorId, partnerId: obj.partnerId },
  221. });
  222. const twoUserId = await ChatGroup.findOne({
  223. where: { autorId: obj.partnerId, partnerId: obj.autorId },
  224. });
  225. if (!oneUserId && !twoUserId) {
  226. var newChatGroup = await ChatGroup.create({ ...obj });
  227. const autor = await User.findAll({ where: { id: newChatGroup.autorId } });
  228. const partner = await User.findAll({
  229. where: { id: newChatGroup.partnerId },
  230. });
  231. newChatGroup.autorId = autor[0];
  232. newChatGroup.partnerId = partner[0];
  233. return newChatGroup;
  234. }
  235. } catch (e) {
  236. return;
  237. }
  238. };
  239. const deleteChatGroup = async ({ id }) => {
  240. const messFind = await ChatGroup.findByPk(id);
  241. if (messFind) {
  242. await ChatGroup.destroy({ where: { id } });
  243. return "ChatGroup deleted";
  244. } else return "ChatGroup not find";
  245. };
  246. var root = {
  247. getUser,
  248. getLogin,
  249. createUser,
  250. getAllUsers,
  251. getMessage,
  252. changePassword,
  253. createMessage,
  254. changeMessage,
  255. deleteMessage,
  256. getAllMessages,
  257. getAllChatGroups,
  258. getAllChatGroupsOneUser,
  259. createChatGroup,
  260. deleteChatGroup,
  261. };
  262. app.use(
  263. "/graphql",
  264. graphqlHTTP({
  265. schema: schema,
  266. rootValue: root,
  267. graphiql: true,
  268. })
  269. );
  270. app.get("/users", async (req, res) => res.send(await User.findAll()));
  271. app.get("/message", async (req, res) => res.send(await Message.findAll()));
  272. app.get("/chat-group", async (req, res) => res.send(await ChatGroup.findAll()));
  273. // app.post("/users", async (req, res) => {
  274. // // const twoUsers = async () => {
  275. // // const userEmail = await User.findOne({ where: { email: req.body.email } });
  276. // // if (userEmail !== null) console.log(err);
  277. // // else {
  278. // // console.log("hi");
  279. // var newUser = new User(req.body);
  280. // // const message = {
  281. // // to: req.body.email,
  282. // // subject: "Registered",
  283. // // text: `Отлично. Вот ваши данные:
  284. // // login: ${req.body.email}
  285. // // password: ${req.body.password}
  286. // // Перейдите по ссылке, чтобы войти в свой аккаунт
  287. // // url: http://localhost:3335/sign_in`,
  288. // // };
  289. // // mailer(message);
  290. // await newUser.save();
  291. // res.status(201).send(newUser);
  292. // // }
  293. // // };
  294. // // twoUsers();
  295. // });
  296. // function errorHandler(err, req, res, next) {
  297. // if (typeof err === "string") {
  298. // return res.status(400).json({ message: err });
  299. // }
  300. // if (err.name === "UnauthorizedError") {
  301. // return res.status(401).json({ message: "Invalid Token" });
  302. // }
  303. // return res.status(500).json({ message: err.message });
  304. // }
  305. app.post("/users/authenticate", async (req, res, next) => {
  306. authenticate(req.body)
  307. .then((user) => {
  308. user
  309. ? res.json(user)
  310. : res
  311. .status(400)
  312. .json({ message: "Username or password is incorrect" });
  313. })
  314. .catch((err) => next(err));
  315. });
  316. // app.use(jwtWare());
  317. app.get("/a", (req, res, next) => {
  318. console.log(req.headers.authorization);
  319. const token1 = req.headers.authorization;
  320. console.log(token1);
  321. // if (token) {
  322. const data = jwt.verify(token1, secret);
  323. console.log(data);
  324. // if (data) {
  325. console.log(data.sub.login);
  326. res.send(`<h1>Hello ${data.sub.login}</h1>`);
  327. // } else {
  328. // res.send(`<h1>Hello haker</h1>`);
  329. // }
  330. // }
  331. });
  332. // (async () => {
  333. // let persone =
  334. // // await User.findOne({ where: { login: "B" } }) ||
  335. // (await User.create({ email: "ljkd@gfd.gfd", password: "1", login: "A" }))
  336. // })()
  337. // createMessage({message: "Hello 1", autorId: 1, partnerId: 2})
  338. // createChatGroup({ autorId: 1, partnerId: 2})
  339. sequelize.sync();
  340. app.listen(3330, () => console.log("The server started on port 3330"));