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

Hamza sajid #141

Open
wants to merge 4 commits into
base: main
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Using JSON Web Tokens
# Using JSON Web Tokens.

## Introduction

Expand Down
100 changes: 47 additions & 53 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,72 +1,66 @@
const { JWT_SECRET } = require("../secrets"); // use this secret!
const User = require("../users/users-model.js");
const jwt = require('jsonwebtoken');

const restricted = (req, res, next) => {
/*
If the user does not provide a token in the Authorization header:
status 401
{
"message": "Token required"
}

If the provided token does not verify:
status 401
{
"message": "Token invalid"
}
const token = req.headers.authorization;

Put the decoded token in the req object, to make life easier for middlewares downstream!
*/
}
if (!token) {
return next({ status: 401, message: "Token required" });
}

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:
status 403
{
"message": "This is not for you"
jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) {
return next({ status: 401, message: "Token invalid" });
}
req.decodedJwt = decoded;
next();
});
};

Pull the decoded token from the req object, to avoid verifying it again!
*/
}

const only = (role_name) => (req, res, next) => {
if (req.decodedJwt.role_name === role_name) {
next();
} else {
next({ status: 403, message: "This is not for you" });
}
};

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

User.findBy({username})
.then(user => {
if (!user) {
next({ status: 401, message: 'Invalid credentials'})
}
else {
next()
}
})
.catch(next)

};

const validateRoleName = (req, res, next) => {
/*
If the role_name in the body is valid, set req.role_name to be the trimmed string and proceed.

If role_name is missing from req.body, or if after trimming it is just an empty string,
set req.role_name to be 'student' and allow the request to proceed.

If role_name is 'admin' after trimming the string:
status 422
{
"message": "Role name can not be admin"
}

If role_name is over 32 characters after trimming the string:
status 422
{
"message": "Role name can not be longer than 32 chars"
}
*/
}
const { role_name } = req.body
if (!role_name || role_name.trim() === '') {
req.role_name = 'student'
next()
} else if (role_name.trim() === 'admin') {
next({ status: 422, message: 'Role name can not be admin' })
} else if (role_name.trim().length > 32) {
next({ status: 422, message: 'Role name can not be longer than 32 chars' })
} else {
req.role_name = role_name.trim()
next()
}
};

module.exports = {
restricted,
checkUsernameExists,
validateRoleName,
only,
}
};
47 changes: 37 additions & 10 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
const router = require("express").Router();
const { checkUsernameExists, validateRoleName } = require('./auth-middleware');
const { JWT_SECRET } = require("../secrets"); // use this secret!
const {tokenBuilder} = require('./auth-token')
const bcrypt = require('bcryptjs')
const User = require('../users/users-model')

router.post("/register", validateRoleName, (req, res, next) => {
/**
[POST] /api/auth/register { "username": "anna", "password": "1234", "role_name": "angel" }

response:
status 201
{
"user"_id: 3,
"username": "anna",
"role_name": "angel"
}
*/
const user = {
username: req.body.username,
password: req.body.password,
role_name: req.role_name
}

const hash = bcrypt.hashSync(user.password, 8)
user.password = hash

User.add(user)
.then(u => {
res.status(201).json({
user_id: u.user_id,
username: u.username,
role_name: u.role_name
})
})
.catch(next)

});


Expand All @@ -37,6 +49,21 @@ router.post("/login", checkUsernameExists, (req, res, next) => {
"role_name": "admin" // the role of the authenticated user
}
*/
let { username, password } = req.body

User.findBy({ username })
.then(([user]) => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = tokenBuilder(user)
res.status(200).json({ message: `${user.username} is back!`, token })
} else {
next({ status: 401, message: 'Invalid Credentials' })
}
})
.catch(next)



});

module.exports = router;
18 changes: 18 additions & 0 deletions api/auth/auth-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../secrets");

function tokenBuilder(user) {
const payload = {
subject: user.user_id,
username: user.username,
role_name: user.role_name
}
const options = {
expiresIn: '1d'
}
return jwt.sign(payload, JWT_SECRET, options)
}

module.exports = {
tokenBuilder,
}
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',
}
84 changes: 31 additions & 53 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,24 @@
const db = require('../../data/db-config.js');
const db = require("../../data/db-config");

function find() {
/**
You will need to join two tables.
Resolves to an ARRAY with all users.

[
{
"user_id": 1,
"username": "bob",
"role_name": "admin"
},
{
"user_id": 2,
"username": "sue",
"role_name": "instructor"
}
]
*/
return db("users")
.join("roles", "users.role_id", "roles.role_id")
.select("users.user_id", "users.username", "roles.role_name");
}

function findBy(filter) {
/**
You will need to join two tables.
Resolves to an ARRAY with all users that match the filter condition.

[
{
"user_id": 1,
"username": "bob",
"password": "$2a$10$dFwWjD8hi8K2I9/Y65MWi.WU0qn9eAVaiBoRSShTvuJVGw8XpsCiq",
"role_name": "admin",
}
]
*/
return db("users as u")
.join("roles as r", "u.role_id", "r.role_id")
.select("u.user_id", "u.username", "r.role_name", "u.password")
.where(filter);
}

function findById(user_id) {
/**
You will need to join two tables.
Resolves to the user with the given user_id.

{
"user_id": 2,
"username": "sue",
"role_name": "instructor"
}
*/
return db("users as u")
.join("roles as r", "u.role_id", "r.role_id")
.select("u.user_id", "u.username", "r.role_name")
.where("u.user_id", user_id)
.first();
}

/**
Expand All @@ -67,21 +39,27 @@ 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
2 changes: 1 addition & 1 deletion api/users/users-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const Users = require("./users-model.js");
const { restricted, only } = require("../auth/auth-middleware.js");

/**
[GET] /api/users
[GET] /api/users/

This endpoint is RESTRICTED: only authenticated clients
should have access.
Expand Down
Binary file modified data/auth.db3
Binary file not shown.
Loading