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

Completed take-home #4

Open
wants to merge 1 commit into
base: master
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
File renamed without changes.
53 changes: 53 additions & 0 deletions expressError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/** ExpressError extends normal JS error so we can
* add a status when we make an instance of it.
*
* The error-handling middleware will return this.
*/

class ExpressError extends Error {
constructor(message, status) {
super();
this.message = message;
this.status = status;
}
}

/** 404 NOT FOUND error. */

class NotFoundError extends ExpressError {
constructor(message = "Not Found") {
super(message, 404);
}
}

/** 401 UNAUTHORIZED error. */

class UnauthorizedError extends ExpressError {
constructor(message = "Unauthorized") {
super(message, 401);
}
}

/** 400 BAD REQUEST error. */

class BadRequestError extends ExpressError {
constructor(message = "Bad Request") {
super(message, 400);
}
}

/** 403 BAD REQUEST error. */

class ForbiddenError extends ExpressError {
constructor(message = "Bad Request") {
super(message, 403);
}
}

module.exports = {
ExpressError,
NotFoundError,
UnauthorizedError,
BadRequestError,
ForbiddenError,
};
85 changes: 85 additions & 0 deletions helpers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"use strict";

/** Convenience middleware to handle common auth cases in routes. */
const {UnauthorizedError} = require('../expressError');
const jwt = require("jsonwebtoken");
const SECRET_KEY = "adslfkjsadlfkjaglkj";


/** Middleware: Authenticate user.
*
* If a token was provided, verify it, and, if valid, store the token payload
* on res.locals (this will include the username and isAdmin field.)
*
* It's not an error if no token was provided or if the token is not valid.
*/

function authenticateJWT(req, res, next) {
try {
const authHeader = req.headers && req.headers.authorization;
if (authHeader) {
const token = authHeader.replace(/^[Bb]earer /, "").trim();
res.locals.user = jwt.verify(token, SECRET_KEY);
}
return next();
} catch (err) {
return next();
}
}

/** Middleware to use when they must be logged in.
*
* If not, raises error.
*/

function ensureLoggedIn(req, res, next) {
try {
if (!res.locals.user) throw new UnauthorizedError();
return next();
} catch (err) {
return next(err);
}
}


/** Middleware to use when they be logged in as an admin user.
*
* If not, raises error.
*/

function ensureAdmin(req, res, next) {
try {
if (!res.locals.user || !res.locals.user.isAdmin) {
throw new UnauthorizedError();
}
return next();
} catch (err) {
return next(err);
}
}

/** Middleware to use when they must provide a valid token & be user matching
* username provided as route param.
*
* If not, raises error.
*/

function ensureCorrectUserOrAdmin(req, res, next) {
try {
const user = res.locals.user;
if (!(user && (user.isAdmin || user.username === req.params.username))) {
throw new UnauthorizedError();
}
return next();
} catch (err) {
return next(err);
}
}


module.exports = {
authenticateJWT,
ensureLoggedIn,
ensureAdmin,
ensureCorrectUserOrAdmin,
};
140 changes: 140 additions & 0 deletions helpers/auth.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"use strict";

const jwt = require("jsonwebtoken");
const { UnauthorizedError } = require("../expressError");
const {
authenticateJWT,
ensureLoggedIn,
ensureAdmin,
ensureCorrectUserOrAdmin,
} = require("./auth");


const SECRET_KEY = "adslfkjsadlfkjaglkj";
const testJwt = jwt.sign({ id: "test", isAdmin: false }, SECRET_KEY);
const badJwt = jwt.sign({ id: "test", isAdmin: false }, "wrong");


describe("authenticateJWT", function () {
test("works: via header", function () {
expect.assertions(2);
//there are multiple ways to pass an authorization token, this is how you pass it in the header.
//this has been provided to show you another way to pass the token. you are only expected to read this code for this project.
const req = { headers: { authorization: `Bearer ${testJwt}` } };
const res = { locals: {} };
const next = function (err) {
expect(err).toBeFalsy();
};
authenticateJWT(req, res, next);
expect(res.locals).toEqual({
user: {
iat: expect.any(Number),
id: "test",
isAdmin: false,
},
});
});

test("works: no header", function () {
expect.assertions(2);
const req = {};
const res = { locals: {} };
const next = function (err) {
expect(err).toBeFalsy();
};
authenticateJWT(req, res, next);
expect(res.locals).toEqual({});
});

test("works: invalid token", function () {
expect.assertions(2);
const req = { headers: { authorization: `Bearer ${badJwt}` } };
const res = { locals: {} };
const next = function (err) {
expect(err).toBeFalsy();
};
authenticateJWT(req, res, next);
expect(res.locals).toEqual({});
});
});


describe("ensureLoggedIn", function () {
test("works", function () {
expect.assertions(1);
const req = {};
const res = { locals: { user: { id: "test", is_admin: false } } };
const next = function (err) {
expect(err).toBeFalsy();
};
ensureLoggedIn(req, res, next);
});

test("unauth if no login", function () {
expect.assertions(1);
const req = {};
const res = { locals: {} };
const next = function (err) {
expect(err instanceof UnauthorizedError).toBeTruthy();
};
ensureLoggedIn(req, res, next);
});
});


