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

Cynthia Coronado #143

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
22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,32 +18,32 @@ 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`
- [ ] `findBy`
- [ ] `findById`
- [x] `find`
- [x] `findBy`
- [x] `findById`

#### 2B - Middleware Functions

Write the following auth middlewares inside `api/auth/auth-middleware.js`:

- [ ] `restricted`
- [ ] `only`
- [ ] `checkUsernameExists`
- [ ] `validateRoleName`
- [x] `restricted`
- [x] `only`
- [x] `checkUsernameExists`
- [x] `validateRoleName`

#### 2C - Endpoints

Authentication will be implemented using JSON Web Tokens.

Write the following endpoints inside `api/auth/auth-router.js`:

- [ ] `[POST] /api/auth/register`
- [ ] `[POST] /api/auth/login`
- [x] `[POST] /api/auth/register`
- [x] `[POST] /api/auth/login`

The endpoints inside `api/users/users-router.js` are built already but check them out:

- [ ] `[GET] /api/users` - only users with a valid token can access
- [ ] `[GET] /api/users/:user_id` - only users with a valid token AND a role of 'admin' can access
- [x] `[GET] /api/users` - only users with a valid token can access
- [x] `[GET] /api/users/:user_id` - only users with a valid token AND a role of 'admin' can access

#### 2D - Secrets File

Expand Down
62 changes: 61 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,24 @@ 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 reuired'
})
}
jwt.verify(token, JWT_SECRET, (err, decodedToken) => {
if(err){
next({
status: 401,
message: 'Token valid'
})
}else{
req.decodedToken = decodedToken
next()
}
})
}

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

Pull the decoded token from the req object, to avoid verifying it again!
*/
const roleName = req.decodedToken.roleName
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 +105,23 @@ 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 characters'
})
}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,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 User = require('../users/users-model')
const jwt = require('jsonwebtoken')

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


Expand All @@ -37,6 +48,30 @@ router.post("/login", checkUsernameExists, (req, res, next) => {
"role_name": "admin" // the role of the authenticated user
}
*/
if(bcrypt.compareSync(req.body.passord, req.user.passord)){
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;
3 changes: 2 additions & 1 deletion api/secrets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
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.
*/
const JWT_SECRET = process.env.JWT_SECRET ||'shh'
module.exports = {

JWT_SECRET
}
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,10 @@ 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 +54,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
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