use of oap.http.Session in project oap by oaplatform.
the class WsService method handle.
@Override
public void handle(Request request, Response response) {
try {
val method = reflection.method(m -> methodMatches(request.requestLine, request.httpMethod, m), (o1, o2) -> {
val path1 = o1.findAnnotation(WsMethod.class).map(WsMethod::path).orElse(o1.name());
val path2 = o2.findAnnotation(WsMethod.class).map(WsMethod::path).orElse(o1.name());
return path1.compareTo(path2);
}).orElse(null);
if (method == null)
response.respond(NOT_FOUND);
else {
Name name = Metrics.name("rest_timer").tag("service", service()).tag("method", method.name());
if (!sessionAware) {
handleInternal(request, response, method, name, null);
} else {
String cookieId = request.cookie(SessionManager.COOKIE_ID).orElse(null);
val authToken = Interceptor.getSessionToken(request);
Session session;
if (cookieId != null && (session = sessionManager.getSessionById(cookieId)) != null && Objects.equals(authToken, session.get(Interceptor.AUTHORIZATION).orElse(null))) {
log.debug("{}: Valid SID [{}] found in cookie", service(), cookieId);
handleInternal(request, response, method, name, __(cookieId, session));
} else {
cookieId = UUID.randomUUID().toString();
log.debug("{}: Creating new session with SID [{}]", service(), cookieId);
session = new Session();
if (authToken != null)
session.set(Interceptor.AUTHORIZATION, authToken);
sessionManager.put(cookieId, session);
handleInternal(request, response, method, name, __(cookieId, session));
}
}
}
} catch (Throwable e) {
wsError(response, e);
}
}
use of oap.http.Session 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));
});
}
}
use of oap.http.Session in project oap by oaplatform.
the class WsServiceSessionTest method testUSER_ID.
@Test
public void testUSER_ID() {
final Session session = new Session();
session.set(Interceptor.USER_ID, "user_id");
session.set(Interceptor.AUTHORIZATION, "987654321");
sessionManager.put("123456", session);
assertGet(HttpAsserts.HTTP_URL("/test/2"), Maps.empty(), Maps.of(__("Cookie", "Authorization=987654321; SID=123456"))).hasCode(200).hasBody(Binder.json.marshal("user_id"));
}
use of oap.http.Session 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());
}
use of oap.http.Session in project oap by oaplatform.
the class SecurityInterceptorTest method testShouldVerifyAndSetUserInSessionIfAuthorizationHeaderIsPresent.
@Test
public void testShouldVerifyAndSetUserInSessionIfAuthorizationHeaderIsPresent() throws UnknownHostException {
final Reflection.Method methodWithAnnotation = REFLECTION.method(method -> method.name().equals("methodWithAnnotation")).get();
final Context context = new Context("/", InetAddress.getLocalHost(), Protocol.HTTP.name());
final String tokenId = UUID.randomUUID().toString();
final HttpRequest httpRequest = new HttpGet();
httpRequest.setHeader("Authorization", tokenId);
httpRequest.setHeader("Host", "localhost");
final Request request = new Request(httpRequest, context);
final User user = new DefaultUser(Role.ADMIN, "testOrg", "test@example.com");
final Token token = new Token();
token.user = new DefaultUser(user);
token.id = tokenId;
token.created = DateTime.now();
when(mockTokenService.getToken(tokenId)).thenReturn(Optional.of(token));
final Session session = new Session();
final Optional<HttpResponse> httpResponse = securityInterceptor.intercept(request, session, methodWithAnnotation, p -> null);
assertFalse(httpResponse.isPresent());
assertNotNull(session.get("user"));
}
Aggregations