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

mvp #137

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open

mvp #137

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
50 changes: 49 additions & 1 deletion api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
const { JWT_SECRET } = require("../secrets"); // use this secret!

const {findBy, find} = require('../users/users-model')

const jwt = require('jsonwebtoken') // used to create, sign, and verify tokens

const restricted = (req, res, next) => {
/*
If the user does not provide a token in the Authorization header:
Expand All @@ -16,6 +20,18 @@ 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) {
return next({ status: 401, message: "Token required" }); //if there is no token, send back a message
}
jwt.verify(token, JWT_SECRET, (err, decodedToken) => {
if (err) {
next({ status: 401, message: "Token invalid" }); //if there is an error, send back a message
} else {
req.decodedToken = decodedToken
next()
}
})
}

const only = role_name => (req, res, next) => {
Expand All @@ -29,17 +45,35 @@ const only = role_name => (req, res, next) => {

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


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 findBy({username: req.body.username}) //we put user in brackets to get the value of the first element in the array
if (!user) {
next({ status: 401, message: "Invalid credentials" })
} else {
req.user = user
next()
}
} catch (error) {
next(error)
}

}


Expand All @@ -62,6 +96,20 @@ const validateRoleName = (req, res, next) => {
"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().toLowerCase() === 'admin') {
next({status: 422, message: 'Role name can not be admin'})
} else if (req.body.role_name.trim().length > 32) {
next({status: 422, message: 'Role name can not be longer than 32 chars'})
} else {
req.role_name = req.body.role_name.trim()
next()
}


}

module.exports = {
Expand Down
35 changes: 34 additions & 1 deletion api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
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) => {
/**
Expand All @@ -9,11 +12,20 @@ router.post("/register", validateRoleName, (req, res, next) => {
response:
status 201
{
"user"_id: 3,
"username": "anna",
"user"_id: 3,
"role_name": "angel"
}
*/

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


Expand All @@ -37,6 +49,27 @@ 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 = buildToken(req.user);
res.status(200).json({
message: `${req.user.username} is back!`,
token
});
} else {
next({ status: 401, message: "Invalid credentials" });
}
});

function buildToken(user) {
const payload = {
subject: user.user_id, //user.id would not work because user is a user object, not a user object with an id
username: user.username,
role_name: user.role_name
};
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',
}
61 changes: 49 additions & 12 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,56 @@ function find() {
}
]
*/

/*
select
user_id,
username,
role_name
from users
join roles on
users.role_id = roles.role_id
*/

return db('users')
.join('roles', 'users.role_id', 'roles.role_id')
.select('user_id', 'username', 'role_name')
}

function findBy(filter) {
/**
You will need to join two tables.
Resolves to an ARRAY with all users that match the filter condition.
/**
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",
}
]
*/
[
{
"user_id": 1,
"username": "bob",
"password": "$2a$10$dFwWjD8hi8K2I9/Y65MWi.WU0qn9eAVaiBoRSShTvuJVGw8XpsCiq",
"role_name": "admin",
}
]
*/

/*
select
user_id,
username,
password,
role_name
from users
join roles on
users.role_id = roles.role_id
where users.user_id = 1;
*/

return db('users')
.join('roles', 'users.role_id', 'roles.role_id')
.select('user_id', 'username', 'password', 'role_name')
.where(filter)
}


function findById(user_id) {
/**
You will need to join two tables.
Expand All @@ -47,6 +79,11 @@ function findById(user_id) {
"role_name": "instructor"
}
*/

return db('users')
.join('roles', 'users.role_id', 'roles.role_id')
.select('user_id', 'username','role_name')
.where('users.user_id', user_id).first()
}

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