Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

'joey bertschler' #853

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
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
57 changes: 50 additions & 7 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const User = require('../users/users-model')

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

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

function restricted(req, res, next) {
if (req.session.user) {
next()
} else {
next({ message: "You shall not pass!" })
console.log('restricted function in auth-middleware.js')
}
}

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

async function checkUsernameFree(req, res, next) {
try {
const users = await User.findBy({ username: req.body.username })
if (!users.length) {
next()
}
else {
next ({ message: "Username taken", status: 422 })
}
} catch (error) {
//res.status(500).json({message: 'Something went wrong'})
next(error) //error handling middleware in server.js, if there was none
//it would use express's default error handling middleware and send back a 500/Internal Server Error
}
}

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

async function checkUsernameExists(req, res, next) {
try {
const users = await User.findBy({ username: req.body.username })
if (users.length) {
req.user = users[0]
next()
}
else {
next ({ message: "Invalid credentials", status: 401 })
}
} catch (error) {
//res.status(500).json({message: 'Something went wrong'})
next(error) //error handling middleware in server.js, if there was none
//it would use express's default error handling middleware and send back a 500/Internal Server Error
}
}

/*
Expand All @@ -42,8 +75,18 @@ 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 < 4) {
next ({ message: "Password must be longer than 3 chars", status: 422 })
} else {
next()
}
}

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

//start with the router

const router = require('express').Router()
const bycrypt = require('bcryptjs')
const User = require('../users/users-model')

const {
checkUsernameFree,
checkUsernameExists,
checkPasswordLength
} = require('./auth-middleware')

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

router.post('/register', checkUsernameFree, checkPasswordLength, (req, res, next) => {
//res.json('register')
const { username, password } = req.body
const hash = bycrypt.hashSync(password, 10) // this is 2^10 rounds of hashing

User.add({ username, password: hash })
.then(saved => {
res.status(201).json(saved)
})
.catch(error => {
next(error)
})
})


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

router.post('/login', checkUsernameExists, (req, res, next) => {
//res.json('login')
const { username, password } = req.body
if (bycrypt.compareSync(password, req.user.password) ) {
//make it so that the user is logged in
req.session.user = req.user
res.status(200).json({ message: `Welcome ${username}!` })
} else {
next({ status: 401, message: "Invalid credentials" })
}
})




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

router.get('/logout', (req, res, next) => {
//res.json('logout')
if (req.session.user) {
req.session.destroy(err=>{
if(err){
next(err)
} else {
res.status(200).json({ message: "logged out" })
}
})
} else {
res.status(200).json({ message: "no session" })
}
})


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

module.exports = router;

33 changes: 32 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 usersRouter = require("./users/users-router.js");
const authRouter = require("./auth/auth-router.js");
const session = require("express-session");
const Store = require("connect-session-knex")(session);
const knex = require('../data/db-config.js');

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

const server = express();

server.use(session ({
name: "chocolatechip",
secret: "shh",
saveUninitialized: false,
resave: false,
store: new Store({
knex,//: require("../db/knex.js"),
createTable: true,
clearInterval: 1000 * 60 * 60, //clear expired sessions every hour
tablename: "sessions",
sidfieldname: "sid",
}),
cookie: {
maxAge: 1000 * 60 * 10, //10 minutes
secure: false,
httpOnly: true, // this means the cookie is only accessible by the server / the browser (not the client)
sameSite: 'none', // this means the cookie is not accessible by javascript, only by https (not http)
//sameSite: "lax", // this means the cookie is accessible by the server and the client

}
}) )
server.use(helmet());
server.use(express.json());
server.use(cors());



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

server.get("/", (req, res) => {
res.json({ api: "up" });
});

server.use((err, req, res, next) => { // eslint-disable-line
res.status(err.status || 500).json({
res.status(err.status || 401).json({
message: err.message,
stack: err.stack,
});
Expand Down
21 changes: 16 additions & 5 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
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) // filter is an object
}

/**
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() //.where({ user_id })
.select('user_id', 'username')
}

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

async function add(user) {
const [id] = await db('users').insert(user) // , 'user_id')
return findById(id)
// return db('users').insert(user).returning('*')
}

// Don't forget to add these to the `exports` object so they can be required in other modules
module.exports = {
find,
findBy,
findById,
add
}
19 changes: 19 additions & 0 deletions api/users/users-router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// Require the `restricted` middleware from `auth-middleware.js`. You will need it here!

const router = require ('express').Router() // router is a function that returns an object
//const restricted = require('./auth-middleware.js') // will check if the user is logged in

const { restricted } = require('../auth/auth-middleware') // will check if the user is logged in
const User = require('../users/users-model.js') // will check if the user is logged in

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

router.get('/', restricted, async (req, res, next) => {
//res.send('Welcome to the users API!') // only one res per route
//res.json('users')
try { // try to find the user in the database
const users = await User.find()
res.json(users)
} catch (err) {
next(err)
} // if there is an error, call next with the error
})


// 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.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const server = require('./api/server.js');

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

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