Search in sources :

Example 1 with HttpResponse

use of oap.http.HttpResponse in project oap by oaplatform.

the class Login2WS method login.

private HttpResponse login(Optional<Token2> optionalToken) {
    if (optionalToken.isPresent()) {
        final Token2 token = optionalToken.get();
        final HttpResponse ok = HttpResponse.ok(token);
        return withAuthorization(ok, token);
    } else {
        return HttpResponse.status(HTTP_UNAUTHORIZED, "Username or password is invalid");
    }
}
Also used : HttpResponse(oap.http.HttpResponse)

Example 2 with HttpResponse

use of oap.http.HttpResponse in project oap by oaplatform.

the class SecurityInterceptor2 method intercept.

@Override
public Optional<HttpResponse> intercept(Request request, Session session, Reflection.Method method, Function<Reflection.Parameter, Object> getParameterValueFunc) {
    log.trace("intercept method={}, request={}", method, request.requestLine);
    val annotation = method.findAnnotation(WsSecurity2.class).orElse(null);
    if (annotation == null)
        return Optional.empty();
    if (session == null) {
        final HttpResponse httpResponse = HttpResponse.status(500, "Session doesn't exist; check if service is session aware");
        log.error(httpResponse.toString());
        return Optional.of(httpResponse);
    }
    val sessionToken = Interceptor.getSessionToken(request);
    if (sessionToken == null) {
        final HttpResponse httpResponse = HttpResponse.status(401, "Session token is missing in header or cookie");
        log.debug(httpResponse.toString());
        return Optional.of(httpResponse);
    }
    var userId = (String) session.get(USER_ID).orElse(null);
    if (userId == null) {
        val token = tokenService.getToken(sessionToken).orElse(null);
        if (token == null) {
            final HttpResponse httpResponse = HttpResponse.status(401, format("Token id [%s] expired or was " + "not created", sessionToken));
            log.debug(httpResponse.toString());
            return Optional.of(httpResponse);
        }
        userId = token.userId;
        session.set(USER_ID, userId);
    } else {
        log.trace("User [{}] found in session", userId);
    }
    if (!annotation.object().isEmpty() && !annotation.permission().isEmpty()) {
        val objectId = getObjectId(method, annotation, getParameterValueFunc);
        if (!aclService.checkOne(objectId, userId, annotation.permission())) {
            val httpResponse = HttpResponse.status(403, String.format("User [%s] has no access to method [%s]", userId, method.name()));
            log.debug(httpResponse.toString());
            return Optional.of(httpResponse);
        }
    }
    return Optional.empty();
}
Also used : lombok.val(lombok.val) lombok.experimental.var(lombok.experimental.var) HttpResponse(oap.http.HttpResponse)

Example 3 with HttpResponse

use of oap.http.HttpResponse in project oap by oaplatform.

the class CatApiTest method testTable.

@Test
public void testTable() throws Exception {
    final HttpResponse table = table(Lists.of("1", "test23"), Lists.of("bbbb", "2"));
    assertString(Strings.readString(table.contentEntity.getContent())).isEqualTo("1    test23\n" + "bbbb 2     \n");
}
Also used : HttpResponse(oap.http.HttpResponse) Test(org.testng.annotations.Test) AbstractTest(oap.testng.AbstractTest)

Example 4 with HttpResponse

use of oap.http.HttpResponse in project oap by oaplatform.

the class WsService method handleInternal.

