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

Steve rivera #139

Open
wants to merge 8 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
94 changes: 44 additions & 50 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,67 +1,61 @@
const { JWT_SECRET } = require("../secrets"); // use this secret!
const User = require('../users/users-model')
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"
}

Put the decoded token in the req object, to make life easier for middlewares downstream!
*/
const token = req.body.authorization

if (!token) {
res.status(401).json({message: 'Token required'})
} else {
jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) {
res.status(401).json({message: 'Token invalid'})
} else {
req.decodedToken = decoded
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:
status 403
{
"message": "This is not for you"
}

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


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) => {
try {
const user = await User.findBy({ username: req.body.username })
if (!user) {
res.status(401).json({message: 'Invalid credentials'})
} else {
req.user = user
next()
}
*/
} catch (err) {
next(err)
}
}


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

if (req.body.role_name || req.body.role_name.trim()) {
req.role_name = 'student'
next()
} else if (req.body.role_name.trim === 'admin') {
res.status(422).json({message: 'Role name can not be admin'})
} else if (req.body.role_name.trim.length > 32) {
res.status(422).json({message: 'Role name can not be longer than 32 chars'})
} else {
req.role_name = req.body.role_name.trim()
next()
}
}

module.exports = {
Expand Down
71 changes: 41 additions & 30 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,53 @@
const router = require("express").Router();
const { checkUsernameExists, validateRoleName } = require('./auth-middleware');
const { JWT_SECRET } = require("../secrets"); // use this secret!
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
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"
}
*/

let user = req.body
const hash = bcrypt.hashSync(user.password, 8)
user.password = hash
User.add(user)
.then(newUser => {
res.status(201).json(newUser)
next()
})
.catch(err => {
res.status(500).json({message: err.message})
})
});


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

response:
status 200
{
"message": "sue is back!",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.ETC.ETC"

let { username, password } = req.body

User.findBy({ username })
.then(([user]) => {
if (user && bcrypt.compareSync(password, user.password)) {
const token = makeToken(user)

res.status(200).json({message: `${user.username} is back!`, token})
} else {
next({status: 401, message: 'Invalid credential'})
}

The token must expire in one day, and must provide the following information
in its payload:

{
"subject" : 1 // the user_id of the authenticated user
"username" : "bob" // the username of the authenticated user
"role_name": "admin" // the role of the authenticated user
}
*/
}).catch(err=>{
res.status(500).json({message: err.message})
})
});

function makeToken(user) {
const payload = {
subject: user.id,
username: user.username,
role: user.role
}
const options = {
expiresIn: "24h"
}
return jwt.sign(payload, JWT_SECRET, options)
}

module.exports = router;
3 changes: 2 additions & 1 deletion api/secrets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
If no fallback is provided, TESTS WON'T WORK and other
developers cloning this repo won't be able to run the project as is.
*/
const jwtSecret = process.env.JWT_SECRET || 'keepitsecret'
module.exports = {

jwtSecret
}
51 changes: 11 additions & 40 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,23 @@
const db = require('../../data/db-config.js');

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 as u')
.join('roles as r', 'r.role_id', 'u.role_id')
.select('u.user_id', 'u.username', 'r.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', 'r.role_id', 'u.role_id')
.select('u.user_id', 'u.username', 'u.password', 'r.role_name')
.where('r.role_name', 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', 'r.role_id', 'u.role_id')
.select('u.user_id', 'u.username', 'r.role_name')
.where('u.user_id', user_id).first()
}

/**
Expand Down
Loading