You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

1 D铆as
5 Hrs
5 Min
54 Seg

Validar roles

20/24
Resources

Link of interest:

GraphQL Shield

Contributions 1

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Validacion de Roles

primero refactorizamos la funcion que recibe el context y revisa si el jwt es valido

const boom = require('@hapi/boom')
const checkJwtGql =async(context)=>{
  const {user}= await context.authenticate('jwt',
  {session:false});
  // console.log(context.req.headers["authorization"])
 // usamos la estrategia de jwt
  if(!user){
    throw boom.unauthorized('jwt is not valid')
  }
  return user
}
module.exports = checkJwtGql

funcion que valida los roles, pasandole el usuario

const boom = require('@hapi/boom')
const checkRoleGql =(user,...roles)=>{
  if(!roles.includes(user.role)){
    throw boom.unauthorized('role is not valid for this request')
  }
  return user
}
module.exports = checkRoleGql

aplicamos las funciones en el resolver que requiera authenticacion

const CategoryService = require("../../services/category.service");
const checkRoleGql = require("../../utils/auth/checkRoleGql");
const checkJwtGql = require("../../utils/auth/checkJwtGql");

const service = new CategoryService();

const allCategories= async()=>{
  const categories = await service.find();
  return categories
}
const addCategory = async (root, {dto},context)=>{
  const user = await checkJwtGql(context) //validate jtw
  checkRoleGql(user,'admin') ; // validate Role
  const newCategory = await service.create(dto);
  return newCategory;
}
const categoryById = async (root, args)=>{
  console.log(args)
  const category = await service.findOne(args.id);
  return category
}

module.exports= {allCategories, categoryById, addCategory}