Search in sources :

Example 51 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class MailChimp method syncUser.

@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
    CloseableHttpResponse resp = null;
    String respJson = getUserJSON(user.getUserID(), request, resp);
    if (respJson != null) {
        String listID = (String) request.get("listID");
        JSONObject root;
        try {
            root = (JSONObject) new JSONParser().parse(respJson);
        } catch (ParseException | org.json.simple.parser.ParseException e) {
            logger.warn("Could not parse json", e);
            return;
        }
        JSONObject exactMatches = (JSONObject) root.get("exact_matches");
        JSONArray members = (JSONArray) exactMatches.get("members");
        if (members.size() == 0) {
            // logger.error("Could not find '" + user.getUserID() + "'");
            this.createUser(user, attributes, request);
            return;
        }
        JSONObject member = (JSONObject) members.get(0);
        String id = (String) member.get("id");
        member = new JSONObject();
        member.put("email_address", user.getUserID());
        JSONObject merge = new JSONObject();
        member.put("merge_fields", merge);
        for (Attribute attr : user.getAttribs().values()) {
            if (attributes.contains(attr.getName())) {
                if (attr.getName().equals("tags")) {
                    JSONArray tagList = new JSONArray();
                    for (String tagName : attr.getValues()) {
                        tagList.add(tagName);
                    }
                    member.put("tags", tagList);
                } else if (this.mergeAttributes.contains(attr.getName())) {
                    merge.put(attr.getName(), attr.getValues().get(0));
                } else {
                    member.put(attr.getName(), attr.getValues().get(0));
                }
            }
        }
        String json = member.toJSONString();
        StringBuffer sb = new StringBuffer();
        try {
            sb.append("https://").append(this.host).append("/3.0/lists/").append(URLEncoder.encode(listID, "UTF-8")).append("/members/").append(URLEncoder.encode(id, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
        }
        String url = sb.toString();
        HttpCon con = null;
        try {
            con = this.createClient();
            HttpPatch post = new HttpPatch(sb.toString());
            post.addHeader("Authorization", "Basic " + new String(java.util.Base64.getEncoder().encode(("x:" + apiKey).getBytes("UTF-8"))));
            StringEntity str = new StringEntity(json, ContentType.APPLICATION_JSON);
            post.setEntity(str);
            resp = con.getHttp().execute(post);
            if (resp.getStatusLine().getStatusCode() != 200) {
                logger.error("Could not create '" + user.getUserID() + "' - " + resp.getStatusLine().getStatusCode() + " - " + EntityUtils.toString(resp.getEntity()));
            }
            String jsonResp = EntityUtils.toString(resp.getEntity());
        } catch (Exception e) {
            logger.warn("Could not get connection", e);
        } finally {
            if (con != null) {
                try {
                    con.getHttp().close();
                } catch (IOException e) {
                }
                con.getBcm().close();
            }
        }
    } else {
        this.createUser(user, attributes, request);
    }
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) JSONArray(org.json.simple.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpPatch(org.apache.http.client.methods.HttpPatch) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.apache.http.ParseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) StringEntity(org.apache.http.entity.StringEntity) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.apache.http.ParseException)

Example 52 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class OAuth2JWT method createClient.

public HttpCon createClient() throws Exception {
    ArrayList<Header> defheaders = new ArrayList<Header>();
    defheaders.add(new BasicHeader("X-Csrf-Token", "1"));
    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false).build();
    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders).setDefaultRequestConfig(rc).build();
    HttpCon con = new HttpCon();
    con.setBcm(bhcm);
    con.setHttp(http);
    return con;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) ArrayList(java.util.ArrayList) BasicHeader(org.apache.http.message.BasicHeader) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Example 53 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class OpenUnisonRestful method bind.

@Override
public void bind(BindInterceptorChain chain, DistinguishedName dn, Password pwd, LDAPConstraints constraints) throws LDAPException {
    String localBindDN = this.getRemoteMappedDN(dn.getDN()).toString();
    HttpCon con;
    try {
        con = this.createClient();
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR), LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    }
    try {
        LdapJsonBindRequest bindRequest = new LdapJsonBindRequest();
        bindRequest.setPassword(new String(pwd.getValue()));
        StringBuffer b = new StringBuffer();
        b.append(this.uriPath).append('/').append(URLEncoder.encode(localBindDN, "UTF-8"));
        StringBuffer urlBuffer = new StringBuffer();
        urlBuffer.append(this.urlBase);
        urlBuffer.append(b);
        HttpPost post = new HttpPost(urlBuffer.toString());
        this.addAuthorizationHeader(b.toString(), post);
        StringEntity str = new StringEntity(gson.toJson(bindRequest), ContentType.APPLICATION_JSON);
        post.setEntity(str);
        HttpResponse resp = con.getHttp().execute(post);
        String json = EntityUtils.toString(resp.getEntity());
        LdapJsonError ldapResponse = gson.fromJson(json, LdapJsonError.class);
        if (ldapResponse.getResponseCode() != 0) {
            throw new LDAPException(LDAPException.resultCodeToString(ldapResponse.getResponseCode()), ldapResponse.getResponseCode(), ldapResponse.getErrorMessage());
        }
    } catch (LDAPException e) {
        throw e;
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR), LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    } finally {
        if (con != null) {
            try {
                con.getHttp().close();
            } catch (IOException e) {
            // no point
            }
            con.getBcm().close();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) LdapJsonError(com.tremolosecurity.ldapJson.LdapJsonError) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) IOException(java.io.IOException) LdapJsonBindRequest(com.tremolosecurity.ldapJson.LdapJsonBindRequest)

