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
65 changes: 57 additions & 8 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const model = require('../users/users-model');

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

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

const restricted = (req, res, next) => {
if(req.session && req.session.user) {
next();
} else {
res.status(401).json('Please log in to view this content');
}
}

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

const checkUsernameFree = async (req, res, next) => {
try {
const user = await model.findBy({username: req.body.username});
console.log(user.username);
console.log(req.body.username);
if(user.username === req.body.username) {
res.status(422).json({
message: 'Username taken'
});
} else {
next();
}
} catch(err) {
res.status(500).json(`Server error: ${err}`);
}
}

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

const checkUsernameExists = async (req, res, next) => {
try {
const user = await model.findBy({username: req.body.username});
console.log(user.username);
if(!user.username) {
res.status(401).json({
message: 'Invalid credentials'
})
} else {
req.userData = user;
next();
}
} catch(err) {
res.status(500).json(`Server error: ${err}`);
}
}

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

const checkPasswordLength = (req, res, next) => {
try {
if(!req.body.password || req.body.password.length <= 3) {
res.status(422).json({
message: 'Password must be longer than 3 chars'
});
} else {
next();
}
} catch(err) {
res.status(500).json(`Server error: ${err}`);
}
}

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

module.exports = {
restricted,
checkUsernameFree,
checkUsernameExists,
checkPasswordLength
}
56 changes: 55 additions & 1 deletion api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
const express = require('express');
const model = require('../users/users-model');
const middleware = require('./auth-middleware');
const bcrypt = require('bcryptjs');
const router = express.Router();


// Require `checkUsernameFree`, `checkUsernameExists` and `checkPasswordLength`
// middleware functions from `auth-middleware.js`. You will need them here!


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

Expand Down Expand Up @@ -61,3 +67,51 @@


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

router.get('/logout', (req, res, next) => {
if(req.session) {
req.session.destroy(err => {
if(err) {
res.json(`Can't logout: ${err.message}`);
} else {
res.json('You were logged out');
}
})
} else {
res.json(`Session wasn't set`);
}
});

router.post('/login', middleware.checkUsernameExists, (req, res, next) => {
let {username, password} = req.body;

model.findBy({username})
.then(user => {
if(user && bcrypt.compareSync(password, user.password)) {
req.session.user = req.userData;
res.status(200).json({message: `Welcome ${user.username}`});

} else {
res.status(401).json({message: 'Invalid credentials'});
}
})
.catch(error => {
res.status(500).json(error);
});
});

router.post('/register', middleware.checkUsernameFree, middleware.checkPasswordLength, (req, res, next) => {
const credentials = req.body;
const hash = bcrypt.hashSync(credentials.password, 14);
credentials.password = hash;
model.add(credentials)
.then(success => {
res.status(200).json(success);
})
.catch(error => {
res.status(500).json(`Server error ${error}`);
})
});


module.exports = router;
24 changes: 22 additions & 2 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 helmet = require("helmet");
const cors = require("cors");
const session = require('express-session');

const authRouter = require('./auth/auth-router');
const userRouter = require('./users/users-router');

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

const server = express();

const sessionConfig = {
name : 'loginsession',
secret: 'verysecret',
cookie: {
name: 'chocolatechip',
maxAge: 1000 * 30,
secure: false,
httpOnly: true
},
resave: false,
saveUninitialized: false
}

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

server.get("/", (req, res) => {
res.json({ api: "up" });
Expand Down
26 changes: 18 additions & 8 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -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() {

async function find() {
return await db('users');
}

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

async function findBy(filter) {
return await db('users').where(filter).orderBy('user_id').first();
}

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

async function findById(user_id) {
return await db('users').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, 'user_id');
return findBy({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
}
18 changes: 17 additions & 1 deletion api/users/users-router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// Require the `restricted` middleware from `auth-middleware.js`. You will need it here!

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

/**
[GET] /api/users
Expand All @@ -26,3 +29,16 @@


// Don't forget to add the router to the `exports` object so it can be required in other modules
router.get('/', middleware.restricted, async (req, res) => {
console.log('Here are all the users');
try {
const users = await model.find();
res.status(200).send(users);
} catch(err) {
res.status(500).json({
message: 'Error retrieving users'
});
}
});

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