1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- const { forwardTo } = require('prisma-binding')
- const bcrypt = require('bcryptjs')
- const jwt = require('jsonwebtoken')
- const LoginError = new Error('You must be logged in.')
- const Query = {
- users: forwardTo('db'),
- trainings: forwardTo('db'),
- me: (parent, args, context, info) => {
- if (!context.request.userId) throw new Error('Not logged in.')
- return context.db.query.user({ where: { id: context.request.userId } }, info)
- }
- }
- const Mutation = {
- createUser: async (parent, args, context, info) => {
- const email = args.email.toLowerCase()
- const password = await bcrypt.hash(args.password, 10)
- console.log(email, password)
- const user = await context.db.mutation.createUser(
- {
- data: {
- ...args,
- email,
- password
- }
- },
- info
- )
- const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
- context.response.cookie('token', token, {
- httpOnly: true,
- maxAge: 7 * 24 * 3600 * 1000
- })
- return user
- },
- signup: async (parent, args, ctx, info) => {
- const email = args.email.toLowerCase()
- const password = await bcrypt.hash(args.password, 10)
- const user = await ctx.db.mutation.createUser(
- {
- data: {
- ...args,
- email,
- password
- }
- },
- info
- )
- const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
- ctx.response.cookie('token', token, {
- httpOnly: true,
- maxAge: 24 * 60 * 60 * 1000
- })
- return user
- },
- login: async (parent, args, context, info) => {
- const { email, password } = args
- const user = await context.db.query.user({ where: { email } })
- if (!user) throw new Error('User not found')
- const valid = await bcrypt.compare(password, user.password)
- if (!valid) throw new Error('Invalid password')
- const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET)
- context.response.cookie(
- 'token',
- token,
- {
- httpOnly: true,
- maxAge: 7 * 24 * 3600 * 1000
- },
- info
- )
- return user
- },
- logout: async (parent, args, context, info) => {
- context.response.clearCookie('token')
- return 'Logged out.'
- },
- createTraining: async (parent, args, context, info) => {
- const { userId } = context.request
- // if (!userId) throw LoginError
- const training = await context.db.mutation.createTraining(
- {
- data: args
- },
- info
- )
- return training
- }
- }
- const resolvers = {
- Query,
- Mutation
- }
- module.exports = { resolvers }
|