Search in sources :

Example 1 with Handler

use of suite.http.Http.Handler in project suite by stupidsing.

the class HttpHandleSessionAuth method getHandler.

public Handler getHandler(BiPredicate<String, String> authenticate, Handler protectedHandler) {
    return new Handler() {

        public Response handle(Request request) {
            var current = System.currentTimeMillis();
            var sessionIdOpt = // 
            request.headers.getOpt(// 
            "Cookie").map(cookie -> HttpHeaderUtil.getCookieAttrs(cookie).get("session"));
            var session = sessionIdOpt.map(sm::get).or(null);
            Response response;
            if (Equals.ab(request.paths, PerList.of("login"))) {
                var attrs = HttpHeaderUtil.getPostedAttrs(request.in);
                var username = attrs.get("username");
                var password = attrs.get("password");
                var paths = HttpHeaderUtil.getPaths(attrs.get("path"));
                if (authenticate.test(username, password)) {
                    var sessionId = getRandomSessionId();
                    sm.put(sessionId, session = new Session(username, current));
                    var request1 = new // 
                    Request(// 
                    request.method, // 
                    request.server, // 
                    paths, // 
                    request.query, // 
                    request.headers, request.in);
                    response = showProtectedPage(request1, sessionId);
                } else
                    response = showLoginPage(paths, true);
            } else if (Equals.ab(request.paths, PerList.of("logout"))) {
                sessionIdOpt.sink(sm::remove);
                response = showLoginPage(PerList.end(), false);
            } else if (session != null && current < session.lastRequestDt.value() + timeoutDuration) {
                session.lastRequestDt.update(current);
                response = showProtectedPage(request, sessionIdOpt.g());
            } else
                response = showLoginPage(request.paths, false);
            return response;
        }

        private Response showProtectedPage(Request request, String sessionId) {
            var r = protectedHandler.handle(request);
            var headers1 = r.headers.put("Set-Cookie", "session=" + sessionId + "; Path=/site");
            return new Response(r.status, headers1, r.body);
        }

        private Response showLoginPage(PerList<String> redirectPath, boolean isLoginFailed) {
            var redirectPath1 = redirectPath.streamlet().map(p -> "/" + p).toJoinedString();
            return Response.of(Pull.from(// 
            "<html>" + // 
            "<head><title>Login</title></head>" + // 
            "<body>" + // 
            "<font face=\"Monospac821 BT,Monaco,Consolas\">" + // 
            (isLoginFailed ? "<b>LOGIN FAILED</b><p/>" : "") + // 
            "<form name=\"login\" action=\"login\" method=\"post\">" + // 
            "Username <input type=\"text\" name=\"username\" autofocus /><br/>" + // 
            "Password <input type=\"password\" name=\"password\" /><br/>" + "<input type=\"hidden\" name=\"path\" value=\"" + htmlUtil.encode(redirectPath1) + // 
            "\" />" + // 
            "<input type=\"submit\" value=\"Login\">" + // 
            "</form>" + // 
            "</font>" + // 
            "</body>" + "</html>"));
        }

        private String getRandomSessionId() {
            var bytes = new byte[16];
            random.nextBytes(bytes);
            return Build.string(sb -> {
                for (var b : bytes) sb.append(String.format("%02x", b));
            });
        }
    };
}
Also used : Response(suite.http.Http.Response) Build(primal.Verbs.Build) Random(java.util.Random) Session(suite.http.Http.Session) SecureRandom(java.security.SecureRandom) BiPredicate(java.util.function.BiPredicate) Response(suite.http.Http.Response) Request(suite.http.Http.Request) SessionManager(suite.http.Http.SessionManager) Pull(primal.MoreVerbs.Pull) Equals(primal.Verbs.Equals) PerList(primal.persistent.PerList) Handler(suite.http.Http.Handler) HtmlUtil(suite.util.HtmlUtil) Request(suite.http.Http.Request) Handler(suite.http.Http.Handler) PerList(primal.persistent.PerList) Session(suite.http.Http.Session)

Example 2 with Handler

use of suite.http.Http.Handler in project suite by stupidsing.

the class HttpHandle method serveDir.