private void handleInternal(Request request, Response response, Reflection.Method method, Name name, Pair<String, Session> session) {
    log.trace("{}: Internal session status: [{}]", service(), session);
    Optional<WsMethod> wsMethod = method.findAnnotation(WsMethod.class);
    Function<Reflection.Parameter, Object> func = (p) -> {
        val ret = getValue(session, request, wsMethod, p).orElse(Optional.empty());
        if (ret instanceof Optional)
            return ((Optional<?>) ret).orElse(null);
        return ret;
    };
    HttpResponse interceptorResponse = session != null ? runInterceptors(request, session._2, method, func) : null;
    if (interceptorResponse != null) {
        response.respond(interceptorResponse);
    } else {
        Metrics.measureTimer(name, () -> {
            List<Reflection.Parameter> parameters = method.parameters;
            LinkedHashMap<Reflection.Parameter, Object> originalValues = getOriginalValues(session, parameters, request, wsMethod);
            ValidationErrors paramValidation = ValidationErrors.empty();
            originalValues.forEach((parameter, value) -> paramValidation.merge(Validators.forParameter(method, parameter, impl, true).validate(value, originalValues)));
            paramValidation.throwIfInvalid();
            Validators.forMethod(method, impl, true).validate(originalValues.values().toArray(new Object[originalValues.size()]), originalValues).throwIfInvalid();
            LinkedHashMap<Reflection.Parameter, Object> values = getValues(originalValues);
            Object[] paramValues = values.values().toArray(new Object[values.size()]);
            values.forEach((parameter, value) -> paramValidation.merge(Validators.forParameter(method, parameter, impl, false).validate(value, values)));
            paramValidation.throwIfInvalid();
            Validators.forMethod(method, impl, false).validate(paramValues, values).throwIfInvalid();
            Object result = method.invoke(impl, paramValues);
            Boolean isRaw = wsMethod.map(WsMethod::raw).orElse(false);
            ContentType produces = wsMethod.map(wsm -> ContentType.create(wsm.produces()).withCharset(UTF_8)).orElse(APPLICATION_JSON);
            String cookie = session != null ? new HttpResponse.CookieBuilder().withSID(session._1).withPath(sessionManager.cookiePath).withExpires(DateTime.now().plusMinutes(sessionManager.cookieExpiration)).withDomain(sessionManager.cookieDomain).withDomain(sessionManager.cookieDomain).build() : null;
            if (method.isVoid())
                response.respond(NO_CONTENT);
            else if (result instanceof HttpResponse)
                response.respond(((HttpResponse) result).withCookie(cookie));
            else if (result instanceof Optional<?>) {
                response.respond(((Optional<?>) result).map(r -> HttpResponse.ok(runPostInterceptors(r, session, method), isRaw, produces).withCookie(cookie)).orElse(NOT_FOUND));
            } else if (result instanceof Result<?, ?>) {
                Result<HttpResponse, HttpResponse> resp = ((Result<?, ?>) result).mapSuccess(r -> HttpResponse.ok(r, isRaw, produces).withCookie(cookie)).mapFailure(r -> HttpResponse.status(HTTP_INTERNAL_ERROR, "", r).withCookie(cookie));
                response.respond(resp.isSuccess() ? ((Result<?, ?>) result).mapSuccess(r -> HttpResponse.ok(runPostInterceptors(r, session, method), isRaw, produces).withCookie(cookie)).successValue : ((Result<?, ?>) result).mapFailure(r -> HttpResponse.status(HTTP_INTERNAL_ERROR, "", r).withCookie(cookie)).failureValue);
            } else if (result instanceof Stream<?>) {
                response.respond(HttpResponse.stream(((Stream<?>) result).map(v -> runPostInterceptors(v, session, method)), isRaw, produces).withCookie(cookie));
            } else
                response.respond(HttpResponse.ok(runPostInterceptors(result, session, method), isRaw, produces).withCookie(cookie));
        });
    }
}
Also used : Pair(oap.util.Pair) Result(oap.util.Result) Binder(oap.json.Binder) Metrics(oap.metrics.Metrics) NOT_FOUND(oap.http.HttpResponse.NOT_FOUND) Reflection(oap.reflect.Reflection) Pair.__(oap.util.Pair.__) HashMap(java.util.HashMap) Strings(oap.util.Strings) Function(java.util.function.Function) NO_CONTENT(oap.http.HttpResponse.NO_CONTENT) Reflect(oap.reflect.Reflect) LinkedHashMap(java.util.LinkedHashMap) HTTP_INTERNAL_ERROR(java.net.HttpURLConnection.HTTP_INTERNAL_ERROR) Map(java.util.Map) Session(oap.http.Session) TEXT_PLAIN(oap.http.ContentTypes.TEXT_PLAIN) Stream(oap.util.Stream) ReflectException(oap.reflect.ReflectException) APPLICATION_JSON(org.apache.http.entity.ContentType.APPLICATION_JSON) Name(oap.metrics.Name) Collectors.toLinkedHashMap(oap.util.Collectors.toLinkedHashMap) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Handler(oap.http.Handler) Collection(java.util.Collection) lombok.val(lombok.val) ContentType(org.apache.http.entity.ContentType) DateTime(org.joda.time.DateTime) Response(oap.http.Response) JsonException(oap.json.JsonException) UUID(java.util.UUID) Request(oap.http.Request) TEXT(oap.ws.WsResponse.TEXT) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) Validators(oap.ws.validate.Validators) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) WrappingRuntimeException(oap.util.WrappingRuntimeException) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Throwables(oap.util.Throwables) HttpResponse(oap.http.HttpResponse) ValidationErrors(oap.ws.validate.ValidationErrors) lombok.val(lombok.val) Optional(java.util.Optional) ContentType(org.apache.http.entity.ContentType) ValidationErrors(oap.ws.validate.ValidationErrors) HttpResponse(oap.http.HttpResponse) Result(oap.util.Result) Stream(oap.util.Stream)

