Search in sources :

Example 56 with Exchange

use of com.predic8.membrane.core.exchange.Exchange in project service-proxy by membrane.

the class LoginDialog method handleLoginRequest.

public void handleLoginRequest(Exchange exc) throws Exception {
    Session s = sessionManager.getSession(exc);
    String uri = exc.getRequest().getUri().substring(path.length() - 1);
    if (uri.indexOf('?') >= 0)
        uri = uri.substring(0, uri.indexOf('?'));
    exc.getDestinations().set(0, uri);
    if (uri.equals("/logout")) {
        if (s != null)
            s.clear();
        exc.setResponse(Response.redirect(path, false).body("").build());
    } else if (uri.equals("/consent")) {
        if (exc.getRequest().getMethod().equals("POST"))
            processConsentPageResult(exc, s);
        else
            showConsentPage(exc, s);
    } else if (uri.equals("/")) {
        if (s == null || !s.isPreAuthorized()) {
            if (exc.getRequest().getMethod().equals("POST")) {
                Map<String, String> userAttributes;
                Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
                String username = params.get("username");
                if (username == null) {
                    showPage(exc, 0, "error", "INVALID_PASSWORD");
                    return;
                }
                if (accountBlocker != null && accountBlocker.isBlocked(username)) {
                    showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
                    return;
                }
                try {
                    userAttributes = userDataProvider.verify(params);
                } catch (NoSuchElementException e) {
                    List<String> params2 = Lists.newArrayList("error", "INVALID_PASSWORD");
                    if (accountBlocker != null) {
                        if (accountBlocker.fail(username))
                            params2.addAll(Lists.newArrayList("accountBlocked", "true"));
                    }
                    showPage(exc, 0, params2.toArray());
                    return;
                } catch (Exception e) {
                    log.error("", e);
                    showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
                    return;
                }
                if (exposeUserCredentialsToSession) {
                    for (Map.Entry<String, String> param : params.entrySet()) if (!userAttributes.containsKey(param.getKey()))
                        userAttributes.put(param.getKey(), param.getValue());
                }
                if (tokenProvider != null)
                    showPage(exc, 1);
                else {
                    String target = params.get("target");
                    if (StringUtils.isEmpty(target))
                        target = "/";
                    exc.setResponse(Response.redirectWithout300(target).build());
                }
                Session session = sessionManager.getOrCreateSession(exc);
                session.preAuthorize(username, userAttributes);
                if (tokenProvider != null)
                    tokenProvider.requestToken(session.getUserAttributes());
            } else {
                showPage(exc, 0);
            }
        } else {
            if (accountBlocker != null && accountBlocker.isBlocked(s.getUserName())) {
                showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
                return;
            }
            if (exc.getRequest().getMethod().equals("POST")) {
                String token = URLParamUtil.getParams(uriFactory, exc).get("token");
                try {
                    if (tokenProvider != null)
                        tokenProvider.verifyToken(s.getUserAttributes(), token);
                } catch (NoSuchElementException e) {
                    List<String> params = Lists.newArrayList("error", "INVALID_TOKEN");
                    if (accountBlocker != null)
                        if (accountBlocker.fail(s.getUserName()))
                            params.addAll(Lists.newArrayList("accountBlocked", "true"));
                    s.clear();
                    showPage(exc, 0, params.toArray());
                    return;
                } catch (Exception e) {
                    log.error("", e);
                    s.clear();
                    showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
                    return;
                }
                if (accountBlocker != null)
                    accountBlocker.unblock(s.getUserName());
                String target = URLParamUtil.getParams(uriFactory, exc).get("target");
                if (StringUtils.isEmpty(target))
                    target = "/";
                if (this.message != null)
                    exc.setResponse(Response.redirectWithout300(target, message).build());
                else
                    exc.setResponse(Response.redirectWithout300(target).build());
                s.authorize();
            } else {
                showPage(exc, 1);
            }
        }
    } else {
        wsi.handleRequest(exc);
    }
}
Also used : ResolverMap(com.predic8.membrane.core.resolver.ResolverMap) ParseException(com.floreysoft.jmte.message.ParseException) MalformedURLException(java.net.MalformedURLException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 57 with Exchange

use of com.predic8.membrane.core.exchange.Exchange in project service-proxy by membrane.

the class LoginInterceptor method handleRequest.

@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    if (loginDialog.isLoginRequest(exc)) {
        loginDialog.handleLoginRequest(exc);
        return Outcome.RETURN;
    }
    Session s = sessionManager.getSession(exc);
    if (s != null && s.isPreAuthorized()) {
        if (tokenProvider == null) {
            s.authorize();
        }
    } else if (s == null || !s.isAuthorized()) {
        return loginDialog.redirectToLogin(exc);
    }
    applyBackendAuthorization(exc, s);
    return super.handleRequest(exc);
}
Also used : Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 58 with Exchange

