Skip to content

finished #131

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 1 commit 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
67 changes: 51 additions & 16 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,53 @@
const { JWT_SECRET } = require("../secrets"); // use this secret!
const { jwtSecret } = require("../secrets/index.js"); // 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:
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

const only = role_name => (req, res, next) => {
/*
if(!token){
res.status(401).json("Token needed")
}else{
jwt.verify(token, jwtSecret, (err, decoded) => {
if(err){
res.status(401).json("Token is bad: " + err.message)
}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!
*/
let decodedToken = req.decodedToken
if(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
Expand All @@ -40,33 +56,52 @@ const checkUsernameExists = (req, res, next) => {
"message": "Invalid credentials"
}
*/
User.findBy(req.body.username)
.then(response => {
if (!response) {
res.status(401).json({ message: 'Invalid credentials' })
}
else { next() }
})
.catch(err => {
res.status(500).json({ message: 'err.message' })
})
}


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 === "") {
req.body.role_name = 'student'
req.body.role_name.trim()
next()
}
else if (req.body.role_name === '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({ mesage: 'Role name can not be longer than 32 chars' })
}
else {
next()
}
}

module.exports = {
restricted,
checkUsernameExists,
validateRoleName,
only,
}
}
58 changes: 48 additions & 10 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const router = require("express").Router();
const { checkUsernameExists, validateRoleName } = require('./auth-middleware');
const { JWT_SECRET } = require("../secrets"); // use this secret!
const { checkUsernameExists, validateRoleName } = require('./auth-middleware');
const User = require('../users/users-model.js')
const bcrypt = require('bcryptjs')
const jwt = require("jsonwebtoken")
const { jwtSecret } = require("../secrets/index"); // use this secret!

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

/** [POST] /api/auth/register { "username": "anna", "password": "1234", "role_name": "angel" }
response:
status 201
{
Expand All @@ -14,29 +15,66 @@ router.post("/register", validateRoleName, (req, res, next) => {
"role_name": "angel"
}
*/
let user = req.body
const hash = bcrypt.hashSync(req.body.password, 8)
user.password = hash
User.add(user)
.then(newUser => {
res.status(201).json(newUser)
})
.catch(err => {
res.status(500).json({ message: err.message })
})
});

function makeToken(user){
const paylaod = {
subject: user.user_id,
username: user.username,
role_name: user.role_name
}
const options = {
expiresIn: "1d"
}
return jwt.sign(payload, jwtSecret, options)
}

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

* [POST] /api/auth/# { "username": "sue", "password": "1234" }
response:
status 200
{
"message": "sue is back!",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.ETC.ETC"
}

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
}
*/
let { username, password } = req.body

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

res.status(200).json({
message: `${user.username} is back!`,
token
})
}else{
res.status(401).json({ message: 'Invalid credentials' })
}
})
.catch(err => {
res.status(500).json({ message: err.message })
});

});

module.exports = router;
module.exports = router;
6 changes: 4 additions & 2 deletions api/secrets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
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.
*/
module.exports = {
const jwtSecret = process.env.JWT_SECRET || "shh";

}
module.exports = {
jwtSecret
}
25 changes: 14 additions & 11 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
@@ -1,10 +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.

[
{
"user_id": 1,
Expand All @@ -18,13 +16,15 @@ function find() {
}
]
*/
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,
Expand All @@ -34,33 +34,37 @@ function findBy(filter) {
}
]
*/
return db('user as u')
.join('roles as r', 'r.role_id', 'u.role_id')
.select('u.*', 'r.role_name')
.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', 'r.role_id', 'u.role_id')
.select('u.user_id', 'u.username', 'r.role_name')
.where('u.user_id', user_id)
}

/**
Creating a user requires a single insert (into users) if the role record with the given
* Creating a user requires a single insert (into users) if the role record with the given
role_name already exists in the db, or two inserts (into roles and then into users)
if the given role_name does not exist yet.

When an operation like creating a user involves inserts to several tables,
we want the operation to succeed or fail as a whole. It would not do to
insert a new role record and then have the insertion of the user fail.

In situations like these we use transactions: if anything inside the transaction
fails, all the database changes in it are rolled back.

{
"user_id": 7,
"username": "anna",
Expand All @@ -83,10 +87,9 @@ async function add({ username, password, role_name }) { // done for you
})
return findById(created_user_id)
}

module.exports = {
add,
find,
findBy,
findById,
};
};
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const server = require('./api/server.js');

const PORT = process.env.PORT || 5000;
const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
Expand Down
Loading