public Handler serveDir(Path root) {
    return request -> ex(() -> {
        var path = root;
        long size;
        for (var p : request.paths) if (!Equals.string(p, ".."))
            path = path.resolve(p);
        var file = path.toFile();
        if (file.exists())
            try (var raf = new RandomAccessFile(file, "r")) {
                size = raf.getChannel().size();
                var array = // 
                request.headers.getOpt(// 
                "Range").map(// 
                range -> range.split(",")).filter(// 
                ranges -> ranges.length == 1).map(// 
                ranges -> ranges[0].split("-")).or(new String[0]);
                if (array.length == 2) {
                    var a0 = array[0];
                    var a1 = array[1];
                    var p0 = max(!a1.isEmpty() ? Long.valueOf(a0) : Long.MIN_VALUE, 0);
                    var px = min(!a1.isEmpty() ? Long.valueOf(a1) : Long.MAX_VALUE, size);
                    var p = LngMutable.of(p0);
                    var empty = // 
                    new Header().put("Content-Range", // 
                    "bytes " + p0 + "-" + px + "/" + size).put("Content-Type", "text/html; charset=UTF-8");
                    return Response.of(Http.S206, empty, Pull.from(new InputStream() {

                        public int read() throws IOException {
                            var pos = p.value();
                            if (pos != px) {
                                raf.seek(p.increment());
                                p.update(pos + 1);
                                return raf.read();
                            } else
                                return -1;
                        }

                        public int read(byte[] b, int off, int len0) throws IOException {
                            var pos = p.value();
                            if (pos != px) {
                                var len1 = min(len0, (int) (px - pos));
                                raf.seek(pos);
                                var n = raf.read(b, off, len1);
                                p.update(pos + n);
                                return n;
                            } else
                                return -1;
                        }
                    }));
                } else
                    return Response.of(Http.S200, Pull.from(Files.newInputStream(path)), size);
            }
        else
            return Http.R404;
    });
}
Also used : PerMap(primal.persistent.PerMap) RandomAccessFile(java.io.RandomAccessFile) Files(java.nio.file.Files) IOException(java.io.IOException) Math.min(java.lang.Math.min) Header(suite.http.Http.Header) Sink(primal.fp.Funs.Sink) Bytes(primal.primitive.adt.Bytes) Response(suite.http.Http.Response) Rethrow.ex(primal.statics.Rethrow.ex) Math.max(java.lang.Math.max) Pull(primal.MoreVerbs.Pull) LngMutable(primal.primitive.adt.LngMutable) Equals(primal.Verbs.Equals) Path(java.nio.file.Path) PerList(primal.persistent.PerList) Handler(suite.http.Http.Handler) InputStream(java.io.InputStream) RandomAccessFile(java.io.RandomAccessFile) Header(suite.http.Http.Header) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 3 with Handler

use of suite.http.Http.Handler in project suite by stupidsing.

the class ServerMain method handler.

