resolvers.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const { forwardTo } = require('prisma-binding')
  2. const bcrypt = require('bcryptjs')
  3. const jwt = require('jsonwebtoken')
  4. const LoginError = new Error('Login required.')
  5. const PermissionError = new Error('No permission.')
  6. const Query = {
  7. currentUser: (parent, args, context, info) => {
  8. if (!context.request.userId) throw LoginError
  9. return context.db.query.user({
  10. where: { id: context.request.userId }
  11. }, info)
  12. }
  13. }
  14. const Mutation = {
  15. createUser: async (parent, args, context, info) => {
  16. if (!context.request.userId) throw LoginError
  17. const user = await context.db.query.user({
  18. where: { id: context.request.userId }
  19. }, info)
  20. if (!user.)
  21. const email = args.email.toLowerCase()
  22. const password = await bcrypt.hash(args.password, 10)
  23. return context.db.mutation.createUser(
  24. {
  25. data: {
  26. ...args,
  27. email,
  28. password
  29. }
  30. },
  31. info
  32. )
  33. },
  34. signup: async (parent, args, ctx, info) => {
  35. const email = args.email.toLowerCase()
  36. const password = await bcrypt.hash(args.password, 10)
  37. const user = await ctx.db.mutation.createUser(
  38. {
  39. data: {
  40. ...args,
  41. email,
  42. password
  43. }
  44. },
  45. info
  46. )
  47. const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
  48. ctx.response.cookie('token', token, {
  49. httpOnly: true,
  50. maxAge: 24 * 60 * 60 * 1000
  51. })
  52. return user
  53. },
  54. login: async (parent, args, context, info) => {
  55. const { email, password } = args
  56. const user = await context.db.query.user({ where: { email } })
  57. if (!user) throw new Error('User not found')
  58. const valid = await bcrypt.compare(password, user.password)
  59. if (!valid) throw new Error('Invalid password')
  60. const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
  61. context.response.cookie(
  62. 'token',
  63. token,
  64. {
  65. httpOnly: true,
  66. maxAge: 7 * 24 * 3600 * 1000
  67. },
  68. info
  69. )
  70. return user
  71. },
  72. logout: async (parent, args, context, info) => {
  73. context.response.clearCookie('token')
  74. return 'Logged out.'
  75. },
  76. requestPassword: async (parent, args, context, info) => {
  77. },
  78. resetPassword: async (parent, args, context, info) => {
  79. },
  80. updateUser: async (parent, args, context, info) => {
  81. },
  82. deleteUser: async (parent, args, context, info) => {
  83. }
  84. }
  85. const resolvers = {
  86. Query,
  87. Mutation
  88. }
  89. module.exports = { resolvers }