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

Nearly there #146

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

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

const only = role_name => (req, res, next) => {
Expand All @@ -29,17 +43,34 @@ 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 (role_name === req.decodedToken.role_name){
next()
} else {
next({ status: 403, message: "This is not for you"})
}
}


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


Expand All @@ -62,6 +93,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
34 changes: 34 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 User = require('../users/users-model')

router.post("/register", validateRoleName, (req, res, next) => {
/**
Expand All @@ -14,6 +17,15 @@ router.post("/register", validateRoleName, (req, res, next) => {
"role_name": "angel"
}
*/
const { username, password } = req.body
const { role_name } = req
const hash = bcrypt.hashSync(password, 8)
User.add({ username, password: hash, role_name })
.then(newUser => {
res.status(201).json(newUser)
})
.catch(next)

});


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

function buildToken(user) {
const payload = {
subject: user.user_id,
role_name: user.role_name,
username: user.username,
}
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',
}
38 changes: 38 additions & 0 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,20 @@ 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) {
Expand All @@ -33,7 +47,24 @@ function findBy(filter) {
"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) {
Expand All @@ -46,7 +77,14 @@ function findById(user_id) {
"username": "sue",
"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