index.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. const ObjectID = require("mongodb").ObjectID;
  2. const jwt = require('jsonwebtoken')
  3. const jwtSecret = 'CbymrfGfnB'
  4. const anonResolvers = ['login', 'createUser'];
  5. ;(async () => {
  6. const {Savable, slice, getModels} = await require('./models.js')('cb')
  7. class User extends Savable {
  8. //static get relations(){
  9. //return {
  10. //events: "users"
  11. //}
  12. //}
  13. }
  14. Savable.addClass(User)
  15. const express = require('express');
  16. const express_graphql = require('express-graphql');
  17. const { buildSchema } = require('graphql');
  18. const schema = buildSchema(`
  19. type Query {
  20. login(login: String!, password: String!): String
  21. events: [Event]
  22. event(eventId: String!): Event
  23. eventMoneysByEvent(eventId: String!): [EventMoney]
  24. eventMoneys: [EventMoney]
  25. }
  26. type Mutation {
  27. createUser(login: String!, password: String!): User
  28. changePassword(password: String!): User
  29. createEvent(name: String!, total: Float!):Event
  30. changeEvent(eventId:String!, name: String!, total: Float!):Event
  31. createEventMoney(eventId: String!, amount: Float):EventMoney
  32. }
  33. type User {
  34. _id: String
  35. login: String
  36. nick : String
  37. moneyEvents: [EventMoney]
  38. }
  39. type Event {
  40. _id: String
  41. name: String
  42. moneyEvents: [EventMoney]
  43. owner: String,
  44. total: Float,
  45. usersSum: Float,
  46. moneyDiff: Float,
  47. avg: Float
  48. }
  49. type EventMoney {
  50. _id: String
  51. user: User
  52. event: Event
  53. amount: Float
  54. owner: String
  55. avgDiff: Float
  56. }
  57. `);
  58. var app = express();
  59. app.use(express.static('public'));
  60. const rootResolvers = {
  61. createUser:async function ({login, password}){
  62. let user = await Savable.m.User.findOne({login, password})
  63. if (user)
  64. return null;
  65. user = await (new User({login, password})).save()
  66. user.___owner = user._id.toString()
  67. user.___permissions = {
  68. read: ["owner", "user"]
  69. }
  70. return await user.save()
  71. },
  72. login: async function({login, password}){
  73. console.log(Savable.classes)
  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, thisUser}}){
  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. if (!thisUser)
  123. return null;
  124. console.log(thisUser, event, amount)
  125. return await (new EventMoney({user: thisUser, 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.query){
  159. return {
  160. schema: schema,
  161. rootValue: rootResolvers,
  162. graphiql: true,
  163. }
  164. }
  165. const operationMatch = gql.query.match(/\{\s*([a-zA-Z]+)\s*/)
  166. const operationName = gql.operationName || operationMatch[1]
  167. console.log('before oper', operationName)
  168. if ((!operationName) || anonResolvers.includes(operationName)){
  169. return {
  170. schema: schema,
  171. rootValue: rootResolvers,
  172. graphiql: true,
  173. }
  174. }
  175. const authorization = req.headers.authorization
  176. console.log(authorization)
  177. if (authorization && authorization.startsWith('Bearer ')){
  178. console.log('token provided')
  179. const token = authorization.substr("Bearer ".length)
  180. const decoded = jwt.verify(token, jwtSecret)
  181. if (decoded){
  182. console.log('token verified', decoded)
  183. let slicedModels = await getModels(decoded.sub.id)
  184. return {
  185. schema: schema,
  186. rootValue: rootResolvers,
  187. graphiql: true,
  188. context: {jwt: decoded.sub,
  189. models: slicedModels}
  190. }
  191. }
  192. }
  193. console.log('bad end')
  194. }))
  195. app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
  196. })()