Skip to content

Commit

Permalink
jwt auth created and added in every API CRUD operation
Browse files Browse the repository at this point in the history
  • Loading branch information
Rober040992 committed Jan 13, 2025
1 parent f1a5fd8 commit 9484314
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 6 deletions.
11 changes: 6 additions & 5 deletions nodepop/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as loginController from './controllers/loginController.js'
import * as productController from './controllers/productController.js'
import * as sessionManager from './config/sessionManager.js'

import * as jwtAuth from './config/jwtAuth.js'
import upload from './config/uploadConfig.js';
import i18n from './config/i18nConfig.js';
import * as langController from './controllers/langController.js'
Expand Down Expand Up @@ -39,11 +40,11 @@ app.use(cookieParser()) // cookie parser to get cookies from client
app.use(express.static(join(import.meta.dirname, 'public'))) // set the folder where statis resources will be served

// API ROUTES //CRUD for products resource
app.get('/api/products', apiPorductController.apiProductGetList)
app.get('/api/products/:productId', apiPorductController.apiProductGetOne) //solo un producto por _id
app.post('/api/products', upload.single('Image'), apiPorductController.apiCreateNewProduct)
app.put('/api/products/:productId',upload.single('Image'), apiPorductController.apiProductUpdate)
app.delete('/api/products/:productId', apiPorductController.apiProductDelete)
app.get('/api/products', jwtAuth.guard, apiPorductController.apiProductGetList)
app.get('/api/products/:productId', jwtAuth.guard, apiPorductController.apiProductGetOne) //solo un producto por _id
app.post('/api/products', jwtAuth.guard, upload.single('Image'), apiPorductController.apiCreateNewProduct)
app.put('/api/products/:productId', jwtAuth.guard, upload.single('Image'), apiPorductController.apiProductUpdate)
app.delete('/api/products/:productId', jwtAuth.guard, apiPorductController.apiProductDelete)
// API LOGIN CRUD
app.post('/api/login', apiLoginCOntroller.loginJWT)

Expand Down
21 changes: 21 additions & 0 deletions nodepop/config/jwtAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import jwt from 'jsonwebtoken'
import createError from 'http-errors'

export function guard (req, res, next) {
//sacar el TokenJWT de la cabecera, body o de la query
const tokenJWT = req.get('Authorization') || req.body.jwt || req.query.jwt //para leer la cabeceza .get()
// controlar si no hay token con error
if (!tokenJWT) {
next(createError(401, 'NO TOKEN PROVIDED 🆘'))
return
}
// compruebo que es valido
jwt.verify(tokenJWT, process.env.JWT_SECRET, (err, payload) =>{
if (err) {
next(createError(401, 'Invalid Token JWT 🆘'))
return
}
next() // si es valido lo dejo pasar
} )

}
2 changes: 1 addition & 1 deletion nodepop/controllers/api/apiLoginController.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export async function loginJWT(req, res, next) {
// si lo encuentro genero un JWT
jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
expiresIn: '2d'
}, (err, tokenJWT) => {
}, (err, tokenJWT) => { //callback
if(err) {
next(err)
return
Expand Down
5 changes: 5 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ Nodepop es una aplicación web para la compra y venta de artículos de segunda m
## Características del API
### base URL: http://localhost:3000/api
### CRUD:
- AUTORIZACION para operaciones CRUD del API:
- tipo post /login . copiar el tokenJWT y pasar este como header:
Key = Authorization ; Value = el tokenJWT que genera el /login
o bien como query : ejm `/api/agents?jwt=eltokengeneradoalhacerlogin`

- Obtencion de lista de productos con metodo GET /products
```json
{
Expand Down

0 comments on commit 9484314

Please sign in to comment.