Example 5 with HttpResponse

use of oap.http.HttpResponse in project oap by oaplatform.

the class SecurityInterceptorTest method testShouldVerifyUserIfPresentInSession.

@Test
public void testShouldVerifyUserIfPresentInSession() {
    final Reflection.Method methodWithAnnotation = REFLECTION.method(method -> method.name().equals("methodWithAnnotation")).get();
    final User user = new DefaultUser(Role.ADMIN, "org", "test@test.com");
    final Session session = new Session();
    session.set("user", user);
    final Optional<HttpResponse> httpResponse = securityInterceptor.intercept(null, session, methodWithAnnotation, (p) -> null);
    assertFalse(httpResponse.isPresent());
}
Also used : Context(oap.http.Context) Reflection(oap.reflect.Reflection) DateTime(org.joda.time.DateTime) Test(org.testng.annotations.Test) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Assert.assertNotNull(org.testng.Assert.assertNotNull) HttpRequest(org.apache.http.HttpRequest) UnknownHostException(java.net.UnknownHostException) Request(oap.http.Request) Reflect(oap.reflect.Reflect) InetAddress(java.net.InetAddress) HttpGet(org.apache.http.client.methods.HttpGet) Session(oap.http.Session) Optional(java.util.Optional) Protocol(oap.http.Protocol) Assert.assertFalse(org.testng.Assert.assertFalse) HttpResponse(oap.http.HttpResponse) Mockito.mock(org.mockito.Mockito.mock) HttpResponse(oap.http.HttpResponse) Reflection(oap.reflect.Reflection) Session(oap.http.Session) Test(org.testng.annotations.Test)

Aggregations

HttpResponse (oap.http.HttpResponse)8 Optional (java.util.Optional)3 UUID (java.util.UUID)3 Request (oap.http.Request)3 Session (oap.http.Session)3 Reflect (oap.reflect.Reflect)3 Reflection (oap.reflect.Reflection)3 DateTime (org.joda.time.DateTime)3 Test (org.testng.annotations.Test)3 InetAddress (java.net.InetAddress)2 UnknownHostException (java.net.UnknownHostException)2 lombok.val (lombok.val)2 Context (oap.http.Context)2 Protocol (oap.http.Protocol)2 HttpRequest (org.apache.http.HttpRequest)2 HttpGet (org.apache.http.client.methods.HttpGet)2 Mockito.mock (org.mockito.Mockito.mock)2 Mockito.when (org.mockito.Mockito.when)2 Assert.assertFalse (org.testng.Assert.assertFalse)2 Assert.assertNotNull (org.testng.Assert.assertNotNull)2