describe("ensureAdmin", function () {
test("works", function () {
expect.assertions(1);
const req = {};
const res = { locals: { user: { id: "test", isAdmin: true } } };
const next = function (err) {
expect(err).toBeFalsy();
};
ensureAdmin(req, res, next);
});

test("unauth if not admin", function () {
expect.assertions(1);
const req = {};
const res = { locals: { user: { id: "test", isAdmin: false } } };
const next = function (err) {
expect(err instanceof UnauthorizedError).toBeTruthy();
};
ensureAdmin(req, res, next);
});

test("unauth if anon", function () {
expect.assertions(1);
const req = {};
const res = { locals: {} };
const next = function (err) {
expect(err instanceof UnauthorizedError).toBeTruthy();
};
ensureAdmin(req, res, next);
});
});


describe("ensureCorrectUserOrAdmin", function () {
test("works: admin", function () {
expect.assertions(1);
const req = { params: { id: "test" } };
const res = { locals: { user: { id: "admin", isAdmin: true } } };
const next = function (err) {
expect(err).toBeFalsy();
};
ensureCorrectUserOrAdmin(req, res, next);
});

test("works: same user", function () {
expect.assertions(1);
const req = { params: { username: "test" } };
const res = { locals: { user: { username: "test", isAdmin: false } } };
const next = function (err) {
expect(err).toBeFalsy();
};
ensureCorrectUserOrAdmin(req, res, next);
});


});
18 changes: 18 additions & 0 deletions helpers/tokens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const jwt = require("jsonwebtoken");
const SECRET_KEY = "adslfkjsadlfkjaglkj"

/** return signed JWT from user data. */

function createToken(user) {
console.assert(user.isAdmin !== undefined,
"createToken passed user without isAdmin property");

let payload = {
id: user.id,
isAdmin: user.isAdmin || false,
};

return jwt.sign(payload, SECRET_KEY);
}

module.exports = { createToken };
36 changes: 36 additions & 0 deletions helpers/tokens.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const jwt = require("jsonwebtoken");
const { createToken } = require("./tokens");
const SECRET_KEY = "adslfkjsadlfkjaglkj";

describe("createToken", function () {
test("works: not admin", function () {
const token = createToken({ id: "test", is_admin: false });
const payload = jwt.verify(token, SECRET_KEY);
expect(payload).toEqual({
iat: expect.any(Number),
id: "test",
isAdmin: false,
});
});

test("works: admin", function () {
const token = createToken({ id: "test", isAdmin: true });
const payload = jwt.verify(token, SECRET_KEY);
expect(payload).toEqual({
iat: expect.any(Number),
id: "test",
isAdmin: true,
});
});

test("works: default no admin", function () {
// given the security risk if this didn't work, checking this specifically
const token = createToken({ id: "test" });
const payload = jwt.verify(token, SECRET_KEY);
expect(payload).toEqual({
iat: expect.any(Number),
id: "test",
isAdmin: false,
});
});
});
File renamed without changes.
9 changes: 6 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
var debug = require('debug')('frontend-code-challenge');
// var debug = require('debug')('frontend-code-challenge');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('./lib/logger');
var cors = require('cors');

const { authenticateJWT } = require("./helpers/auth");
var users = require('./routes/users');
const auth = require('./routes/auth');

var app = express();
var log = logger(app);
Expand All @@ -17,8 +18,10 @@ app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(authenticateJWT);

app.use('/users', users);
app.use('/auth', auth);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
Expand All @@ -38,7 +41,7 @@ app.use(function(err, req, res, next) {
});
});

app.set('port', process.env.PORT || 3000);
app.set('port', process.env.PORT || 3001);

var server = app.listen(app.get('port'), function() {
log.info(
Expand Down
10 changes: 5 additions & 5 deletions init_data.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"data": {
"1" : { "id": 1, "email": "[email protected]", "firstName": "Kyle", "lastName": "White", "state": "active"},
"2" : { "id": 2, "email": "[email protected]", "firstName": "Jane", "lastName": "Stone", "state": "active"},
"3" : { "id": 3, "email": "[email protected]", "firstName": "Lilly", "lastName": "Smith", "state": "pending"},
"4" : { "id": 4, "email": "[email protected]", "firstName": "Fred", "lastName": "Miles", "state": "pending"},
"5" : { "id": 5, "email": "[email protected]", "firstName": "Alexandra", "lastName": "Betts", "state": "pending"}
"1" : { "id": 1, "email": "[email protected]", "firstName": "Kyle", "lastName": "White", "state": "active", "hashed_password": "$2a$12$3GHUYzBWi.pTbMvE42UPRO52wffZV9qOsrUj2FjiTV4CVH.h3UuBW", "isAdmin": true},
"2" : { "id": 2, "email": "[email protected]", "firstName": "Jane", "lastName": "Stone", "state": "active", "hashed_password": null, "isAdmin": false},
"3" : { "id": 3, "email": "[email protected]", "firstName": "Lilly", "lastName": "Smith", "state": "pending", "hashed_password": null, "isAdmin": false},
"4" : { "id": 4, "email": "[email protected]", "firstName": "Fred", "lastName": "Miles", "state": "pending", "hashed_password": null, "isAdmin": false},
"5" : { "id": 5, "email": "[email protected]", "firstName": "Alexandra", "lastName": "Betts", "state": "pending", "hashed_password": null, "isAdmin": false}
}
}
Loading