Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions api/models/guest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require('mongoose')

const schema = mongoose.Schema({
username: String,
password: String
})

module.exports = mongoose.model('Guest', schema)
82 changes: 82 additions & 0 deletions api/routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const router = require('express').Router()
const Guest = require('../models/guest')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')

const {SECRET_KEY} = process.env

router.get('/profile', async (req, res, next) => {
try {
const token = req.headers.authorization.split('Bearer ')[1] // we define the token as the second object in the authorization array
const payload = jwt.verify(token, SECRET_KEY) //we verify the token and the secret_key
const guest = await Guest.findOne({ _id: payload.id }).select('-__v -password') // we find the user account associated with the user id

const status = 200 // success status
res.json({ status, guest })
} catch (e) {
console.error(e)
const error = new Error('You are not authorized to access this route.')
error.status = 401
next(error)
}
})

router.post('/signup', async (req, res, next) => {
const status = 201
try {
const { username, password } = req.body
const guest = await Guest.findOne({ username })
if (guest) throw new Error(`User ${username} already exists`)

const saltRounds = 10
const hashedPassword = await bcrypt.hash(password, saltRounds)
const newGuest = await Guest.create({
username,
password: hashedPassword
})

// Create a JWT
const payload = { id: newGuest._id } // set up payload
const options = { expiresIn: '1 day' } // sets up expiration
const token = jwt.sign(payload, SECRET_KEY, options)

// if all is well, responde with success message
res.status(status).json({ status, token })
} catch (e) {
console.error(e)
const error = new Error(`You can't come to this party.`)
error.status = 400
next(error)
}
})

router.post('/login', async (req, res, next) => {
const status = 201
try {
const { username, password } = req.body
// find user by username
const guest = await Guest.findOne({ username })
// if it doesnt exists, throw an error
if (!guest) throw new Error(`Username could not be found`)

// if it does exist, compare the plain text password to the hashed version
const isValid = await bcrypt.compare(password, guest.password)
// if validation fails, throw an error
if (!isValid) throw new Error(`Password is not valid.`)

// Create a JWT
const payload = { id: guest._id } // set up payload
const options = { expiresIn: '1 day' } // sets up expiration
const token = jwt.sign(payload, SECRET_KEY, options)

// if all is well, responde with success message
res.status(status).json({ status, token })
} catch (e) {
console.error(e)
const error = new Error(`Login credentials incorrect.`)
error.status = 400
next(error)
}
})

module.exports = router
29 changes: 26 additions & 3 deletions api/routes/parties.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,34 @@
const router = require('express').Router()
const Guest = require('../models/guest')
const Party = require('../models/party')
const jwt = require('jsonwebtoken')

const {SECRET_KEY} = process.env

router.get('/', async (req, res, next) => {
const status = 200
const response = await Party.find().select('-__v')
try {
const token = req.headers.authorization.split('Bearer ')[1]
const payload = jwt.verify(token, SECRET_KEY)
const guest = await Guest.findOne({ _id: payload.id }).select('-__v -password')
let parties
console.log(guest)
if (guest){
let parties = await Party.find().select('-__v')
console.log("you have access")
console.log(parties)
} else {
console.log("you dont have access")
let parties = await Party.find().select('false')
}

res.json({ status, response })
const status = 200 // success status
res.status(status).json({ status, parties })
} catch (e) {
console.error(e)
const error = new Error('You are not authorized to access this route.')
error.status = 401
next(error)
}
})

router.get('/exclusive', async (req, res, next) => {
Expand Down
1 change: 1 addition & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ if (NODE_ENV === 'development') app.use(require('morgan')('dev'))
app.use(require('body-parser').json())

// Routes
app.use('/api/', require('./api/routes/auth'))
app.use('/api/parties', require('./api/routes/parties'))

// Not Found Handler
Expand Down
4 changes: 3 additions & 1 deletion db/seeds.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ const Party = require('../api/models/party')
const config = require('../nodemon.json')

const reset = async () => {
mongoose.connect(config.env.MONGO_DB_CONNECTION, { useNewUrlParser: true })
mongoose.connect(config.env.MONGO_DB_CONNECTION, {
useNewUrlParser: true
})
await Party.deleteMany() // Deletes all records
return await Party.create([
{ name: 'Oooooontz' },
Expand Down
3 changes: 2 additions & 1 deletion nodemon.sample.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"env": {
"MONGO_DB_CONNECTION": "",
"NODE_ENV": "development",
"PORT": 5000
"PORT": 5000,
"SECRET_KEY": "MYSECRETKEY"
}
}
Loading