Skip to content

Commit

Permalink
Add user registration, sign in, authaticated endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
liissee committed Feb 19, 2020
1 parent fc4d5c2 commit c3e46a0
Show file tree
Hide file tree
Showing 4 changed files with 147 additions and 16 deletions.
82 changes: 72 additions & 10 deletions backend/package-lock.json

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

3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
"@babel/core": "^7.8.3",
"@babel/node": "^7.8.3",
"@babel/preset-env": "^7.8.3",
"bcrypt-nodejs": "0.0.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"mongoose": "^5.8.10",
"mongoose": "^5.9.1",
"nodemon": "^2.0.2"
},
"devDependencies": {
Expand Down
70 changes: 69 additions & 1 deletion backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,37 @@ import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import mongoose from 'mongoose'
import crypto from "crypto"
import bcrypt from 'bcrypt-nodejs'

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/authAPI"
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true })
mongoose.Promise = Promise

const User = mongoose.model('User', {
name: {
type: String,
unique: true,
required: true,
minlength: 2,
maxlength: 20
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true,
minlength: 5
},
accessToken: {
type: String,
default: () => crypto.randomBytes(128).toString('hex')
}
})

// Defines the port the app will run on. Defaults to 8080, but can be
// overridden when starting the server. For example:
//
Expand All @@ -18,12 +44,54 @@ const app = express()
app.use(cors())
app.use(bodyParser.json())

const authenticateUser = async (req, res, next) => {
const user = await User.findOne({ accessToken: req.header('Authorization') })
if (user) {
req.user = user //what does this mean?
next() //when to use next? (calling the next() function which allows the proteced endpoint to continue execution)
} else {
res.status(401).json({ loggedOut: true })
}
}

// Start defining your routes here
app.get('/', (req, res) => {
res.send('Hello world')
res.send('Hello world!!!')
})

// Create user
// Database only saves correct users, but doesn't display error when incorrect users are posted
app.post('/user', async (req, res) => {
try {
const { name, email, password } = req.body
// Why not await when endpoint is async?
const user = new User({ name, email, password: bcrypt.hashSync(password) })
user.save()
res.status(201).json({ name: user.name, id: user._id, accessToken: user.accessToken })
} catch (err) {
res.status(400).json({ message: 'Could not create user', errors: err.errors })
}
})

app.post('/session', async (req, res) => {
const user = await User.findOne({ email: req.body.email })
if (user && bcrypt.compareSync(req.body.password, user.password)) {
res.json({ userId: user._id, accessToken: user.accessToken })
} else {
res.json({ notFound: true })
}
})

app.get('/secret', authenticateUser)
app.get('/secret', (req, res) => {
// res.json("Secreeeet")
res.json({ secret: 'this is a super secret meessage' }) //what is the difference: res.json and res.send?
})



// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})

8 changes: 4 additions & 4 deletions frontend/package-lock.json

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

0 comments on commit c3e46a0

Please sign in to comment.