From 0464c8f97d2b464a4bd73a688002bdd900755ca0 Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 03:10:26 +0400 Subject: [PATCH 01/11] wip --- api/auth/auth-middleware.js | 23 ++++-- api/auth/auth-router.js | 19 +++++ api/server.js | 8 +- api/users/users-router.js | 12 +++ index.js | 3 +- package-lock.json | 157 ++++++++++++++++++++++++++++++++++++ package.json | 1 + 7 files changed, 213 insertions(+), 10 deletions(-) diff --git a/api/auth/auth-middleware.js b/api/auth/auth-middleware.js index ddd8bc4dd7..69f7a14cfa 100644 --- a/api/auth/auth-middleware.js +++ b/api/auth/auth-middleware.js @@ -6,8 +6,9 @@ "message": "You shall not pass!" } */ -function restricted() { - +function restricted(req, res, next) { + console.log('restricted function in auth-middleware.js') + next() } /* @@ -18,8 +19,8 @@ function restricted() { "message": "Username taken" } */ -function checkUsernameFree() { - +function checkUsernameFree(req, res, next) { + next() } /* @@ -30,8 +31,8 @@ function checkUsernameFree() { "message": "Invalid credentials" } */ -function checkUsernameExists() { - +function checkUsernameExists(req, res, next) { + next() } /* @@ -42,8 +43,14 @@ function checkUsernameExists() { "message": "Password must be longer than 3 chars" } */ -function checkPasswordLength() { - +function checkPasswordLength(req, res, next) { + 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 +} diff --git a/api/auth/auth-router.js b/api/auth/auth-router.js index ffd7a2e003..bbce911b3f 100644 --- a/api/auth/auth-router.js +++ b/api/auth/auth-router.js @@ -1,6 +1,10 @@ // 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() + /** 1 [POST] /api/auth/register { "username": "sue", "password": "1234" } @@ -25,6 +29,10 @@ } */ +router.post('/register', (req, res, next) => { + res.json('register') +}) + /** 2 [POST] /api/auth/login { "username": "sue", "password": "1234" } @@ -42,6 +50,10 @@ } */ + router.post('/login', (req, res, next) => { + res.json('login') + }) + /** 3 [GET] /api/auth/logout @@ -59,5 +71,12 @@ } */ + router.get('/logout', (req, res, next) => { + res.json('logout') + }) + // Don't forget to add the router to the `exports` object so it can be required in other modules + +module.exports = router; + \ No newline at end of file diff --git a/api/server.js b/api/server.js index bdc628cef2..e3371962fb 100644 --- a/api/server.js +++ b/api/server.js @@ -1,7 +1,8 @@ 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"); /** Do what needs to be done to support sessions with the `express-session` package! To respect users' privacy, do NOT send them a cookie unless they log in. @@ -21,6 +22,11 @@ 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" }); }); diff --git a/api/users/users-router.js b/api/users/users-router.js index 84aaf5b4be..22b140787f 100644 --- a/api/users/users-router.js +++ b/api/users/users-router.js @@ -1,5 +1,9 @@ // 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 /** [GET] /api/users @@ -24,5 +28,13 @@ } */ + router.get('/', restricted, (req, res, next) => { + //res.send('Welcome to the users API!') // only one res per route + res.json('users') + }) + // Don't forget to add the router to the `exports` object so it can be required in other modules + + +module.exports = router; \ No newline at end of file diff --git a/index.js b/index.js index 71f14885b1..5320cdafde 100644 --- a/index.js +++ b/index.js @@ -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`) }); diff --git a/package-lock.json b/package-lock.json index 88b90ba28e..285f7fcaa5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "bcryptjs": "^2.4.3", "cors": "^2.8.5", "express": "^4.17.1", + "express-session": "^1.17.2", "helmet": "^4.6.0", "knex": "^0.95.14", "sqlite3": "^5.0.2" @@ -2854,6 +2855,72 @@ "node": ">= 0.10.0" } }, + "node_modules/express-session": { + "version": "1.17.2", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.17.2.tgz", + "integrity": "sha512-mPcYcLA0lvh7D4Oqr5aNJFMtBMKPLl++OKKxkHzZ0U0oDq1rpKBnkR5f5vCHR26VeArlTOEF9td4x5IjICksRQ==", + "dependencies": { + "cookie": "0.4.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.0.2", + "parseurl": "~1.3.3", + "safe-buffer": "5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/express-session/node_modules/cookie": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.1.tgz", + "integrity": "sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express-session/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express-session/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/express-session/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/express-session/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -5384,6 +5451,14 @@ "node": ">= 0.8" } }, + "node_modules/on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -5765,6 +5840,14 @@ "node": ">=0.6" } }, + "node_modules/random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha1-T2ih3Arli9P7lYSMMDJNt11kNgs=", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -6770,6 +6853,17 @@ "is-typedarray": "^1.0.0" } }, + "node_modules/uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/undefsafe": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", @@ -9472,6 +9566,51 @@ } } }, + "express-session": { + "version": "1.17.2", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.17.2.tgz", + "integrity": "sha512-mPcYcLA0lvh7D4Oqr5aNJFMtBMKPLl++OKKxkHzZ0U0oDq1rpKBnkR5f5vCHR26VeArlTOEF9td4x5IjICksRQ==", + "requires": { + "cookie": "0.4.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.0.2", + "parseurl": "~1.3.3", + "safe-buffer": "5.2.1", + "uid-safe": "~2.1.5" + }, + "dependencies": { + "cookie": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.1.tgz", + "integrity": "sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA==" + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + } + } + }, "extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -11412,6 +11551,11 @@ "ee-first": "1.1.1" } }, + "on-headers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", + "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==" + }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -11701,6 +11845,11 @@ "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" }, + "random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha1-T2ih3Arli9P7lYSMMDJNt11kNgs=" + }, "range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -12480,6 +12629,14 @@ "is-typedarray": "^1.0.0" } }, + "uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "requires": { + "random-bytes": "~1.0.0" + } + }, "undefsafe": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", diff --git a/package.json b/package.json index 4b1b5792f5..e12c372a8b 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "bcryptjs": "^2.4.3", "cors": "^2.8.5", "express": "^4.17.1", + "express-session": "^1.17.2", "helmet": "^4.6.0", "knex": "^0.95.14", "sqlite3": "^5.0.2" From 96125db76b141668b8bfadcf642e491233d1589e Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 03:16:32 +0400 Subject: [PATCH 02/11] wip2 --- api/users/users-model.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/api/users/users-model.js b/api/users/users-model.js index 0eb347ce52..efc3ae9c66 100644 --- a/api/users/users-model.js +++ b/api/users/users-model.js @@ -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') } /** 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 }) } /** 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 +} From 7839e288fa1cedffae6ee9c6abbeb805eba2a89d Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 03:26:00 +0400 Subject: [PATCH 03/11] wip3 --- api/users/users-model.js | 3 ++- api/users/users-router.js | 11 +++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/api/users/users-model.js b/api/users/users-model.js index efc3ae9c66..1d1b08be5f 100644 --- a/api/users/users-model.js +++ b/api/users/users-model.js @@ -4,7 +4,7 @@ const db = require('../../data/db-config') resolves to an ARRAY with all users, each user having { user_id, username } */ function find() { - return db('users') + return db('users').select('user_id', 'username') } /** @@ -19,6 +19,7 @@ function findBy(filter) { */ function findById(user_id) { return db('users').where('user_id', user_id).first() //.where({ user_id }) + .select('user_id', 'username') } /** diff --git a/api/users/users-router.js b/api/users/users-router.js index 22b140787f..6028cab885 100644 --- a/api/users/users-router.js +++ b/api/users/users-router.js @@ -4,6 +4,7 @@ const router = require ('express').Router() // router is a function that returns //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 @@ -28,9 +29,15 @@ const { restricted } = require('../auth/auth-middleware') // will check if the u } */ - router.get('/', restricted, (req, res, next) => { + router.get('/', restricted, async (req, res, next) => { //res.send('Welcome to the users API!') // only one res per route - res.json('users') + //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 }) From cf517e74914d4a42e9c448756536b761387643c8 Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 09:42:03 +0400 Subject: [PATCH 04/11] wip4 --- api/auth/auth-middleware.js | 3 ++- api/auth/auth-router.js | 11 +++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/api/auth/auth-middleware.js b/api/auth/auth-middleware.js index 69f7a14cfa..d782fe3b06 100644 --- a/api/auth/auth-middleware.js +++ b/api/auth/auth-middleware.js @@ -6,10 +6,11 @@ "message": "You shall not pass!" } */ + function restricted(req, res, next) { console.log('restricted function in auth-middleware.js') next() -} + } /* If the username in req.body already exists in the database diff --git a/api/auth/auth-router.js b/api/auth/auth-router.js index bbce911b3f..ce20151693 100644 --- a/api/auth/auth-router.js +++ b/api/auth/auth-router.js @@ -5,6 +5,13 @@ const router = require('express').Router() +const { + checkUsernameFree, + checkUsernameExists, + checkPasswordLength +} = require('./auth-middleware') + + /** 1 [POST] /api/auth/register { "username": "sue", "password": "1234" } @@ -29,7 +36,7 @@ const router = require('express').Router() } */ -router.post('/register', (req, res, next) => { +router.post('/register', checkUsernameFree, checkPasswordLength, (req, res) => { res.json('register') }) @@ -50,7 +57,7 @@ router.post('/register', (req, res, next) => { } */ - router.post('/login', (req, res, next) => { + router.post('/login', checkUsernameExists, (req, res) => { res.json('login') }) From 4a46dd3f90519d923b63f386e0a72c4c1ab2e821 Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 10:06:26 +0400 Subject: [PATCH 05/11] wip5 --- api/auth/auth-middleware.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/api/auth/auth-middleware.js b/api/auth/auth-middleware.js index d782fe3b06..bb82eb1a3c 100644 --- a/api/auth/auth-middleware.js +++ b/api/auth/auth-middleware.js @@ -1,3 +1,5 @@ +const User = require('../users/users-model') + /* If the user does not have a session saved in the server @@ -20,8 +22,20 @@ function restricted(req, res, next) { "message": "Username taken" } */ -function checkUsernameFree(req, res, next) { - next() +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" }) + } + } 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 + } } /* From 2d3abd64faa98b6ef3b2d31e071afc788566972c Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 10:14:29 +0400 Subject: [PATCH 06/11] wip6 --- api/auth/auth-middleware.js | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/api/auth/auth-middleware.js b/api/auth/auth-middleware.js index bb82eb1a3c..31a3a8461a 100644 --- a/api/auth/auth-middleware.js +++ b/api/auth/auth-middleware.js @@ -29,7 +29,7 @@ async function checkUsernameFree(req, res, next) { next() } else { - next ({ "message": "Username taken" }) + next ({ message: "Username taken", status: 422 }) } } catch (error) { //res.status(500).json({message: 'Something went wrong'}) @@ -46,8 +46,20 @@ async function checkUsernameFree(req, res, next) { "message": "Invalid credentials" } */ -function checkUsernameExists(req, res, next) { - next() +async function checkUsernameExists(req, res, next) { + try { + const users = await User.findBy({ username: req.body.username }) + if (users.length) { + 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 + } } /* From e8d0709459027fd5f7701bb54c813f78734a7cce Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 10:18:31 +0400 Subject: [PATCH 07/11] wip7 --- api/auth/auth-middleware.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/api/auth/auth-middleware.js b/api/auth/auth-middleware.js index 31a3a8461a..4dd2371163 100644 --- a/api/auth/auth-middleware.js +++ b/api/auth/auth-middleware.js @@ -71,7 +71,11 @@ async function checkUsernameExists(req, res, next) { } */ 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 From f30e5e7556b4e5cf351360b5d0c41ad60e112205 Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 10:47:57 +0400 Subject: [PATCH 08/11] wip8 --- api/server.js | 25 +++++++++++++++++++++++++ package-lock.json | 34 ++++++++++++++++++++++++++++++++++ package.json | 1 + 3 files changed, 60 insertions(+) diff --git a/api/server.js b/api/server.js index e3371962fb..026c94604f 100644 --- a/api/server.js +++ b/api/server.js @@ -3,6 +3,10 @@ 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/dbConfig.js'); + /** Do what needs to be done to support sessions with the `express-session` package! To respect users' privacy, do NOT send them a cookie unless they log in. @@ -18,6 +22,27 @@ const authRouter = require("./auth/auth-router.js"); 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()); diff --git a/package-lock.json b/package-lock.json index 285f7fcaa5..cab21120d1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "1.0.0", "dependencies": { "bcryptjs": "^2.4.3", + "connect-session-knex": "^2.1.1", "cors": "^2.8.5", "express": "^4.17.1", "express-session": "^1.17.2", @@ -2053,6 +2054,23 @@ "node": ">=8" } }, + "node_modules/connect-session-knex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/connect-session-knex/-/connect-session-knex-2.1.1.tgz", + "integrity": "sha512-gIOqwoU4mWe9uwkWsnBI9KsBr2sYp0IyXX6NJG7oGW6wJjy5CpWufB3FoJPEYb2OqNPMmshr07vS12pcMfok2g==", + "dependencies": { + "bluebird": "^3.7.2", + "knex": "^0.95.6" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/connect-session-knex/node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + }, "node_modules/console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", @@ -8943,6 +8961,22 @@ "xdg-basedir": "^4.0.0" } }, + "connect-session-knex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/connect-session-knex/-/connect-session-knex-2.1.1.tgz", + "integrity": "sha512-gIOqwoU4mWe9uwkWsnBI9KsBr2sYp0IyXX6NJG7oGW6wJjy5CpWufB3FoJPEYb2OqNPMmshr07vS12pcMfok2g==", + "requires": { + "bluebird": "^3.7.2", + "knex": "^0.95.6" + }, + "dependencies": { + "bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + } + } + }, "console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", diff --git a/package.json b/package.json index e12c372a8b..5e53f4d7bc 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ }, "dependencies": { "bcryptjs": "^2.4.3", + "connect-session-knex": "^2.1.1", "cors": "^2.8.5", "express": "^4.17.1", "express-session": "^1.17.2", From 021137ea50d438769b84ca19db8c0642ecccee07 Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 11:10:17 +0400 Subject: [PATCH 09/11] wip9 --- api/auth/auth-router.js | 19 +++++++++++++++---- api/server.js | 2 +- data/auth.db3 | Bin 24576 -> 36864 bytes 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/api/auth/auth-router.js b/api/auth/auth-router.js index ce20151693..7beb2cb907 100644 --- a/api/auth/auth-router.js +++ b/api/auth/auth-router.js @@ -4,6 +4,8 @@ //start with the router const router = require('express').Router() +const bycrypt = require('bcryptjs') +const User = require('../users/users-model') const { checkUsernameFree, @@ -11,8 +13,6 @@ const { checkPasswordLength } = require('./auth-middleware') - - /** 1 [POST] /api/auth/register { "username": "sue", "password": "1234" } @@ -36,8 +36,18 @@ const { } */ -router.post('/register', checkUsernameFree, checkPasswordLength, (req, res) => { - res.json('register') +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) + }) }) @@ -59,6 +69,7 @@ router.post('/register', checkUsernameFree, checkPasswordLength, (req, res) => { router.post('/login', checkUsernameExists, (req, res) => { res.json('login') + }) diff --git a/api/server.js b/api/server.js index 026c94604f..855c42d4c3 100644 --- a/api/server.js +++ b/api/server.js @@ -5,7 +5,7 @@ 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/dbConfig.js'); +const knex = require('../data/db-config.js'); /** Do what needs to be done to support sessions with the `express-session` package! diff --git a/data/auth.db3 b/data/auth.db3 index c675b8976de7278e7ec8e9ba2c7add79645518ec..b7b188f8f92fe618b778d20a79508d0487b93966 100644 GIT binary patch delta 577 zcmZoTz}T>WX@az%FarYvClJE`=R_T2Sz!h}?+LuTx(poLe;D{3`QGz+@h;>w<;mdr z!~JJtV*_`676-eyr7UA3cV=EnYDIBsadBpTUU7VCML}j!YDzqcD5rCft7C|(f~TL0 zYlK1qcEt$_`FRMr1O<%*s96b`je>0K;<7-?N=p)xa#BJ1>p`}`3}T0xAL8ibVDUM81KkRR(z#{t+hn*_j1~ zK0$ddmWjb3iC#`lY0eq`?vr=Ay!^f27X7r_k3Qw3wcd93kvM# z*=)*tQHbpu1OGSv%bNuaj`L5xtgpl!&%wwn&RJTVT2#ErfJK0fk$)Eh|1O}04g8aL b`Fn9N^8aK2BG%1<32*t?*_eenlk$@Qj4vRL From b920eba6fdfaeeecfaf2fef0b997169bf688f5ac Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 11:24:59 +0400 Subject: [PATCH 10/11] wip9 --- api/auth/auth-middleware.js | 1 + api/auth/auth-router.js | 15 ++++++++++++--- data/auth.db3 | Bin 36864 -> 36864 bytes 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/api/auth/auth-middleware.js b/api/auth/auth-middleware.js index 4dd2371163..a867fc0a72 100644 --- a/api/auth/auth-middleware.js +++ b/api/auth/auth-middleware.js @@ -50,6 +50,7 @@ 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 { diff --git a/api/auth/auth-router.js b/api/auth/auth-router.js index 7beb2cb907..f50e98cf66 100644 --- a/api/auth/auth-router.js +++ b/api/auth/auth-router.js @@ -67,12 +67,21 @@ router.post('/register', checkUsernameFree, checkPasswordLength, (req, res, next } */ - router.post('/login', checkUsernameExists, (req, res) => { - res.json('login') - + 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 diff --git a/data/auth.db3 b/data/auth.db3 index b7b188f8f92fe618b778d20a79508d0487b93966..ba565ca624af47d6683feec74e0612023016129f 100644 GIT binary patch delta 384 zcmZozz|^pSX@WGP$V3@uMv;vPOXArW`A#wLo!TrYaDcDA$(WJVx4F{RJ(LBrKvhf1&JjYKoj&qN)vNagELEjik0&6^HP;+b(BhrQ;R@O z0MYT8DN0sG5V1UvHmXXswYXfw#lXP8$bW}{|ITJX hgG>B+%FMo;gu()%=LrM<6QG`3{4&zaww$=k2LP%&Z)E@g delta 60 scmZozz|^pSX@WGP@I)DBM&XSKOX8Ur1U3sAyyBlYL4b{m0SIt$0r-m#$N&HU From 03ede89194e36c57636804f4ed5f00fed9136c7b Mon Sep 17 00:00:00 2001 From: joey-bertschler Date: Thu, 13 Jan 2022 11:38:28 +0400 Subject: [PATCH 11/11] wip10 --- api/auth/auth-middleware.js | 8 ++++++-- api/auth/auth-router.js | 13 ++++++++++++- api/server.js | 2 +- data/auth.db3 | Bin 36864 -> 36864 bytes 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/api/auth/auth-middleware.js b/api/auth/auth-middleware.js index a867fc0a72..5f511020de 100644 --- a/api/auth/auth-middleware.js +++ b/api/auth/auth-middleware.js @@ -10,9 +10,13 @@ const User = require('../users/users-model') */ function restricted(req, res, next) { - console.log('restricted function in auth-middleware.js') - next() + if (req.session.user) { + next() + } else { + next({ message: "You shall not pass!" }) + console.log('restricted function in auth-middleware.js') } +} /* If the username in req.body already exists in the database diff --git a/api/auth/auth-router.js b/api/auth/auth-router.js index f50e98cf66..f233826206 100644 --- a/api/auth/auth-router.js +++ b/api/auth/auth-router.js @@ -99,7 +99,18 @@ router.post('/register', checkUsernameFree, checkPasswordLength, (req, res, next */ router.get('/logout', (req, res, next) => { - res.json('logout') + //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" }) + } }) diff --git a/api/server.js b/api/server.js index 855c42d4c3..233722439a 100644 --- a/api/server.js +++ b/api/server.js @@ -57,7 +57,7 @@ server.get("/", (req, res) => { }); 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, }); diff --git a/data/auth.db3 b/data/auth.db3 index ba565ca624af47d6683feec74e0612023016129f..e91d4a0b0d66df0b303b737df432ce83b1132826 100644 GIT binary patch delta 483 zcmZozz|^pSX@WGP_(U0JM)8da^Ys~-HyN-9a53}iGVt%>FXq?XEGQt)@8-hH${^gx znwFohVw9+2XrPj*@8{#~7nGCY>+a|i9A4m=>{{wxsvlZp9OCH};^byzY!c~cmgVf> z7EoSV5}B6~;gyv-x!8Xq(C8No{6G0$@PF7WXmE>Pg`HWL5oj(m2eT++R$^W%6C1NI zXHtF=FW)H!M&79myi<9n0v*xGtI=e{#Om8zZktmTm}Oj;W}0sp;qK{e8WrrHq3h`! z>FMj?RbgD76*Bo#o-K!^m4StxvANM?^ZcNCV;!Z^;?$zN#N1RRD^1r46?OK~uZGG-;_r82QG3v(vrC-E{cFfj6+V&FRk)Nz21rOB9)b@RDAV@6Jp r1pgfd{yRX8m-tzfnSD7YKd4uPh(BTAe*zT0#m^$mY|A-WAzuOjK@=to