anon.js 2.2 KB

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