anon.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const { buildSchema } = require('graphql');
  2. const jwt = require('jsonwebtoken')
  3. module.exports = ({Savable, secret}) => {
  4. class User extends Savable {
  5. async getACL(){
  6. return [this._id.toString(), "user"]
  7. }
  8. }
  9. Savable.addClass(User)
  10. const anonResolvers = {
  11. createUser:async function ({login, password}){
  12. let user = await Savable.m.User.findOne({login, password})
  13. if (user)
  14. return null;
  15. user = await (new User({login, password})).save()
  16. user.___owner = user._id.toString()
  17. user.___permissions = {
  18. read: ["owner", "user"]
  19. }
  20. return await user.save()
  21. },
  22. async login({login, password}){
  23. const user = await Savable.m.User.findOne({login, password})
  24. if (!user)
  25. return null;
  26. const token = jwt.sign({ sub: {id: user._id, login, acl: await user.getACL()}}, secret); //подписывам токен нашим ключем
  27. return token
  28. },
  29. changePassword:async function ({login, password, newPassword}){
  30. const user = await Savable.m.User.findOne({login, password})
  31. if (!user) return null;
  32. user.password = newPassword;
  33. return await user.save()
  34. },
  35. }
  36. const anonSchema = buildSchema(`
  37. type Query {
  38. login(login: String!, password: String!): String
  39. }
  40. type Mutation {
  41. createUser(login: String!, password: String!): User
  42. changePassword(login: String!, password: String!, newPassword: String!): User
  43. }
  44. type User {
  45. _id: String
  46. login: String
  47. }
  48. `)
  49. return {anonResolvers, anonSchema}
  50. }