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

Expand All @@ -6,7 +7,12 @@
"message": "You shall not pass!"
}
*/
function restricted() {
function restricted(req,res,next) {
if(req.session && req.session.user) {
next();
}else{
next({ status: 401, message: "You shall not pass!"})
}

}

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

async function checkUsernameFree(req,res,next) {
try {
const user = await Users.findBy(req.body.username)
if(user){
next({ status: 422, message: "Username taken"})
}else{
next();
}
} catch (err) {
next(err)
}
}

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

async function checkUsernameExists(req,res,next) {
try {
const user = await Users.findBy(req.body.username)
if(!user){
next({ status: 401, message: "Invalid credentials"})
}else{
next();
}
} catch (err) {
next(err)
}
}

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

function checkPasswordLength(req,res,next) {
let { password } = req.body
if(password === undefined || password === null || password.length <= 3){
next({ status: 422, 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 = {
checkUsernameFree,
checkPasswordLength,
checkUsernameExists,
restricted
}
58 changes: 55 additions & 3 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
const express = require('express')
const Users = require('../users/users-model')
const bcrypt = require('bcryptjs')
const { checkUsernameFree, checkPasswordLength, checkUsernameExists } = require('./auth-middleware')
const router = express.Router()
// Require `checkUsernameFree`, `checkUsernameExists` and `checkPasswordLength`
// middleware functions from `auth-middleware.js`. You will need them here!



router.post('/register', checkUsernameFree, checkPasswordLength, async (req, res, next) => {
const { username, password } = req.body
try {
const hashedPassword = await bcrypt.hash(password, 12)
const credentials = {
username: username,
password: hashedPassword
}
const result = await Users.add(credentials)
res.status(201).json(result)
} catch (error) {
next(error)
}


})
/**
1 [POST] /api/auth/register { "username": "sue", "password": "1234" }

Expand All @@ -25,7 +47,20 @@
}
*/


router.post('/login', checkUsernameExists, async (req, res, next) => {
try {
const { password } = await Users.findBy(req.body.username)
const validPassword = await bcrypt.compare(req.body.password, password)
if (validPassword) {
req.session.user = req.body.username
res.status(200).json({ message: `Welcome ${req.body.username}!` })
} else {
next({ status: 401, message: "Invalid credentials" })
}
} catch (err) {
next({ message: 'Login error, please try again' })
}
})
/**
2 [POST] /api/auth/login { "username": "sue", "password": "1234" }

Expand All @@ -42,7 +77,23 @@
}
*/


router.get('/logout', (req, res, next) => {
try {
if (req.session.user) {
req.session.destroy(err => {
if (err) {
res.send('error logging out')
} else {
res.status(200).json({ message: 'logged out' })
}
})
} else {
res.status(200).json({ message: 'no session' })
}
} catch (err) {
next(err)
}
})
/**
3 [GET] /api/auth/logout

Expand All @@ -59,5 +110,6 @@
}
*/


// Don't forget to add the router to the `exports` object so it can be required in other modules
module.exports = router
24 changes: 24 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
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')
const authRouter = require('./auth/auth-router')

/**
Do what needs to be done to support sessions with the `express-session` package!
Expand All @@ -20,6 +24,26 @@ const server = express();
server.use(helmet());
server.use(express.json());
server.use(cors());
server.use(session({
name: 'chocolatechip',
secret: 'Bloomtech',
cookie: {
maxAge: 1000 * 60 * 60,
secure: false
},
httpOnly: true,
resave: false,
saveUninitialized: false,
store: new KnexSessionStore({
knex: require('../data/db-config'),
tablename: "sessions",
sidfieldname: "session_id",
createtable: true,
clearInterval: 1000 * 1000 * 60
})
}))
server.use('/api/users', usersRouter)
server.use('/api/auth', authRouter)

server.get("/", (req, res) => {
res.json({ api: "up" });
Expand Down
35 changes: 29 additions & 6 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,52 @@
const db = require('../../data/db-config')
/**
resolves to an ARRAY with all users, each user having { user_id, username }
*/
function find() {
async function find() {
const users = await db('users')
.select('user_id', 'username')
return users

}

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

async function findBy(filter) {
const [users] = await db('users')
// .select('user_id', 'username')
.where('user_id', filter).orWhere('username', filter).orWhere('password',filter)
return users
}

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

async function findById(user_id) {
const users = await db('users')
.select('user_id', 'username')
.where('user_id', user_id)
return users
}

/**
resolves to the newly inserted user { user_id, username }
*/
function add(user) {
async function add(user) {
const newID = await db('users')
.insert(user)
const newUser = await db('users')
.select('user_id', 'username')
.where('user_id', newID)
.first()
return(newUser)

}

// Don't forget to add these to the `exports` object so they can be required in other modules
module.exports = {
find,
findBy,
findById,
add,
}
17 changes: 17 additions & 0 deletions api/users/users-router.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
const express = require('express')
const Users = require('./users-model')
const { restricted } = require('../auth/auth-middleware')
const router = express.Router();


router.get('/', restricted, async (req, res, next) => {
try {
const users = await Users.find()
res.status(200).json(users)
} catch (err) {
next(err)
}
})

// Require the `restricted` middleware from `auth-middleware.js`. You will need it here!


Expand Down Expand Up @@ -26,3 +41,5 @@


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

module.exports = router
Binary file modified data/auth.db3
Binary file not shown.
Loading