|
@@ -1,11 +1,52 @@
|
|
|
const { forwardTo } = require('prisma-binding')
|
|
|
+const bcrypt = require('bcryptjs')
|
|
|
+const jwt = require('jsonwebtoken')
|
|
|
+const { randomBytes } = require('crypto')
|
|
|
+const { promisify } = require('util')
|
|
|
|
|
|
const Query = {
|
|
|
projects: forwardTo('db'),
|
|
|
- connectionCommand: (parent, args, context, info) => 'Hello!'
|
|
|
+ connectionCommand: (parent, args, context, info) => 'Hello!',
|
|
|
+ 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 Mutations = {}
|
|
|
+const Mutations = {
|
|
|
+ createUser: async (parent, args, context, info) => {
|
|
|
+ const email = args.email.toLowerCase()
|
|
|
+ const password = await bcrypt.hash(args.password, 10)
|
|
|
+ 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
|
|
|
+ },
|
|
|
+ userLogin: 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
|
|
|
+ })
|
|
|
+ return user
|
|
|
+ }
|
|
|
+}
|
|
|
|
|
|
const resolvers = {
|
|
|
Query
|