Skip to content
Open

hi #2

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
64 changes: 55 additions & 9 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const { JWT_SECRET } = require("../secrets"); // use this secret!
const Users = require("../users/users-model");
const jwt = require('jsonwebtoken')

const restricted = (req, res, next) => {
/*
Expand All @@ -16,9 +18,22 @@ const restricted = (req, res, next) => {

Put the decoded token in the req object, to make life easier for middlewares downstream!
*/
}
const token = req.headers.authorization
if (!token) {
next({status:401, message: "Token required"})
} else {
jwt.verify(token, JWT_SECRET, (err, tokenD) => {
if (err) {
next({status: 401, message: "Token invalid"})
} else {
req.decoded_token = tokenD;
}
next();
})
}
};

const only = role_name => (req, res, next) => {
const only = (role_name) => (req, res, next) => {
/*
If the user does not provide a token in the Authorization header with a role_name
inside its payload matching the role_name passed to this function as its argument:
Expand All @@ -29,21 +44,41 @@ const only = role_name => (req, res, next) => {

Pull the decoded token from the req object, to avoid verifying it again!
*/
}
if ( role_name === req.decoded_token.role_name ) {
next()
} else {
next({status: 403, message: "This is not for you"})
}
};


const checkUsernameExists = (req, res, next) => {
const checkUsernameExists = async (req, res, next) => {
/*
If the username in req.body does NOT exist in the database
status 401
{
"message": "Invalid credentials"
}
*/
}

try {
const user = await Users.findBy({ username: req.body.username }).first();
if (!user) {
next({ status: 401, message: "Invalid credentials" });
} else {
req.user = user;
next();
}
} catch (error) {
next(error);
}
};

const validateRoleName = (req, res, next) => {
let trimmed;
try {
trimmed = req.body.role_name.trim();
} catch (err) {
console.log("defaulting to student...");
}
/*
If the role_name in the body is valid, set req.role_name to be the trimmed string and proceed.

Expand All @@ -62,11 +97,22 @@ const validateRoleName = (req, res, next) => {
"message": "Role name can not be longer than 32 chars"
}
*/
}
if (!trimmed) {
req.role_name = "student";
next();
} else if (trimmed === "admin") {
next({ status: 422, message: "Role name can not be admin" });
} else if (trimmed.length > 32) {
next({ status: 422, message: "Role name can not be longer than 32 chars" });
} else {
req.role_name = trimmed;
next();
}
};

module.exports = {
restricted,
checkUsernameExists,
validateRoleName,
only,
}
};
35 changes: 32 additions & 3 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const router = require("express").Router();
const { checkUsernameExists, validateRoleName } = require('./auth-middleware');
const { checkUsernameExists, validateRoleName } = require("./auth-middleware");
const { JWT_SECRET } = require("../secrets"); // use this secret!

const Users = require("../users/users-model");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
router.post("/register", validateRoleName, (req, res, next) => {
/**
[POST] /api/auth/register { "username": "anna", "password": "1234", "role_name": "angel" }
Expand All @@ -14,9 +16,16 @@ router.post("/register", validateRoleName, (req, res, next) => {
"role_name": "angel"
}
*/
const { username, password } = req.body;
const role_name = req.role_name;
const hash = bcrypt.hashSync(password, 10);
Users.add({ username, password: hash, role_name })
.then((result) => {
res.status(201).json(result);
})
.catch(next);
});


router.post("/login", checkUsernameExists, (req, res, next) => {
/**
[POST] /api/auth/login { "username": "sue", "password": "1234" }
Expand All @@ -37,6 +46,26 @@ router.post("/login", checkUsernameExists, (req, res, next) => {
"role_name": "admin" // the role of the authenticated user
}
*/
if (bcrypt.compareSync(req.body.password, req.user.password)) {
const token = makeToken(req.user);
res.json({
message: `${req.user.username} is back!`,
token: token,
});
} else {
next({ status: 401, message: "Invalid credentials" });
}
});

const makeToken = (user) => {
const payload = {
subject: user.user_id,
role_name: user.role_name,
username: user.username,
};
const options = {
expiresIn: "1d",
};
return jwt.sign(payload, JWT_SECRET, options);
};
module.exports = router;
2 changes: 1 addition & 1 deletion api/secrets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
developers cloning this repo won't be able to run the project as is.
*/
module.exports = {

JWT_SECRET: process.env.JWT_SECRET || 'shh'
}
43 changes: 30 additions & 13 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const db = require('../../data/db-config.js');
const db = require("../../data/db-config.js");

function find() {
/**
Expand All @@ -18,6 +18,9 @@ function find() {
}
]
*/
return db("users")
.join("roles", "users.role_id", "roles.role_id")
.select("user_id", "username", "role_name");
}

function findBy(filter) {
Expand All @@ -34,6 +37,10 @@ function findBy(filter) {
}
]
*/
return db("users")
.where(filter)
.join("roles", "users.role_id", "roles.role_id")
.select("user_id", "username", "password", "role_name");
}

function findById(user_id) {
Expand All @@ -47,6 +54,11 @@ function findById(user_id) {
"role_name": "instructor"
}
*/
return db("users")
.where('user_id', user_id)
.join("roles", "users.role_id", "roles.role_id")
.select("user_id", "username", "role_name").first();

}

/**
Expand All @@ -67,21 +79,26 @@ function findById(user_id) {
"role_name": "team lead"
}
*/
async function add({ username, password, role_name }) { // done for you
let created_user_id
await db.transaction(async trx => {
let role_id_to_use
const [role] = await trx('roles').where('role_name', role_name)
async function add({ username, password, role_name }) {
// done for you
let created_user_id;
await db.transaction(async (trx) => {
let role_id_to_use;
const [role] = await trx("roles").where("role_name", role_name);
if (role) {
role_id_to_use = role.role_id
role_id_to_use = role.role_id;
} else {
const [role_id] = await trx('roles').insert({ role_name: role_name })
role_id_to_use = role_id
const [role_id] = await trx("roles").insert({ role_name: role_name });
role_id_to_use = role_id;
}
const [user_id] = await trx('users').insert({ username, password, role_id: role_id_to_use })
created_user_id = user_id
})
return findById(created_user_id)
const [user_id] = await trx("users").insert({
username,
password,
role_id: role_id_to_use,
});
created_user_id = user_id;
});
return findById(created_user_id);
}

module.exports = {
Expand Down
Binary file modified data/auth.db3
Binary file not shown.
6 changes: 6 additions & 0 deletions notes/commands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
```sh
git init
git add .
git commit -m"update"
git push -u origin bryan-guner
```
29 changes: 29 additions & 0 deletions notes/notes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
## Parts of a token

header
payload
subject
name
issues
verify signature

base 64 encoded

> Tokens CAN be encrypted

> Tokens can be larger than cookies

> Tokens are Client side

- client does most of work

> Sessions are server side

## Install JSON Web Token

[] npm i jsonwebtoken\

## Install bcrypt

https://www.npmjs.com/package/bcrypt
[] npm install bcrypt
Binary file added notes/session-vs-token-auth.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading