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

complete mvp #135

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
44 changes: 44 additions & 0 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ const restricted = (req, res, next) => {

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("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) => {
Expand All @@ -29,6 +43,12 @@ const only = role_name => (req, res, next) => {

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()
}
}


Expand All @@ -40,6 +60,16 @@ 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' })
})
}


Expand All @@ -62,6 +92,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 === "") {
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 = {
Expand Down
41 changes: 41 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 User = require('../users/users-model.js')
const bcrypt = require('bcryptjs')
const jwt = require("jsonwebtoken")

router.post("/register", validateRoleName, (req, res, next) => {
/**
Expand All @@ -14,8 +17,29 @@ 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("/login", checkUsernameExists, (req, res, next) => {
/**
Expand All @@ -37,6 +61,23 @@ router.post("/login", checkUsernameExists, (req, res, next) => {
"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;
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 || "shh";

module.exports = {
jwtSecret
}
11 changes: 11 additions & 0 deletions api/users/users-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ 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) {
Expand All @@ -34,6 +37,10 @@ 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) {
Expand All @@ -47,6 +54,10 @@ function findById(user_id) {
"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)
}

/**
Expand Down
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 || 6000;

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