Search in sources :

Example 1 with SwaggerAuthorizationException

use of com.crivano.swaggerservlet.SwaggerAuthorizationException in project balcaovirtual by trf2-jus-br.

the class ProcessoNumeroPecaIdPdfGet method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    String usuario = null;
    String origem;
    if (ProcessoValidarGet.isValidToken(req.token, req.numero)) {
        origem = "pub";
    } else {
        Usuario u = BalcaojusServlet.getPrincipal();
        if (u == null)
            throw new SwaggerAuthorizationException("Usuário não autenticado e token inexistente ou inválido");
        usuario = u.usuario;
        if (u.usuarios.get(req.sistema) != null)
            origem = u.usuarios.get(req.sistema).origem;
        else
            origem = "pub";
    }
    resp.jwt = DownloadJwtFilenameGet.jwt(origem, usuario, null, req.sistema, req.numero, req.id, null, null, null, null, null, null);
}
Also used : Usuario(br.jus.trf2.balcaojus.AutenticarPost.Usuario) SwaggerAuthorizationException(com.crivano.swaggerservlet.SwaggerAuthorizationException)

Example 2 with SwaggerAuthorizationException

use of com.crivano.swaggerservlet.SwaggerAuthorizationException in project balcaovirtual by trf2-jus-br.

the class UploadServlet method doPost.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
    // try {
    // SessionsCreatePost.assertAuthorization();
    // } catch (SwaggerAuthorizationException e) {
    // throw new ServletException("É necessário estar autenticado para enviar aquivos.");
    // }
    corsHeaders(response);
    String dirFinal = Utils.getDirFinal();
    String dirTemp = Utils.getDirTemp();
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(dirTemp));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        @SuppressWarnings("rawtypes") List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        @SuppressWarnings("rawtypes") Iterator i = fileItems.iterator();
        JSONObject o = new JSONObject();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fileName = fi.getName();
                long sizeInBytes = fi.getSize();
                String fileId = UUID.randomUUID().toString();
                // Write the file
                file = new File(dirFinal + "/" + fileId + ".pdf");
                fi.write(file);
                o.put("name", fileName);
                o.put("size", sizeInBytes);
                o.put("id", fileId);
            }
        }
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(o.toString(3));
    } catch (Exception ex) {
        System.out.println(ex);
    }
}
Also used : DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) SwaggerAuthorizationException(com.crivano.swaggerservlet.SwaggerAuthorizationException) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JSONObject(org.json.JSONObject) Iterator(java.util.Iterator) List(java.util.List) File(java.io.File)

Example 3 with SwaggerAuthorizationException

use of com.crivano.swaggerservlet.SwaggerAuthorizationException in project balcaovirtual by trf2-jus-br.

the class AutenticarPost method verify.

public static Map<String, Object> verify(String jwt) throws SwaggerAuthorizationException {
    final JWTVerifier verifier = new JWTVerifier(Utils.getJwtPassword());
    Map<String, Object> map;
    try {
        map = verifier.verify(jwt);
    } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | SignatureException | IOException | JWTVerifyException e) {
        throw new SwaggerAuthorizationException(e);
    }
    return map;
}
Also used : JWTVerifyException(com.auth0.jwt.JWTVerifyException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) JWTVerifier(com.auth0.jwt.JWTVerifier) SwaggerAuthorizationException(com.crivano.swaggerservlet.SwaggerAuthorizationException)

Example 4 with SwaggerAuthorizationException

use of com.crivano.swaggerservlet.SwaggerAuthorizationException in project balcaovirtual by trf2-jus-br.

the class AutenticarPost method run.

