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

Marina monsivais #130

Open
wants to merge 7 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
48 changes: 47 additions & 1 deletion api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { JWT_SECRET } = require("../secrets"); // use this secret!
const usersModel = require('../users/users-model')

const restricted = (req, res, next) => {
/*
Expand All @@ -16,6 +17,22 @@ 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){
res.status(401).json({
message:"Token required"
})
} else {
jwt.verify(token,JWT_SECRET,(err,decoded)=>{
if(err){
res.status(401).json("Token invalid" )
}else{
req.decodedToken = decoded
next()
}
})
}

}

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

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) => {
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 usersModel.findBy({username: req.body.username})
if(!user){
next({ status: 422, message:"Invalid credentials" })
}else{
req.user = user
next()
}
}catch(err){
next(err)
}
}


Expand All @@ -62,6 +97,17 @@ 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() === '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
43 changes: 43 additions & 0 deletions 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 Users = require('../users/users-model')

router.post("/register", validateRoleName, (req, res, next) => {
/**
Expand All @@ -14,6 +17,16 @@ router.post("/register", validateRoleName, (req, res, next) => {
"role_name": "angel"
}
*/

let user = req.body;
const rounds = process.env.BCRYPT_ROUNDS || 8;
const hash = bcrypt.hashSync(user.password, rounds);
user.password = hash
Users.add(user)
.then(saved => {
res.status(201).json(saved)
next()
})
});


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

Users.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 Credentials' });
}
})
.catch(next);
});

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



module.exports = router;
4 changes: 3 additions & 1 deletion 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 || 'keepitsecret'

module.exports = {
jwtSecret
}
25 changes: 25 additions & 0 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,14 @@ function find() {
"role_name": "instructor"
}
]
select u.username, u.user_id, r.role_name
from users u
join roles r
on u.role_id = r.role_id
*/
return db('users as u')
.join("roles as r", 'u.role_id', '=', 'r.role_id')
.select('u.username','u.user_id', 'r.role_name');
}

function findBy(filter) {
Expand All @@ -33,7 +40,16 @@ function findBy(filter) {
"role_name": "admin",
}
]
select u.user_id, u.username, u.password, r.role_name
from users u
join roles r
on u.role_id = r.role_id
where u.user_id = 1
*/
return db('users as u')
.join('roles as r', 'u.role_id', '=', 'r.role_id')
.select('u.user_id','u.username','u.password','r.role_name')
.where('r.role_name', filter)
}

function findById(user_id) {
Expand All @@ -46,7 +62,16 @@ function findById(user_id) {
"username": "sue",
"role_name": "instructor"
}
select u.user_id, u.username, r.role_name
from users u
join roles r
on u.role_id = r.role_id
where u.user_id = 2
*/
return db('users as u')
.join('roles r', 'u.role_id', '=', 'r.role_id')
.select('u.user_id','u.username','r.role_name')
.where('u.user_id', user_id).first();
}

/**
Expand Down
1 change: 1 addition & 0 deletions api/users/users-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ router.get("/", restricted, (req, res, next) => { // done for you
Users.find()
.then(users => {
res.json(users);
console.log([users])
})
.catch(next);
});
Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require("dotenv").config();
const server = require('./api/server.js');

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