Skip to content
Open

mvp #847

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
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ Your assignment page on Canvas should contain instructions for submitting this p

Write the following user access functions inside `api/users/users-model.js`:

- [ ] `find`
- [ ] `findBy`
- [ ] `findById`
- [ ] `add`
- [x ] `find`
- [ x] `findBy`
- [x ] `findById`
- [x ] `add`

#### 2B - Middleware Functions

Write the following auth middlewares inside `api/auth/auth-middleware.js`:

- [ ] `restricted`
- [ ] `checkUsernameFree`
- [ ] `checkPasswordLength`
- [ ] `checkUsernameExists`
- [ x] `restricted`
- [ x] `checkUsernameFree`
- [ x] `checkPasswordLength`
- [ x] `checkUsernameExists`

#### 2C - Endpoints

Expand Down
64 changes: 57 additions & 7 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
const express = require('express')
const User = require('../users/users-model')

/*
If the user does not have a session saved in the server

Expand All @@ -6,8 +9,12 @@
"message": "You shall not pass!"
}
*/
function restricted() {

const restricted = (req, res, next) => {
if (req.session.user) {
next()
} else {
res.status(401).json("You shall not pass!")
}
}

/*
Expand All @@ -18,8 +25,19 @@ function restricted() {
"message": "Username taken"
}
*/
function checkUsernameFree() {

function checkUsernameFree(req, res, next) {
User.findBy(req.body)
.then(response => {
if (response.length) {
res.status(422).json({ message: 'Username taken' })
}
else {
next()
}
})
.catch(err => {
res.status(500).json({ message: err.message })
})
}

/*
Expand All @@ -30,8 +48,28 @@ function checkUsernameFree() {
"message": "Invalid credentials"
}
*/
function checkUsernameExists() {

async function checkUsernameExists(req, res, next) {
// User.findBy({ username: req.body.username })
// .then(user => {
// if (user.username) {
// req.userData = user[0]
// next()
// }
// else {
// res.status(401).json({ message: 'invalid credentials' })
// }
// })
try {
const rows = await User.findBy({ username: req.body.username })
if (rows.length) {
req.userData = rows[0]
next()
} else {
res.status(401).json("Invalid Credentials")
}
} catch (e) {
res.status(500).json(`Server error: ${e.message}`)
}
}

/*
Expand All @@ -42,8 +80,20 @@ function checkUsernameExists() {
"message": "Password must be longer than 3 chars"
}
*/
function checkPasswordLength() {
function checkPasswordLength(req, res, next) {
if (!req.body.password || req.body.password.length <= 3) {
res.status(422).json({ message: 'Password must be longer than 3 chars' })
}
else {
next()
}
}

module.exports = {
restricted,
checkUsernameFree,
checkUsernameExists,
checkPasswordLength
}

// Don't forget to add these to the `exports` object so they can be required in other modules
53 changes: 52 additions & 1 deletion api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
// Require `checkUsernameFree`, `checkUsernameExists` and `checkPasswordLength`
// middleware functions from `auth-middleware.js`. You will need them here!

const router = require("express").Router();
const { checkUsernameFree, checkUsernameExists, checkPasswordLength } = require('./auth-middleware')
const User = require('../users/users-model.js')
const bcrypt = require("bcryptjs")

/**
1 [POST] /api/auth/register { "username": "sue", "password": "1234" }
Expand All @@ -25,6 +29,18 @@
}
*/

router.post('/register', checkUsernameFree, checkPasswordLength, (req, res) => {
console.log('register post route')
const hash = bcrypt.hashSync(req.body.password, 10)
User.add({ username: req.body.username, password: hash })
.then(response => {
res.status(201).json(response)
})
.catch(err => {
res.status(500).json({ message: err.message })
})
})


/**
2 [POST] /api/auth/login { "username": "sue", "password": "1234" }
Expand All @@ -42,6 +58,23 @@
}
*/

router.post('/login', checkUsernameExists, (req, res) => {
console.log('login post route')
try {
const verified = bcrypt.compareSync(req.body.password, req.userData.password)
if (verified) {
req.session.user = req.userData
res.status(200).json({ message: `Welcome ${req.userData.username}` })
// res.json(`Welcome back ${req.userData.username}`)
//res.json(`Welcome back ${req.session.user.username}`)
} else {
res.status(401).json({ message: "Invalid Credentials" })
}
} catch (e) {
res.status(500).json({ message: "Invalid Credentials" })
}
})


/**
3 [GET] /api/auth/logout
Expand All @@ -59,5 +92,23 @@
}
*/


router.get('/logout', (req, res) => {
console.log('auth log out route')
if (req.session) {
req.session.destroy(err => {
if (err) {
res.json(`Can't log out:${err.message}`)
} else {
res.status(200).json({ message: 'logged out' })
}
})
} else {
res.status(200).json({ message: "no session" })
}

})

module.exports = router;


// Don't forget to add the router to the `exports` object so it can be required in other modules
33 changes: 33 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");
const session = require("express-session")
const KnexSessionStore = require("connect-session-knex")(session)



const usersRouter = require('./users/users-router.js')
const authRouter = require('./auth/auth-router.js')

/**
Do what needs to be done to support sessions with the `express-session` package!
Expand All @@ -17,9 +24,35 @@ const cors = require("cors");

const server = express();

const config = {
name: "chocolatechip",
secret: "keep it secret, keep it safe",
cookie: {
maxAge: 1000 * 60 * 60,
secure: false,
httpOnly: true
},
resave: false,
saveUninitialized: false,
store: new KnexSessionStore({
knex: require("../data/db-config.js"),
tablename: "sessions",
sidfieldname: "sid",
createTable: true,
clearInterval: 1000 * 60 * 60
})
}



server.use(helmet());
server.use(express.json());
server.use(cors());
server.use(session(config));


server.use('/api/users', usersRouter)
server.use('/api/auth', authRouter)

server.get("/", (req, res) => {
res.json({ api: "up" });
Expand Down
20 changes: 15 additions & 5 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
const db = require('../../data/db-config')

/**
resolves to an ARRAY with all users, each user having { user_id, username }
*/
function find() {

return db('users').select('user_id', 'username').orderBy("user_id")
}

/**
resolves to an ARRAY with all users that match the filter condition
*/
function findBy(filter) {

return db("users").where(filter).orderBy("user_id");
}

/**
resolves to the user { user_id, username } with the given user_id
*/
function findById(user_id) {

return db('users').where('user_id', user_id).first()
}

/**
resolves to the newly inserted user { user_id, username }
*/
function add(user) {

async function add(user) {
const [id] = await db("users").insert(user);
return findById(id);
}

// Don't forget to add these to the `exports` object so they can be required in other modules

module.exports = {
find,
findBy,
findById,
add
}
15 changes: 15 additions & 0 deletions api/users/users-router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
// Require the `restricted` middleware from `auth-middleware.js`. You will need it here!
const router = require("express").Router();
const User = require('./users-model')
const { restricted } = require('../auth/auth-middleware')

router.get('/', restricted, (req, res) => {
console.log('getting all users')
User.find()
.then(users => {
res.status(200).json(users)
})
.catch(err => {
res.status(401).json({ message: 'You shall not pass!' })
})
})

/**
[GET] /api/users
Expand All @@ -24,5 +37,7 @@
}
*/

module.exports = router;


// Don't forget to add the router to the `exports` object so it can be required in other modules
Binary file modified data/auth.db3
Binary file not shown.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const server = require('./api/server.js');

const PORT = process.env.PORT || 5000;
const PORT = process.env.PORT || 4000;

server.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
Expand Down
Loading