private Handler handler() {
    BiPredicate<String, String> authenticate = (username, password) -> // 
    Defaults.secrets().prove(Suite.substitute("auth .0 .1", new Str(username), new Str(password)));
    Fun2<String, String, List<String>> authenticateRoles = (username, password) -> {
        return authenticate.test(username, password) ? List.of("role") : null;
    };
    var sseHeaders = new Header(// 
    PerMap.<String, PerList<String>>empty().put("Cache-Control", // 
    PerList.of("no-cache")).put("Content-Type", PerList.of("text/event-stream")));
    Handler handlerDump = request -> Response.of(Pull.from(// 
    "" + // 
    "<html>" + "<br/>method = " + // 
    request.method + "<br/>server = " + // 
    request.server + "<br/>paths = " + // 
    request.paths + "<br/>attrs = " + // 
    HttpHeaderUtil.getAttrs(request.query) + "<br/>headers = " + // 
    request.headers + "</html>"));
    Handler handlerSse = request -> Response.ofWriter(Http.S200, sseHeaders, write -> {
        new Object() {

            private int i = 8;

            private void dispatch() {
                sleep.sink2(1000l, () -> {
                    if (0 < i--) {
                        var event = "event: number\ndata: { \"i\": " + i + " }\n\n";
                        write.f(Bytes.of(event.getBytes(Utf8.charset)));
                        dispatch();
                    } else
                        write.f(null);
                });
            }
        }.dispatch();
    });
    Handler handlerStatus = request -> {
        var cfg = new TradeCfgImpl();
        var summarize = Summarize.of(cfg);
        var sbs = summarize.summarize(trade -> trade.strategy);
        return Response.of(Pull.from("<pre>" + sbs.log + new TreeMap<>(sbs.pnlByKey) + "</pre>"));
    };
    var hh = new HttpHandle();
    var hhsa = new HttpHandleSessionAuth();
    var hhta = new HttpHandleTokenAuth();
    return hh.routeByPath(// 
    PerMap.<String, Handler>empty().put("api", // 
    hhta.applyFilter("role", hh.serveText("in good shape"))).put("hello", // 
    hh.serveText("hello world")).put("html", // 
    hh.serveDir(Paths.get(FileUtil.suiteDir() + "/src/main/html"))).put("path", // 
    hh.serveDir(Tmp.root)).put("site", // 
    hhsa.getHandler(authenticate, handlerDump)).put("sse", // 
    handlerSse).put("status", // 
    handlerStatus).put("token", hh.routeByMethod(// 
    PerMap.<String, Handler>empty().put("PATCH", // 
    hhta.refreshToken(authenticateRoles)).put("POST", hhta.getToken(authenticateRoles)))));
}
Also used : Schedule(suite.os.Schedule) Sink2(primal.fp.Funs2.Sink2) LocalDateTime(java.time.LocalDateTime) Scheduler(suite.os.Scheduler) RunUtil(suite.util.RunUtil) ArrayList(java.util.ArrayList) Defaults(suite.cfg.Defaults) BiPredicate(java.util.function.BiPredicate) Http(suite.http.Http) Response(suite.http.Http.Response) SmtpServer(suite.smtp.SmtpServer) Utf8(primal.Nouns.Utf8) LocalTime(java.time.LocalTime) FileUtil(suite.os.FileUtil) Pull(primal.MoreVerbs.Pull) HttpServe(suite.http.HttpServe) Sleep(primal.Verbs.Sleep) Handler(suite.http.Http.Handler) TelegramBotMain(suite.sample.TelegramBotMain) PerMap(primal.persistent.PerMap) TradeCfgImpl(suite.trade.data.TradeCfgImpl) Files(java.nio.file.Files) HttpNio(suite.http.HttpNio) HttpHandleSessionAuth(suite.http.HttpHandleSessionAuth) Summarize(suite.trade.analysis.Summarize) HttpHandle(suite.http.HttpHandle) Start(primal.Verbs.Start) HttpHeaderUtil(suite.http.HttpHeaderUtil) Header(suite.http.Http.Header) Bytes(primal.primitive.adt.Bytes) List(java.util.List) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) HttpHandleTokenAuth(suite.http.HttpHandleTokenAuth) Fun2(primal.fp.Funs2.Fun2) PerList(primal.persistent.PerList) Str(suite.node.Str) Tmp(primal.Nouns.Tmp) HttpHandle(suite.http.HttpHandle) TradeCfgImpl(suite.trade.data.TradeCfgImpl) Handler(suite.http.Http.Handler) Str(suite.node.Str) HttpHandleSessionAuth(suite.http.HttpHandleSessionAuth) Header(suite.http.Http.Header) ArrayList(java.util.ArrayList) List(java.util.List) PerList(primal.persistent.PerList) HttpHandleTokenAuth(suite.http.HttpHandleTokenAuth)

Aggregations

Pull (primal.MoreVerbs.Pull)3 PerList (primal.persistent.PerList)3 Handler (suite.http.Http.Handler)3 Response (suite.http.Http.Response)3 Files (java.nio.file.Files)2 BiPredicate (java.util.function.BiPredicate)2 Equals (primal.Verbs.Equals)2 PerMap (primal.persistent.PerMap)2 Bytes (primal.primitive.adt.Bytes)2 Header (suite.http.Http.Header)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 RandomAccessFile (java.io.RandomAccessFile)1 Math.max (java.lang.Math.max)1 Math.min (java.lang.Math.min)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 SecureRandom (java.security.SecureRandom)1 LocalDateTime (java.time.LocalDateTime)1 LocalTime (java.time.LocalTime)1