@Override
public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
    String usuariosRestritos = Utils.getUsuariosRestritos();
    if (usuariosRestritos != null) {
        if (!ArrayUtils.contains(usuariosRestritos.split(","), req.username))
            throw new PresentableUnloggedException("Usuário não autorizado.");
    }
    // Read list from connected systems
    String[] systems = Utils.getSystems();
    if (systems == null)
        return;
    String authorization = "Basic " + SwaggerUtils.base64Encode((req.username + ":" + req.password).getBytes());
    Map<String, SwaggerCallParameters> mapp = new HashMap<>();
    for (String system : systems) {
        String urlsys = Utils.getApiUrl(system);
        IUsuarioUsernameGet.Request q = new IUsuarioUsernameGet.Request();
        q.username = req.username;
        mapp.put(system, new SwaggerCallParameters(system + "-autenticar-usuário", authorization, "GET", urlsys + "/usuario/" + req.username, q, IUsuarioUsernameGet.Response.class));
    }
    SwaggerMultipleCallResult mcr = SwaggerCall.callMultiple(mapp, BalcaojusServlet.TIMEOUT_MILLISECONDS);
    resp.status = Utils.getStatus(mcr);
    String origem = null;
    String usuarios = null;
    String cpf = null;
    String nome = null;
    String email = null;
    for (String system : mcr.responses.keySet()) {
        IUsuarioUsernameGet.Response u = (IUsuarioUsernameGet.Response) mcr.responses.get(system);
        if (u.codusu == null)
            continue;
        if (origem == null)
            origem = u.interno ? "int" : "ext";
        else if ((origem.equals("int") && !u.interno) || (origem.equals("ext") && u.interno))
            origem = "int/ext";
        if (u.cpf != null)
            cpf = u.cpf;
        if (u.nome != null)
            nome = u.nome;
        if (u.email != null)
            email = u.email;
        if (usuarios == null)
            usuarios = "";
        else
            usuarios += ";";
        usuarios += system + "," + u.codusu + "," + (u.interno ? "int" : "ext") + "," + serialize(u.codentidade != null && !u.codentidade.equals("0") ? u.codentidade : null) + "," + serialize(u.entidade) + "," + serialize(u.codunidade != null && !u.codunidade.equals("0") ? u.codunidade : null) + "," + serialize(u.unidade) + "," + (u.perfil != null && !u.perfil.equals("") ? u.perfil.toLowerCase() : "null");
    }
    if (usuarios == null)
        throw new SwaggerAuthorizationException("Credenciais rejeitadas. Base" + (systems.length == 1 ? "" : "s") + " acessada" + (systems.length == 1 ? "" : "s") + ": " + Utils.getSystemsNames() + ".", mcr.status);
    String jwt = jwt(origem, req.username, cpf, nome, email, usuarios);
    verify(jwt);
    resp.id_token = jwt;
    Cookie cookie = buildCookie(jwt);
    SwaggerServlet.getHttpServletResponse().addCookie(cookie);
    Usuario.setSenha(req.username, req.password);
}
Also used : Cookie(javax.servlet.http.Cookie) IUsuarioUsernameGet(br.jus.trf2.sistemaprocessual.ISistemaProcessual.IUsuarioUsernameGet) HashMap(java.util.HashMap) SwaggerCallParameters(com.crivano.swaggerservlet.SwaggerCallParameters) SwaggerAuthorizationException(com.crivano.swaggerservlet.SwaggerAuthorizationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) PresentableUnloggedException(com.crivano.swaggerservlet.PresentableUnloggedException) SwaggerMultipleCallResult(com.crivano.swaggerservlet.SwaggerMultipleCallResult)

Aggregations

SwaggerAuthorizationException (com.crivano.swaggerservlet.SwaggerAuthorizationException)4 IOException (java.io.IOException)2 Usuario (br.jus.trf2.balcaojus.AutenticarPost.Usuario)1 IUsuarioUsernameGet (br.jus.trf2.sistemaprocessual.ISistemaProcessual.IUsuarioUsernameGet)1 JWTVerifier (com.auth0.jwt.JWTVerifier)1 JWTVerifyException (com.auth0.jwt.JWTVerifyException)1 PresentableUnloggedException (com.crivano.swaggerservlet.PresentableUnloggedException)1 SwaggerCallParameters (com.crivano.swaggerservlet.SwaggerCallParameters)1 SwaggerMultipleCallResult (com.crivano.swaggerservlet.SwaggerMultipleCallResult)1 File (java.io.File)1 InvalidKeyException (java.security.InvalidKeyException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SignatureException (java.security.SignatureException)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 List (java.util.List)1 ServletException (javax.servlet.ServletException)1 Cookie (javax.servlet.http.Cookie)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 FileItem (org.apache.commons.fileupload.FileItem)1