Example 54 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class OpenUnisonRestful method search.

@Override
public void search(SearchInterceptorChain chain, DistinguishedName base, Int scope, Filter filter, ArrayList<Attribute> attributes, Bool typesOnly, Results results, LDAPSearchConstraints constraints) throws LDAPException {
    String localBindDN = this.getRemoteMappedDN(base.getDN()).toString();
    HttpCon con;
    try {
        con = this.createClient();
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR), LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    }
    try {
        String searchScope;
        switch(scope.getValue()) {
            case 0:
                searchScope = "base";
                break;
            case 1:
                searchScope = "one";
                break;
            case 2:
                searchScope = "sub";
                break;
            default:
                throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR), LDAPException.OPERATIONS_ERROR, "Unknown search scope : " + scope.getValue());
        }
        StringBuffer b = new StringBuffer();
        b.append(this.uriPath).append('/').append(URLEncoder.encode(localBindDN, "UTF-8")).append('/').append(URLEncoder.encode(searchScope, "UTF-8"));
        StringBuffer urlBuffer = new StringBuffer();
        urlBuffer.append(this.urlBase).append(b);
        urlBuffer.append("?filter=").append(URLEncoder.encode(filter.getRoot().toString(), "UTF-8"));
        for (Attribute attribute : attributes) {
            urlBuffer.append("&attributes=").append(URLEncoder.encode(attribute.getAttribute().getName(), "UTF-8"));
        }
        HttpGet get = new HttpGet(urlBuffer.toString());
        this.addAuthorizationHeader(b.toString(), get);
        HttpResponse resp = con.getHttp().execute(get);
        String json = EntityUtils.toString(resp.getEntity());
        if (resp.getStatusLine().getStatusCode() == 200) {
            ArrayList<Entry> toReturn = new ArrayList<Entry>();
            Type listType = new TypeToken<List<LdapJsonEntry>>() {
            }.getType();
            List<LdapJsonEntry> returned = gson.fromJson(json, listType);
            for (LdapJsonEntry fromServer : returned) {
                LDAPAttributeSet attrs = new LDAPAttributeSet();
                for (String attrName : fromServer.getAttrs().keySet()) {
                    LDAPAttribute attr = new LDAPAttribute(attrName);
                    for (String value : fromServer.getAttrs().get(attrName)) {
                        attr.addValue(value);
                    }
                    attrs.add(attr);
                }
                LDAPEntry ldapEntry = new LDAPEntry(this.getLocalMappedDN(new DN(fromServer.getDn())).toString(), attrs);
                toReturn.add(new Entry(ldapEntry));
            }
            chain.addResult(results, new IteratorEntrySet(toReturn.iterator()), base, scope, filter, attributes, typesOnly, constraints);
        } else {
            LdapJsonError ldapResponse = gson.fromJson(json, LdapJsonError.class);
            throw new LDAPException(LDAPException.resultCodeToString(ldapResponse.getResponseCode()), ldapResponse.getResponseCode(), ldapResponse.getErrorMessage());
        }
    } catch (LDAPException e) {
        throw e;
    } catch (Exception e) {
        throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR), LDAPException.OPERATIONS_ERROR, "Could not create connection", e);
    } finally {
        if (con != null) {
            try {
                con.getHttp().close();
            } catch (IOException e) {
            // no point
            }
            con.getBcm().close();
        }
    }
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) LdapJsonEntry(com.tremolosecurity.ldapJson.LdapJsonEntry) HttpResponse(org.apache.http.HttpResponse) DN(com.novell.ldap.util.DN) IOException(java.io.IOException) IOException(java.io.IOException) IteratorEntrySet(net.sourceforge.myvd.util.IteratorEntrySet) LdapJsonEntry(com.tremolosecurity.ldapJson.LdapJsonEntry) ContentType(org.apache.http.entity.ContentType) Type(java.lang.reflect.Type) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) LdapJsonError(com.tremolosecurity.ldapJson.LdapJsonError) ArrayList(java.util.ArrayList) List(java.util.List)

Example 55 with HttpCon

use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.

the class OpenUnisonRestful method createClient.

public HttpCon createClient() throws Exception {
    ArrayList<Header> defheaders = new ArrayList<Header>();
    defheaders.add(new BasicHeader("X-Csrf-Token", "1"));
    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false).build();
    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders).setDefaultRequestConfig(rc).build();
    HttpCon con = new HttpCon();
    con.setBcm(bhcm);
    con.setHttp(http);
    return con;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) ArrayList(java.util.ArrayList) BasicHeader(org.apache.http.message.BasicHeader) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Aggregations

HttpCon (com.tremolosecurity.provisioning.util.HttpCon)104 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)82 IOException (java.io.IOException)70 ClientProtocolException (org.apache.http.client.ClientProtocolException)49 JSONObject (org.json.simple.JSONObject)43 ParseException (org.json.simple.parser.ParseException)33 Workflow (com.tremolosecurity.provisioning.core.Workflow)32 ArrayList (java.util.ArrayList)32 UnsupportedEncodingException (java.io.UnsupportedEncodingException)31 OpenShiftTarget (com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)27 JSONParser (org.json.simple.parser.JSONParser)25 HashMap (java.util.HashMap)24 JSONArray (org.json.simple.JSONArray)22 User (com.tremolosecurity.provisioning.core.User)18 Attribute (com.tremolosecurity.saml.Attribute)17 Gson (com.google.gson.Gson)16 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HashSet (java.util.HashSet)13 List (java.util.List)13 KSToken (com.tremolosecurity.unison.openstack.util.KSToken)12