Skip to content
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ You will complete the following tasks and do any extra wiring and package instal

Write the following user access functions inside `api/users/users-model.js`:

- [ ] `find`
- [] `find`
- [ ] `findBy`
- [ ] `findById`

Expand Down
45 changes: 43 additions & 2 deletions api/auth/auth-middleware.js
Original file line number Diff line number Diff line change
@@ -1,5 +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) => {
/*
If the user does not provide a token in the Authorization header:
Expand All @@ -16,6 +17,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 invalid'})
} else {
req.decodedToken = decodedToken
next()
}
})
}

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

Pull the decoded token from the req object, to avoid verifying it again!
*/
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: 401, message: 'Invalid credentials' })
} else {
req.user = user
next()
}
} catch (err) {
next(err)
}
}


Expand All @@ -62,6 +92,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
35 changes: 35 additions & 0 deletions api/auth/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
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 +18,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(user => {
res.status(201).json(user)
})
.catch(next)

});


Expand All @@ -37,6 +50,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',
}
12 changes: 12 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')
.join('roles', 'users.role_id', 'roles.role_id')
.select('user_id', 'username', 'role_name')
}

function findBy(filter) {
Expand All @@ -34,6 +37,11 @@ function findBy(filter) {
}
]
*/
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 @@ -47,6 +55,10 @@ 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
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