const { forwardTo } = require('prisma-binding') const bcrypt = require('bcryptjs') const jwt = require('jsonwebtoken') const LoginError = new Error('Login required.') const PermissionError = new Error('No permission.') const Query = { currentUser: (parent, args, context, info) => { if (!context.request.userId) throw LoginError return context.db.query.user({ where: { id: context.request.userId } }, info) } } const Mutation = { createUser: async (parent, args, context, info) => { if (!context.request.userId) throw LoginError const user = await context.db.query.user({ where: { id: context.request.userId } }, info) if (!user.) const email = args.email.toLowerCase() const password = await bcrypt.hash(args.password, 10) return context.db.mutation.createUser( { data: { ...args, email, password } }, info ) }, 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.' }, requestPassword: async (parent, args, context, info) => { }, resetPassword: async (parent, args, context, info) => { }, updateUser: async (parent, args, context, info) => { }, deleteUser: async (parent, args, context, info) => { } } const resolvers = { Query, Mutation } module.exports = { resolvers }