use of com.predic8.membrane.core.exchange.Exchange in project service-proxy by membrane.

the class LoginInterceptor method handleResponse.

@Override
public Outcome handleResponse(Exchange exc) throws Exception {
    Header header = exc.getResponse().getHeader();
    header.setNoCacheResponseHeaders();
    return super.handleResponse(exc);
}
Also used : Header(com.predic8.membrane.core.http.Header)

Example 59 with Exchange

use of com.predic8.membrane.core.exchange.Exchange in project service-proxy by membrane.

the class AMQuota method setResponseToServiceUnavailable.

private void setResponseToServiceUnavailable(Exchange exc, PolicyQuota pq) {
    // TODO do a better response here
    Header hd = new Header();
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message", "Quota Exceeded");
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }
    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DateTimeFormatter(org.joda.time.format.DateTimeFormatter)

Example 60 with Exchange

use of com.predic8.membrane.core.exchange.Exchange in project service-proxy by membrane.

the class AMRateLimiter method setResponseToServiceUnavailable.

public void setResponseToServiceUnavailable(Exchange exc, PolicyRateLimit prl) throws UnsupportedEncodingException {
    Header hd = new Header();
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC().withLocale(Locale.US);
    hd.add("Date", dateFormatter.print(DateTime.now()));
    hd.add("X-LimitDuration", PeriodFormat.getDefault().print(prl.getInterval().toPeriod()));
    hd.add("X-LimitRequests", Integer.toString(prl.getRequests()));
    String ip = exc.getRemoteAddrIp();
    DateTime availableAgainDateTime = prl.getNextCleanup();
    hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));
    /*StringBuilder bodyString = new StringBuilder();
        DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
        bodyString.append(ip).append(" exceeded the rate limit of ").append(prl.getRequests())
                .append(" requests per ")
                .append(PeriodFormat.getDefault().print(prl.getInterval().toPeriod()))
                .append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));*/
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message", "The rate limit of " + prl.getRequests() + " requests in " + prl.getInterval().getStandardSeconds() + " seconds is exceeded. The next requests can be made at " + dtFormatter.print(availableAgainDateTime));
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }
    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) DateTime(org.joda.time.DateTime)

Aggregations

Exchange (com.predic8.membrane.core.exchange.Exchange)107 Test (org.junit.Test)39 IOException (java.io.IOException)32 Request (com.predic8.membrane.core.http.Request)25 Outcome (com.predic8.membrane.core.interceptor.Outcome)24 Response (com.predic8.membrane.core.http.Response)16 AbstractInterceptor (com.predic8.membrane.core.interceptor.AbstractInterceptor)16 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)16 HttpRouter (com.predic8.membrane.core.HttpRouter)14 Before (org.junit.Before)13 ServiceProxyKey (com.predic8.membrane.core.rules.ServiceProxyKey)12 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)11 Header (com.predic8.membrane.core.http.Header)10 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)10 CacheBuilder (com.google.common.cache.CacheBuilder)9 Rule (com.predic8.membrane.core.rules.Rule)6 URISyntaxException (java.net.URISyntaxException)6 UnknownHostException (java.net.UnknownHostException)6 ArrayList (java.util.ArrayList)6 Session (com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)5