index.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. User.init(
  24. {
  25. email: Sequelize.STRING,
  26. password: Sequelize.STRING,
  27. login: Sequelize.STRING,
  28. },
  29. { sequelize, modelName: "user" }
  30. );
  31. class Message extends Sequelize.Model {}
  32. Message.init(
  33. { message: Sequelize.STRING },
  34. { sequelize, modelName: "message" }
  35. );
  36. // class Transaction extends Sequelize.Model {}
  37. // Transaction.init(
  38. // { amount: Sequelize.DECIMAL },
  39. // {
  40. // sequelize,
  41. // modelName: "transaction",
  42. // scopes: {
  43. // before(date) {
  44. // return {
  45. // where: {
  46. // createdAt: {
  47. // [Op.lte]: date,
  48. // },
  49. // },
  50. // };
  51. // },
  52. // },
  53. // }
  54. // );
  55. User.hasMany(Message, {});
  56. Message.belongsTo(User, {});
  57. // Money.hasMany(Transaction, { as: "ins", foreignKey: "inId" });
  58. // Money.hasMany(Transaction, { as: "outs", foreignKey: "outId" });
  59. // Transaction.belongsTo(Money, { as: "in", sourceKey: "inId" });
  60. // Transaction.belongsTo(Money, { as: "out", sourceKey: "outId" });
  61. const secret = `7.!BMB?Y+Bc2vZE-Hb5YuCT6QvE^FN,JWN6M?_VtFXeC5dLtB!`;
  62. const secretPass = "JcFWhuLkpaK9aB3Gtbvo2Y0BApdw5q1tUyAyJeD8fJXs78d7zR";
  63. const authenticate = async ({ email, password }) => {
  64. const user = await User.findOne({ where: { email, password } });
  65. if (user) {
  66. const token = jwt.sign({ sub: { id: user.id, email: user.email } }, secret);
  67. return token;
  68. }
  69. };
  70. var schema = buildSchema(`
  71. type Query {
  72. getLogin(login: String, password: String): String
  73. getUser(id: ID!): User
  74. getMessage(id: ID!): Message
  75. }
  76. type Mutation {
  77. createUser(email: String, password: String, login: String): User
  78. }
  79. type User {
  80. id: Int
  81. createdAt: String
  82. email: String
  83. login: String
  84. }
  85. type Message {
  86. id: Int
  87. createdAt: String
  88. message: String
  89. userId: User
  90. }
  91. `);
  92. const getUser = async ({ id }) => await User.findByPk(id);
  93. const getMessage = async ({ id }) => {
  94. return await Message.findByPk(id) || getUser()
  95. };
  96. const getLogin = async ({ login, password }) => {
  97. const userFind = await User.findOne({ where: { login, password } });
  98. return authenticate(userFind);
  99. };
  100. const createUser = async ({ email, password, login }) => {
  101. const wasUserCreated = await User.findOne({ where: { email } });
  102. if (!wasUserCreated) {
  103. // const passwordModification = jwt.sign(password + secretPass, secret);
  104. const user = { email, password, login };
  105. const newUser = new User(user);
  106. await newUser.save();
  107. return await User.findOne({ where: { login } });
  108. } else console.error("error");
  109. };
  110. var root = { getUser, getLogin, createUser, getMessage };
  111. app.use(
  112. "/graphql",
  113. graphqlHTTP({
  114. schema: schema,
  115. rootValue: root,
  116. graphiql: true,
  117. })
  118. );
  119. app.get("/users", async (req, res) => res.send(await User.findAll()));
  120. app.get("/message", async (req, res) => res.send(await Message.findAll()));
  121. // app.post("/users", async (req, res) => {
  122. // // const twoUsers = async () => {
  123. // // const userEmail = await User.findOne({ where: { email: req.body.email } });
  124. // // if (userEmail !== null) console.log(err);
  125. // // else {
  126. // // console.log("hi");
  127. // var newUser = new User(req.body);
  128. // // const message = {
  129. // // to: req.body.email,
  130. // // subject: "Registered",
  131. // // text: `Отлично. Вот ваши данные:
  132. // // login: ${req.body.email}
  133. // // password: ${req.body.password}
  134. // // Перейдите по ссылке, чтобы войти в свой аккаунт
  135. // // url: http://localhost:3335/sign_in`,
  136. // // };
  137. // // mailer(message);
  138. // await newUser.save();
  139. // res.status(201).send(newUser);
  140. // // }
  141. // // };
  142. // // twoUsers();
  143. // });
  144. app.get("/login", async (req, res) => {
  145. res.send(await User.findAll());
  146. });
  147. // function errorHandler(err, req, res, next) {
  148. // if (typeof err === "string") {
  149. // return res.status(400).json({ message: err });
  150. // }
  151. // if (err.name === "UnauthorizedError") {
  152. // return res.status(401).json({ message: "Invalid Token" });
  153. // }
  154. // return res.status(500).json({ message: err.message });
  155. // }
  156. app.post("/users/authenticate", async (req, res, next) => {
  157. authenticate(req.body)
  158. .then((user) => {
  159. user
  160. ? res.json(user)
  161. : res
  162. .status(400)
  163. .json({ message: "Username or password is incorrect" });
  164. })
  165. .catch((err) => next(err));
  166. });
  167. // app.use(jwtWare());
  168. app.get("/a", (req, res, next) => {
  169. console.log(req.headers.authorization);
  170. const token1 = req.headers.authorization;
  171. console.log(token1);
  172. // if (token) {
  173. const data = jwt.verify(token1, secret);
  174. console.log(data);
  175. // if (data) {
  176. console.log(data.sub.login);
  177. res.send(`<h1>Hello ${data.sub.login}</h1>`);
  178. // } else {
  179. // res.send(`<h1>Hello haker</h1>`);
  180. // }
  181. // }
  182. });
  183. // (async () => {
  184. // let persone =
  185. // // User.findOne({ where: { login: "David" } }) ||
  186. // (await User.create({ email: "gfd@gfd.gfd", password: "1", login: "A" }))
  187. // persone.createMessage({message: "Hello"})
  188. // })();
  189. sequelize.sync();
  190. app.listen(3330, () => console.log("The server started on port 3330"));