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

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

function restricted(req,res,next) {
next()
}

/*
Expand All @@ -18,8 +20,18 @@ 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{
res.status(422).json({ "message": "Username taken"})
next()
}
}catch(err){
next(err)
}
}

/*
Expand All @@ -30,8 +42,17 @@ 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){
next()
}else{
next({ message: "Invalid credentials", status: 401 })
}
}catch(err){
next(err)
}
}

/*
Expand All @@ -42,8 +63,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){
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
// Don't forget to add these to the `exports` object so they can be required in other modules

module.exports = {
restricted,
checkUsernameFree,
checkUsernameExists,
checkPasswordLength,
}
19 changes: 16 additions & 3 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
// 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')
/**
1 [POST] /api/auth/register { "username": "sue", "password": "1234" }

Expand All @@ -24,7 +30,9 @@
"message": "Password must be longer than 3 chars"
}
*/

router.post('/register', checkPasswordLength, checkUsernameFree, (req,res,next) =>{
res.json('register')
})

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

router.post('/login', checkUsernameExists,(req,res,next) =>{
res.json('login')
})

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

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;
34 changes: 32 additions & 2 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");

//requiring usersRouter
const usersRouter = require('./users/users-router');
//requiring authRouter
const authRouter = require('./auth/auth-router')
//requiring session & Knex session store
const session = require('express-session');
const { Store } = require("express-session");
const KnexSessionStore = require('connect-session-knex')(session)
const knex = require('../data/db-config')
/**
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.
Expand All @@ -14,17 +22,39 @@ const cors = require("cors");
The session can be persisted in memory (would not be adecuate for production)
or you can use a session store like `connect-session-knex`.
*/

const server = express();
server.use(session({
name: 'chocolatechip',
secret: 'shh',
saveUninitialized: false,
resave: false,
store: new KnexSessionStore({
knex,
tablename:'sessions',
sidfieldname:'sid',
createTable:true,
clearInterval: 1000 * 60 * 60
}),
cookie: {
maxAge: 1000 * 60 * 60,
secure:false,
httpOnly:true
}
}));

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

server.use(cors());
//using usersRouter & authRouter
server.use('/api/users', usersRouter);
server.use('/api/auth', authRouter)

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

//err handling middleware
server.use((err, req, res, next) => { // eslint-disable-line
res.status(err.status || 500).json({
message: err.message,
Expand Down
23 changes: 17 additions & 6 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').orderBy('user_id');
}

/**
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) {

function findById(id) {
return db('users')
.select('user_id', 'username')
.where({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,
}
13 changes: 12 additions & 1 deletion api/users/users-router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const router = require('express').Router();
const User = require('./users-model')
// Require the `restricted` middleware from `auth-middleware.js`. You will need it here!

const { restricted } = require('../auth/auth-middleware')

/**
[GET] /api/users
Expand All @@ -23,6 +25,15 @@
"message": "You shall not pass!"
}
*/
router.get('/', restricted, async(req,res,next)=>{
try{
const users = await User.find()
res.json(users)
} catch (error){
next(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 added connect-session-knex.sqlite
Binary file not shown.
Binary file modified data/auth.db3
Binary file not shown.
Loading