@Override public <T> T require(final Class<T> type) { return req.require(type); }
@Override public void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { String error = req.param("error").toOptional().orElse(""); String username = req.param("username").toOptional().orElse(""); req.set("username", username); req.set("error", error); if (loginUrl.equals(req.path())) { // default login form rsp.type(MediaType.html).send(String.format(FORM, error, callback, username)); } else { super.handle(req, rsp, chain); } }
@Override public String getFullRequestURL() { String query = req.queryString().map(it -> "?" + it).orElse(""); return getScheme() + "://" + getServerName() + ":" + getServerPort() + req.contextPath() + req .path() + query; }
private String template(Request req) { String contextPath = req.contextPath(); return "<script>" + "window.LiveReloadOptions = {" + "host: '" + req.hostname() + "'," + "port: '" + req.port() + contextPath + "'" + "};" + "</script>\n" + "<script src=\"" + contextPath + "/livereload.js\"></script>"; }
protected void handshake(final Request req, final Runnable handler) throws Exception { this.injector = req.require(Injector.class); this.renderers = ImmutableList.copyOf(injector.getInstance(Renderer.KEY)); this.produces = req.route().produces(); this.locals = req.attributes(); this.lastEventId = req.header("Last-Event-ID"); this.locale = req.locale(); handshake(handler); }
@SuppressWarnings({"unchecked"}) @Override public void handle(final Request req, final Response rsp) throws Throwable { Clients clients = req.require(Clients.class); String clientName = req.param(clients.getClientNameParameter()).value(this.clientName); WebContext ctx = req.require(WebContext.class); ClientFinder finder = req.require(ClientFinder.class); AuthStore<CommonProfile> store = req.require(AuthStore.class); log.debug("profile: {}", identity); if (identity != null) { req.set(Auth.ID, identity.getId()); req.set(Auth.CNAME, client.getName()); store.set(identity); String queryString = req.queryString().map(it -> "?" + it).orElse(""); final String requestedUrl = req.path() + queryString; log.debug("requestedUrl: {}", requestedUrl); ctx.setSessionAttribute(Pac4jConstants.REQUESTED_URL, requestedUrl);
@Override public void handle(final Request req, final Response rsp) throws Throwable { HealthCheckRegistry registry = req.require(HealthCheckRegistry.class); SortedMap<String, Result> checks = req.param("name").toOptional().map(name -> { SortedMap<String, Result> set = ImmutableSortedMap.of(name, registry.runHealthCheck(name)); return set; }).orElseGet(() -> registry.runHealthChecks()); final Status status; if (checks.isEmpty()) { status = Status.NOT_IMPLEMENTED; } else { status = checks.values().stream() .filter(it -> !it.isHealthy()) .findFirst() .map(it -> Status.SERVER_ERROR) .orElse(Status.OK); } rsp.status(status) .header("Cache-Control", "must-revalidate,no-cache,no-store") .send(checks); }
@Override public void handle(final Request req, final Response rsp, final Err ex) throws Throwable { log.error("execution of: {}{} resulted in exception\nRoute:\n{}\n\nStacktrace:", req.method(), req.path(), req.route().print(6), ex); Config conf = req.require(Config.class); boolean stackstrace = Try.apply(() -> conf.getBoolean("err.stacktrace")) .orElse(req.require(Env.class).name().equals("dev")); rsp.send( Results .when(MediaType.html, () -> Results.html(VIEW).put("err", ex.toMap(stackstrace))) .when(MediaType.all, () -> ex.toMap(stackstrace))); }
Swagger base = Json.mapper().convertValue(hash, Swagger.class); Swagger swagger = new SwaggerBuilder(options.tagger) .build(base, provider.apply(req.require(M))); boolean json = req.path().endsWith(".json"); if (configurer != null) { configurer.accept(swagger); boolean json = req.path().endsWith(".json"); if (json) { return Results.json(Json.mapper().writer().writeValueAsBytes(swagger)); String page = Optional.ofNullable(req.param("theme").value(options.theme)) .map(theme -> index.replace("<style>", "<link rel=\"stylesheet\" " + "type=\"text/css\" href=\"" + fullStaticPath + "theme-" + theme.toLowerCase()
if (req.accepts(MediaType.html).isPresent()) { Route route = req.route(); ImmutableMap.Builder<String, Object> map = ImmutableMap.builder(); return map })); envdata.put("request params", dump(() -> req.params().toMap())); req.ifSession().ifPresent(s -> envdata.put("session", dump(s::attributes))); req.method(), req.path(), req.route().print(6), err); rsp.type(MediaType.html).send(writer.toString());
@SuppressWarnings("unchecked") @Override public void handle(final Request req, final Response rsp) throws Throwable { // DON'T create a session for JWT/param/header auth (a.k.a stateless) Optional<Session> ifSession = req.ifSession(); if (ifSession.isPresent()) { Session session = ifSession.get(); Optional<String> profileId = session.unset(Auth.ID).toOptional(); if (profileId.isPresent()) { Optional<CommonProfile> profile = req.require(AuthStore.class).unset(profileId.get()); log.debug("logout {}", profile); session.destroy(); } } else { log.debug("nothing to logout from session"); } String redirectTo = req.<String> ifGet("auth.logout.redirectTo").orElse(this.redirectTo); rsp.redirect(redirectTo); }
static void install(final Env env, final Config conf) { String path = conf.getString("crash.httpshell.path"); Router router = env.router(); router.get(path + "/{cmd:.*}", router.promise("direct", (req, deferred) -> { MediaType type = req.accepts(MediaType.json) .map(it -> MediaType.json) .orElse(MediaType.html); PluginContext ctx = req.require(PluginContext.class); ShellFactory shellFactory = ctx.getPlugin(ShellFactory.class); Shell shell = shellFactory.create(null); String cmd = req.param("cmd").value().replaceAll("/", " "); ShellProcess process = shell.createProcess(cmd); ShellProcessContext spc = new SimpleProcessContext( result -> deferred.resolve(result.type(type))); process.execute(spc); })); }
long timestamp = req.timestamp(); sb.append(req.ip()); sb.append(SP).append(DASH).append(SP); sb.append(userId.apply(req)); sb.append(BL).append(df.apply(timestamp)).append(BR); sb.append(SP); sb.append(Q).append(req.method()); sb.append(SP); sb.append(req.path()); if (queryString) { req.queryString().ifPresent(s -> sb.append(QUERY).append(s)); sb.append(req.protocol()); sb.append(Q).append(SP); int status = ersp.status().orElse(Status.OK).value(); if (extended) { sb.append(SP); sb.append(Q).append(req.header(REFERER).value(DASH)).append(Q).append(SP); sb.append(Q).append(req.header(USER_AGENT).value(DASH)).append(Q);
@Override public void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { /** * Get or generate a token */ Session session = req.session(); String token = session.get(name).toOptional().orElseGet(() -> { String newToken = generator.apply(req); session.set(name, newToken); return newToken; }); req.set(name, token); if (requireToken.test(req)) { String candidate = req.header(name).toOptional() .orElseGet(() -> req.param(name).toOptional().orElse(null)); if (!token.equals(candidate)) { throw new Err(Status.FORBIDDEN, "Invalid Csrf token: " + candidate); } } chain.next(req, rsp); } }
@Override public Request set(final Key<?> key, final Object value) { req.set(key, value); return this; }
@Override public void handle(final Request req, final Response rsp) throws Throwable { String error = req.param("error").value(""); String username = req.param("username").value(""); req.set("username", username); req.set("error", error); // default login form rsp.type(MediaType.html).send(String.format(FORM, error, callback, username)); }
@Override public void handle(Request req, Response rsp, Route.Chain chain) throws Throwable { try { WebContext context = req.require(WebContext.class); /** 1: don't save authentication urls: */ String existingRequestedUrl = (String) context .getSessionAttribute(Pac4jConstants.REQUESTED_URL); boolean resetRequestedUrl = excludes.stream() .filter(it -> !it.endsWith("/**") && req.matches(it)) .findFirst() .isPresent(); conf.getSecurityLogic() .perform(context, conf, new Pac4jGrantAccessAdapter(req, rsp, chain), conf.getHttpActionAdapter(), clients, authorizers, matchers, multiProfile); /** 2: don't save authentication urls: */ if (resetRequestedUrl && req.ifSession().isPresent()) { // log.info("ignoring {} by {}", ctx.g, existingRequestedUrl); context.setSessionAttribute(Pac4jConstants.REQUESTED_URL, existingRequestedUrl); } } catch (TechnicalException x) { Throwable cause = x.getCause(); if (!(cause instanceof Err)) { // Pac4j wrap everything as TechnicalException, it makes stacktrace ugly, so we rethrow // Err cause = x; } throw cause; } // } }
@Override default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { Sse sse = req.require(Sse.class); String path = req.path(); rsp.send(new Deferred(deferred -> { try { sse.handshake(req, () -> { Try.run(() -> handle(req, sse)) .onSuccess(() -> deferred.resolve(null)) .onFailure(ex -> { deferred.reject(ex); Logger log = LoggerFactory.getLogger(Sse.class); log.error("execution of {} resulted in error", path, ex); }); }); } catch (Exception ex) { deferred.reject(ex); } })); }
@Override public void handle(Request req, Response rsp) { WebContext context = req.require(WebContext.class); String redirectTo = req.<String>ifGet("pac4j.logout.redirectTo").orElse(defaultUrl); conf.getLogoutLogic() .perform(context, conf, conf.getHttpActionAdapter(), redirectTo, logoutUrlPattern, localLogout, destroySession, centralLogout); } }
static Provider profileProvider(AtomicReference<Registry> registry, Class profile, Function<Request, UserProfile> unauthenticated) { return () -> { Request req = registry.get().require(Request.class); ProfileManager pm = req.require(ProfileManager.class); Object result = pm.getAll(req.ifSession().isPresent()).stream() .filter(profile::isInstance) .findFirst() .orElse(null); if (result == null) { if (unauthenticated == null) { throw new Err(Status.FORBIDDEN, "Not found: " + profile.getSimpleName()); } result = unauthenticated.apply(req); } return result; }; } }