Giter Club home page Giter Club logo

Comments (8)

hsluoyz avatar hsluoyz commented on May 18, 2024 1

Can you debug it and find the crashing line?

from jcasbin.

amelleHamouch avatar amelleHamouch commented on May 18, 2024

Line 69 , Enforcer enforcer = new Enforcer(tempConfPath, tempPoliciesPath);
says the enforcer is null

from jcasbin.

hsluoyz avatar hsluoyz commented on May 18, 2024

I can't squeeze out a bit information time to time like this. Can you provide a full working and runnable example to reproduce?

from jcasbin.

amelleHamouch avatar amelleHamouch commented on May 18, 2024

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package com.kapiasolutions.karma.filter;

import com.kapiasolutions.karma.util.LogUtil;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.casbin.jcasbin.main.Enforcer;

/**
*

  • @author ahamouch
    */
    @Provider
    public class JCasbinFilter implements ContainerRequestFilter {

    String conf;
    String policies;
    String key = "";

    @OverRide
    public void filter(ContainerRequestContext crc) throws IOException {

     try {
         InitialContext initialContext = new InitialContext();
         Context environmentContext = (Context) initialContext.lookup("java:/comp/env");
         configureCasbinFiles(environmentContext);
         UriInfo uriInfo = crc.getUriInfo();
         Request request = crc.getRequest();
         String requestPath = uriInfo.getPath();
         int index = requestPath.lastIndexOf("/");
         String object = requestPath.substring(index);
         String verb = request.getMethod();
         String domain = requestPath.replace(object, "");
         String confContent = decryptFile(key, conf);
         String polContent = decryptFile(key, policies);
    
         // adresse des fichier temporaires
         String tempConfPath = writeTempFile(confContent, conf);
         String tempPoliciesPath = writeTempFile(polContent, policies);
    
         //Utilisation de Enforcer de Casbin en lui passant les informations récupéré sur la requête
         Enforcer enforcer = new Enforcer(tempConfPath, tempPoliciesPath);
         //Si False accès non autorisé , requête annulée , envoi de la invalidAccessLevelResponse
         if (enforcer.enforce(object, domain, verb) == false) {
             String msg = String.format("You are not allowed to access this service", requestPath);
             CacheControl cc = new CacheControl();
             cc.setNoStore(true);
             Response invalidAccessLevelResponse = Response.status(Response.Status.FORBIDDEN)
                     .entity(msg)
                     .cacheControl(cc)
                     .build();
             crc.abortWith(invalidAccessLevelResponse);
         }
    
     } catch (NamingException ex) {
         LogUtil.showLog(ex);
     } catch (Exception ex) {
         Logger.getLogger(JCasbinFilter.class.getName()).log(Level.SEVERE, null, ex);
     }
    

    }

    //Création de la Réponse en cas d'accès refusé
    //Configuration de Casbin via les variables d'environnement
    private void configureCasbinFiles(Context environmentContext) throws NamingException {

     this.conf = (String) environmentContext.lookup("casbinConf");
     this.policies = (String) environmentContext.lookup("casbinPolicies");
    

    }

    //Lecture et récupération des données cryptées
    public static byte[] readCasbinFile(String path) throws Exception {

     byte[] encoded;
     encoded = Files.readAllBytes(Paths.get(path));
     return encoded;
    

    }

    //Génération de la clé à partir du String
    public static SecretKey generateKey(String keyStr) throws NoSuchAlgorithmException {
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    SecureRandom random = new SecureRandom(keyStr.getBytes());
    keygen.init(random);
    SecretKey secretKey = keygen.generateKey();
    return secretKey;
    }

    //Le fichier est décrypté ici
    public String decryptFile(String key, String path) throws Exception {
    SecretKey secretkey = generateKey(key);
    byte[] cipherText = readCasbinFile(path);
    byte[] IV = new byte[16];
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec keySpec = new SecretKeySpec(secretkey.getEncoded(), "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(IV);
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    byte[] decryptedText = cipher.doFinal(cipherText);
    String decrypt = new String(decryptedText);

     return decrypt;
    

    }

    //Création du fichier temporaire de config Casbin
    public String writeTempFile(String contentConf, String confFilePath) throws IOException {

     if (confFilePath.contains("model.conf")) {
         String tempPath = confFilePath.replace("model.conf", "tempModel.conf");
    
         FileWriter writer = new FileWriter(tempPath, false);
         writer.write(contentConf);
         writer.close();
         return tempPath;
     } else {
         String tempPath = confFilePath.replace("karma.policy", "Tempkarma.policy");
         FileWriter writer = new FileWriter(tempPath, false);
         writer.write(contentConf);
         writer.close();
         return tempPath;
     }
    

    }
    }

from jcasbin.

hsluoyz avatar hsluoyz commented on May 18, 2024

It's better in a GitHub repo, with project files, POM file, etc. So I can run it at once without copy-paste and setup a lot of code.

from jcasbin.

amelleHamouch avatar amelleHamouch commented on May 18, 2024

eh ..I don't have the right to share this code unfortunately ><

from jcasbin.

hsluoyz avatar hsluoyz commented on May 18, 2024

You should provide a minimized example, only show the bug.

from jcasbin.

dimi-nk avatar dimi-nk commented on May 18, 2024

I bumped into a similar issue last night. The code that parses the policy.csv expects everything to be delimited with ", " and nothing else. I'll make a PR to make that a bit more lenient.

from jcasbin.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.