Skip to content

Commit

Permalink
Back end almost done
Browse files Browse the repository at this point in the history
  • Loading branch information
Yeaseen committed May 16, 2021
1 parent d13e6bd commit fdff435
Show file tree
Hide file tree
Showing 8 changed files with 181 additions and 11 deletions.
4 changes: 3 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { query } = require('express')
const express = require('express')
require('dotenv').config()

const isAuth = require('./middleware/requireLogin')
const PORT = process.env.PORT || 5000
const { graphqlHTTP } = require('express-graphql')
const mongoose = require('mongoose')
Expand All @@ -24,6 +24,8 @@ mongoose.connection.on('error', (err) => {
const graphqlSchema = require('./graphql/schema/index')
const graphqlResolvers = require('./graphql/resolvers/index')

app.use(isAuth)

app.use(
'/graphql',
graphqlHTTP({
Expand Down
24 changes: 24 additions & 0 deletions graphql/resolvers/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const bcrypt = require('bcryptjs')
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
require('../../models/user')

const User = mongoose.model('User')
Expand All @@ -24,5 +25,28 @@ module.exports = {
} catch (err) {
throw err
}
},
login: async ({ email, password }) => {
//console.log(email)
const savedUser = await User.findOne({ email: email })
if (!savedUser) {
throw new Error('Invalid Email or Password')
}
const isEqual = await bcrypt.compare(password, savedUser.password)
if (isEqual) {
throw new Error('Invalid Email or Password')
}
const token = jwt.sign(
{ userId: savedUser.id, email: savedUser.email },
process.env.JWT_SECRET,
{
expiresIn: '1h'
}
)
return {
userId: savedUser._id,
token: token,
tokenExpiration: 1
}
}
}
17 changes: 13 additions & 4 deletions graphql/resolvers/booking.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ const { transformedBooking } = require('./merge')
const Booking = mongoose.model('Booking')

module.exports = {
bookings: async () => {
bookings: async (args, req) => {
if (!req.isAuth) {
throw new Error('Unauthenticated!')
}
try {
const bookings = await Booking.find()
return bookings.map((booking) => {
Expand All @@ -15,11 +18,14 @@ module.exports = {
throw err
}
},
bookEvent: async (args) => {
bookEvent: async (args, req) => {
if (!req.isAuth) {
throw new Error('Unauthenticated!')
}
try {
const fetchedEvent = await Event.findById({ _id: args.eventId })
const booking = new Booking({
user: '609f61da4263fa0a88e0af1d',
user: req.userId,
event: fetchedEvent
})
const result = await booking.save()
Expand All @@ -28,7 +34,10 @@ module.exports = {
throw err
}
},
cancelBooking: async (args) => {
cancelBooking: async (args, req) => {
if (!req.isAuth) {
throw new Error('Unauthenticated!')
}
try {
const booking = await Booking.findById(args.bookingId).populate('event')
const event = transformedEvent(booking.event)
Expand Down
12 changes: 8 additions & 4 deletions graphql/resolvers/events.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const mongoose = require('mongoose')
require('../../models/event')

require('../../models/user')
const User = mongoose.model('User')
const Event = mongoose.model('Event')
const { transformedEvent } = require('./merge')

Expand All @@ -15,13 +16,16 @@ module.exports = {
throw err
}
},
createEvent: async (args) => {
createEvent: async (args, req) => {
if (!req.isAuth) {
throw new Error('Unauthenticated!')
}
const event = new Event({
title: args.eventInput.title,
description: args.eventInput.description,
price: +args.eventInput.price,
date: new Date(args.eventInput.date),
creator: '609f61da4263fa0a88e0af1d'
creator: req.userId
})

let createdEvent
Expand All @@ -30,7 +34,7 @@ module.exports = {
const result = await event.save()

createdEvent = transformedEvent(result)
const creator = await User.findById('609f61da4263fa0a88e0af1d')
const creator = await User.findById(req.userId)
if (!creator) {
throw new Error('Creator not FOUND!')
}
Expand Down
7 changes: 7 additions & 0 deletions graphql/schema/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ type User {
createdEvents: [Event!]
}
type AuthData {
userId: ID!
token: String!
tokenExpiration: Int!
}
input UserInput {
email: String!
password: String!
Expand All @@ -38,6 +44,7 @@ input EventInput {
type RootQuery {
events: [Event!]!
bookings: [Booking!]!
login(email: String!, password: String!): AuthData!
}
type RootMutation {
Expand Down
33 changes: 33 additions & 0 deletions middleware/requireLogin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const jwt = require('jsonwebtoken')
require('dotenv').config()

module.exports = (req, res, next) => {
const authorization = req.get('Authorization')
//authorization = Bearer hdjhsabdjh(generated token from jsonwebtoken)
if (!authorization) {
req.isAuth = false
return next()
}
const token = authorization.replace('Bearer ', '')

if (!token || token === '') {
req.isAuth = false
return next()
}
let decodedToken
try {
decodedToken = jwt.verify(token, process.env.JWT_SECRET)
} catch (error) {
req.isAuth = false
return next()
}

if (!decodedToken) {
req.isAuth = false
return next()
}

req.isAuth = true
req.userId = decodedToken.userId
next()
}
94 changes: 92 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"express": "^4.17.1",
"express-graphql": "^0.12.0",
"graphql": "^15.5.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.12.9"
},
"devDependencies": {
Expand Down

0 comments on commit fdff435

Please sign in to comment.