index.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. const ObjectID = require("mongodb").ObjectID;
  2. const jwt = require('jsonwebtoken')
  3. const jwtSecret = 'CbymrfGfnB'
  4. const expressJwt = require('express-jwt');
  5. const anonResolvers = ['login', 'createUser'];
  6. ;(async () => {
  7. const {Savable, slice, getModels} = await require('./models.js')('cb')
  8. class User extends Savable {
  9. static get relations(){
  10. return {
  11. events: "users"
  12. }
  13. }
  14. }
  15. Savable.addClass(User)
  16. const express = require('express');
  17. const express_graphql = require('express-graphql');
  18. const { buildSchema } = require('graphql');
  19. const schema = buildSchema(`
  20. type Query {
  21. login(login: String!, password: String!): String
  22. events: [Event]
  23. event(eventId: String!): Event
  24. eventMoneysByEvent(eventId: String!): [EventMoney]
  25. eventMoneys: [EventMoney]
  26. }
  27. type Mutation {
  28. createUser(login: String!, password: String!): User
  29. changePassword(password: String!): User
  30. createEvent(name: String!, total: Float!):Event
  31. changeEvent(eventId:String!, name: String!, total: Float!):Event
  32. createEventMoney(eventId: String!, amount: Float):EventMoney
  33. }
  34. type User {
  35. _id: String
  36. login: String
  37. nick : String
  38. moneyEvents: [EventMoney]
  39. }
  40. type Event {
  41. _id: String
  42. name: String
  43. moneyEvents: [EventMoney]
  44. owner: String,
  45. total: Float,
  46. usersSum: Float,
  47. moneyDiff: Float,
  48. avg: Float
  49. }
  50. type EventMoney {
  51. _id: String
  52. user: User
  53. event: Event
  54. amount: Float
  55. owner: String
  56. avgDiff: Float
  57. }
  58. `);
  59. var app = express();
  60. app.use(express.static('public'));
  61. const rootResolvers = {
  62. createUser:async function ({login, password}){
  63. let user = await Savable.m.User.findOne({login, password})
  64. if (user)
  65. return null;
  66. user = await (new User({login, password})).save()
  67. user.___owner = user._id.toString()
  68. user.___permissions = {
  69. read: ["owner", "user"]
  70. }
  71. return await user.save()
  72. },
  73. login: async function({login, password}){
  74. const user = await Savable.m.User.findOne({login, password})
  75. if (!user)
  76. return null;
  77. const token = jwt.sign({ sub: {id: user._id, login}}, jwtSecret); //подписывам токен нашим ключем
  78. return token
  79. },
  80. changePassword:async function ({password}, {jwt: {id}, models: {SlicedSavable, User}} ){
  81. id = new ObjectID(id)
  82. const user = await SlicedSavable.m.User.findOne({_id: id})
  83. if (!user)
  84. return null;
  85. user.password = password;
  86. return await user.save()
  87. },
  88. async createEvent({name, total}, {jwt: {id}, models: {Event}}){
  89. return await (new Event({name, total})).save()
  90. },
  91. async changeEvent({eventId, name, total}, {jwt: {id}, models: {SlicedSavable}}){
  92. const event = await SlicedSavable.m.Event.findOne({_id: ObjectID(eventId)})
  93. if (!event)
  94. return null;
  95. event.name = name
  96. event.total = total
  97. return await event.save()
  98. },
  99. async events({}, {jwt: {id}, models: {SlicedSavable}}){
  100. let events = []
  101. for (let event of SlicedSavable.m.Event.find({})){
  102. event = await event
  103. //const {_id, name, owner, moneyEvents, usersSum, moneyDiff, total} = event
  104. //event = {_id, name, owner, moneyEvents, usersSum: await event.usersSum, total}
  105. //console.log(event)
  106. events.push(event)
  107. }
  108. return events;
  109. },
  110. async event({eventId}, {jwt: {id}, models: {SlicedSavable}}){
  111. return await SlicedSavable.m.Event.findOne({_id: ObjectID(eventId)});
  112. },
  113. async createEventMoney({eventId, amount}, {jwt: {id}, models: {SlicedSavable, EventMoney}}){
  114. let eventMoney = await SlicedSavable.m.EventMoney.findOne({"user._id": ObjectID(id), "event._id": ObjectID(eventId)})
  115. if (eventMoney){
  116. eventMoney.amount = amount;
  117. return await eventMoney.save()
  118. }
  119. const event = await SlicedSavable.m.Event.findOne({_id: ObjectID(eventId)})
  120. if (!event)
  121. return null;
  122. const me = await SlicedSavable.m.User.findOne({_id: ObjectID(id)})
  123. if (!me)
  124. return null;
  125. return await (new EventMoney({user: me, event, amount})).save()
  126. },
  127. async eventMoneysByEvent({eventId}, {jwt: {id}, models: {SlicedSavable}}){
  128. const event = await SlicedSavable.m.Event.findOne({_id: ObjectID(eventId)});
  129. if (!event)
  130. return null
  131. const moneys = [];
  132. for (let money of event.moneyEvents){
  133. try {
  134. await money
  135. console.log(money)
  136. }
  137. catch (e){
  138. console.log('skip no access user' ,e)
  139. }
  140. moneys.push(money)
  141. console.log('in loop')
  142. }
  143. console.log('after loop')
  144. return moneys;
  145. },
  146. async eventMoneys({}, {jwt: {id}, models: {SlicedSavable}}){
  147. const me = await SlicedSavable.m.User.findOne({_id: ObjectID(id)});
  148. if (!me)
  149. return null
  150. const moneys = [];
  151. for (let money of me.moneyEvents){
  152. moneys.push(await money)
  153. }
  154. return moneys;
  155. },
  156. }
  157. app.use('/graphql', express_graphql(async (req, res, gql) => {
  158. if (gql.operationName === null || anonResolvers.includes(gql.operationName))
  159. return {
  160. schema: schema,
  161. rootValue: rootResolvers,
  162. graphiql: true,
  163. }
  164. const authorization = req.headers.authorization
  165. if (authorization && authorization.startsWith('Bearer ')){
  166. console.log('token provided')
  167. const token = authorization.substr("Bearer ".length)
  168. const decoded = jwt.verify(token, jwtSecret)
  169. if (decoded){
  170. console.log('token verified', decoded)
  171. let slicedModels = getModels(decoded.sub.id)
  172. return {
  173. schema: schema,
  174. rootValue: rootResolvers,
  175. graphiql: true,
  176. context: {jwt: decoded.sub,
  177. models: slicedModels}
  178. }
  179. }
  180. }
  181. }))
  182. app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
  183. })()