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

Shivneel Prasad #144

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

const restricted = (req, res, next) => {
/*
/*
If the user does not provide a token in the Authorization header:
status 401
{
Expand All @@ -16,9 +17,21 @@ const restricted = (req, res, next) => {

Put the decoded token in the req object, to make life easier for middlewares downstream!
*/
const restricted = (req, res, next) => {
const token = req.headers.authorization
if(!token) {
return next({ status: 401, message: 'Token required' })
}
jwt.verify(token, JWT_SECRET, (err, decodedToken) => {
if (err) {
next({ status: 401, message: 'Token Invalid' })
} else {
req.decodedJwt = decodedToken
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 +42,36 @@ const only = role_name => (req, res, next) => {

Pull the decoded token from the req object, to avoid verifying it again!
*/
const only = role_name => (req, res, next) => {
const token = req.decodedJwt
if (token.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 checkUsernameExists = async (req, res, next) => {
const { username } = req.body
const user = await UM.findBy({ username })
if(!user) {
res.status(401).json({
status: 401,
message: 'Invalid credentials',
})
} else {
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.

Expand All @@ -62,11 +90,24 @@ const validateRoleName = (req, res, next) => {
"message": "Role name can not be longer than 32 chars"
}
*/
const validateRoleName = (req, res, next) => {
const roles = req.body
if(!roles.role_name || roles.role_name.trim() === ""){
roles.role_name = "student"
next()
} else if(roles.role_name.trim() === "admin"){
res.status(422).json({message: "Role name can not be admin"})
} else if(roles.role_name.trim().length > 32){
res.status(422).json({message: "Role name can not be longer than 32 chars"})
} else{
roles.role_name = roles.role_name.trim()
next()
}
}

module.exports = {
restricted,
checkUsernameExists,
validateRoleName,
only,
}
}
34 changes: 28 additions & 6 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
const router = require("express").Router();
const { checkUsernameExists, validateRoleName } = require('./auth-middleware');
const { JWT_SECRET } = require("../secrets"); // use this secret!
const { BCRYPT_ROUNDS } = require("../secrets"); // use this secret!
const UM = require('../users/users-model')
const bcrypt = require('bcrypt');
const tokenCreator = require('./tokenCreator')

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

Expand All @@ -13,11 +15,19 @@ router.post("/register", validateRoleName, (req, res, next) => {
"username": "anna",
"role_name": "angel"
}
*/
});
**/
router.post("/register", validateRoleName, (req, res, next) => {
let addUsers = req.body
const hash = bcrypt.hashSync(addUsers.password, BCRYPT_ROUNDS)
addUsers.password = hash

UM.add(addUsers)
.then(saved => {
res.status(201).json(saved)
})
.catch(next)
});

router.post("/login", checkUsernameExists, (req, res, next) => {
/**
[POST] /api/auth/login { "username": "sue", "password": "1234" }

Expand All @@ -36,7 +46,19 @@ router.post("/login", checkUsernameExists, (req, res, next) => {
"username" : "bob" // the username of the authenticated user
"role_name": "admin" // the role of the authenticated user
}
*/
**/
router.post("/login", checkUsernameExists, (req, res, next) => {
let { username, password } = req.body
UM.findBy({ username })
.then(([user]) => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = tokenCreator(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/tokenCreator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const jwt = require('jsonwebtoken')
const { JWT_SECRET } = require('../secrets/index')

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

return token
}

module.exports = tokenCreator
5 changes: 4 additions & 1 deletion api/secrets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,8 @@
developers cloning this repo won't be able to run the project as is.
*/
module.exports = {

BCRYPT_ROUNDS: process.env.BCRYPT_ROUNDS || 8,
NODE_ENV: process.env.NODE_ENV || 'development',
PORT: process.env.PORT || 9000,
JWT_SECRET: process.env.JWT_SECRET || 'shh',
}
2 changes: 2 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");
const morgan = require('morgan');

const authRouter = require("./auth/auth-router.js");
const usersRouter = require("./users/users-router.js");
Expand All @@ -10,6 +11,7 @@ const server = express();
server.use(helmet());
server.use(express.json());
server.use(cors());
server.use(morgan('dev'));

server.use("/api/auth", authRouter);
server.use("/api/users", usersRouter);
Expand Down
76 changes: 44 additions & 32 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
const db = require('../../data/db-config.js');

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

[
{
Expand All @@ -18,36 +17,49 @@ function find() {
}
]
*/
}

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",
}
]
*/
}

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"
function find() {
return db('users as u')
.leftJoin('roles as r ', 'u.role_id', '=', 'r.role_id' )
.select('u.user_id', 'u.username', 'r.role_name')
}

/**
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",
}
]
*/
function findBy(filter) {
return db('users as u')
.leftJoin('roles as r', 'u.role_id', 'r.role_id')
.select('u.user_id', 'u.username', 'u.password', 'r.role_name')
.where(filter)
}
/**
You will need to join two tables.
Resolves to the user with the given user_id.

{
"user_id": 2,
"username": "sue",
"role_name": "instructor"
}
*/

function findById(user_id) {
return db("users as u")
.leftJoin("roles as r", "u.role_id", "r.role_id")
.select("u.user_id","u.username","r.role_name")
.where({ user_id })
.first()
}
*/
}

/**
Creating a user requires a single insert (into users) if the role record with the given
Expand Down
Binary file modified data/auth.db3
Binary file not shown.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require('dotenv').config()

const server = require('./api/server.js');

const PORT = process.env.PORT || 9000;
Expand Down
Loading