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
39 changes: 31 additions & 8 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const User = require('../users/users-model')
/*
If the user does not have a session saved in the server

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

function restricted(req, res, next){
if(req.session.user){
next()
}else{
res.status(401).json('You shall not pass!')
}
}

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

async function checkUsernameFree(req, res, next){
try{
const rows = await User.findBy({username: req.body.username})
if(!rows.length){
next()
}else{
res.status(401).json('Username taken')
}
}catch(err){
res.status(500).json(`Server error: ${err.message}`)
}
}

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

function checkUsernameExists(req, res, next){
if(!req.body.username){
res.status(401).json('Invalid credentials')
}else{
next()
}
}

/*
Expand All @@ -42,8 +60,13 @@ function checkUsernameExists() {
"message": "Password must be longer than 3 chars"
}
*/
function checkPasswordLength() {

function checkPasswordLength(req, res, next){
if(!req.body.password || req.body.password <= 3){
res.status(422).json({message: 'Password must be longer than 3 chars'})
}else{
next()
}
}

// Don't forget to add these to the `exports` object so they can be required in other modules
module.exports = {restricted, checkUsernameExists, checkUsernameFree, checkPasswordLength}
46 changes: 42 additions & 4 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// Require `checkUsernameFree`, `checkUsernameExists` and `checkPasswordLength`
// middleware functions from `auth-middleware.js`. You will need them here!

const express = require('express')
const router = express.Router()
const User = require('../users/users-model')
const bcrypt = require('bcryptjs')
const mw = require('./auth-middleware')
const {restart} = require('nodemon')

/**
1 [POST] /api/auth/register { "username": "sue", "password": "1234" }
Expand All @@ -24,7 +29,15 @@
"message": "Password must be longer than 3 chars"
}
*/

router.post('/register', mw.checkPasswordLength, mw.checkUsernameFree, mw.checkUsernameExists, async (req, res) => {
try{
const hash = bcrypt.hashSync(req.body.password, 10)
const newUser = await User.add({username: req.body.username, password: hash})
res.status(201).json(newUser)
}catch(err){
res.status(500).json(`Server error: ${err.message}`)
}
})

/**
2 [POST] /api/auth/login { "username": "sue", "password": "1234" }
Expand All @@ -41,7 +54,19 @@
"message": "Invalid credentials"
}
*/

router.post('/login', mw.checkPasswordLength, mw.checkUsernameExists, (req, res) => {
try{
const verified = bcrypt.compareSync(req.body.password, req.userData.username)
if(verified){
req.session.user = req.userData
req.json(`Welcome back: ${req.userData.username}`)
}else{
res.status(401).json('Incorrect username or password')
}
}catch(err){
res.status(500).json(`Server error: ${err.message}`)
}
})

/**
3 [GET] /api/auth/logout
Expand All @@ -58,6 +83,19 @@
"message": "no session"
}
*/

router.get('/logout', (req, res) => {
if(req.session){
req.session.destroy(err => {
if(err){
res.json(`Can't logout: ${err.message}`)
}else{
res.json(`Logged out successfully`)
}
})
}else{
res.json('Session doesnt exist')
}
})

// Don't forget to add the router to the `exports` object so it can be required in other modules
module.exports = router
28 changes: 27 additions & 1 deletion api/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");
const userRouter = require('./users/users-router')
const authRouter = require('./auth/auth-router')
const session = require('express-session')
const knex = require('../data/db-config')
const Store = require('connect-session-knex')(session)

/**
Do what needs to be done to support sessions with the `express-session` package!
Expand All @@ -16,10 +21,31 @@ const cors = require("cors");
*/

const server = express();
const config = {
name: 'session',
secret: 'chocolatechip',
cookie:{
maxAge: 1000 * 60 *60,
secure: false,
httpOnly:true
},
resave: false,
saveUninitialized: false,
store: new Store({
knex,
tablename: 'users',
sidfieldname: 'uid',
createTable: true,
clearInterval: 1000 * 60 *60
})
}

server.use(helmet());
server.use(express.json());
server.use(cors());
server.use(session(config))
server.use('/api/users', userRouter)
server.use('/api/auth', authRouter)

server.get("/", (req, res) => {
res.json({ api: "up" });
Expand All @@ -32,4 +58,4 @@ server.use((err, req, res, next) => { // eslint-disable-line
});
});

module.exports = server;
module.exports = server;
13 changes: 8 additions & 5 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
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')
}

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

return db('users').where(filter)
}

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

return db('users').select('user_id', 'username').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}
12 changes: 10 additions & 2 deletions api/users/users-router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Require the `restricted` middleware from `auth-middleware.js`. You will need it here!

const router = require('express').Router()
const mw = require('../auth/auth-middleware')
const Users = require('./users-model')

/**
[GET] /api/users
Expand All @@ -23,6 +25,12 @@
"message": "You shall not pass!"
}
*/

router.get('/', mw.restricted, (req, res) => {
Users.find()
.then(users => {
res.status(200).json(users)
})
})

// Don't forget to add the router to the `exports` object so it can be required in other modules
module.exports = router
Loading