Search in sources :

Example 1 with Cookie

use of com.blade.mvc.http.Cookie in project tale by otale.

the class TaleUtils method setCookie.

/**
 * 设置记住密码 cookie
 */
public static void setCookie(RouteContext context, Integer uid) {
    boolean isSSL = Commons.site_url().startsWith("https");
    String token = EncryptKit.md5(UUID.UU64());
    RememberMe rememberMe = new RememberMe();
    rememberMe.setUid(uid);
    rememberMe.setExpires(DateKit.nowUnix() + ONE_MONTH);
    rememberMe.setRecentIp(Collections.singletonList(context.address()));
    rememberMe.setToken(token);
    long count = select().from(Options.class).where(Options::getName, OPTION_SAFE_REMEMBER_ME).count();
    if (count == 0) {
        Options options = new Options();
        options.setName(OPTION_SAFE_REMEMBER_ME);
        options.setValue(JsonKit.toString(rememberMe));
        options.setDescription("记住我 Token");
        options.save();
    } else {
        update().from(Options.class).set(Options::getValue, JsonKit.toString(rememberMe)).where(Options::getName, OPTION_SAFE_REMEMBER_ME).execute();
    }
    Cookie cookie = new Cookie();
    cookie.name(REMEMBER_IN_COOKIE);
    cookie.value(token);
    cookie.httpOnly(true);
    cookie.secure(isSSL);
    cookie.maxAge(ONE_MONTH);
    cookie.path("/");
    context.response().cookie(cookie);
}
Also used : Cookie(com.blade.mvc.http.Cookie) Options(com.tale.model.entity.Options) RememberMe(com.tale.model.dto.RememberMe)

Example 2 with Cookie

use of com.blade.mvc.http.Cookie in project blade by biezhi.

the class RouteMethodHandler method handleResponse.

public FullHttpResponse handleResponse(Request request, Response response, ChannelHandlerContext context) {
    Session session = request.session();
    if (null != session) {
        Cookie cookie = new Cookie();
        cookie.name(WebContext.sessionKey());
        cookie.value(session.id());
        cookie.httpOnly(true);
        cookie.secure(request.isSecure());
        response.cookie(cookie);
    }
    FullHttpResponse fullHttpResponse = response.body().write(new BodyWriter() {

        @Override
        public FullHttpResponse onByteBuf(ByteBuf byteBuf) {
            return createResponseByByteBuf(response, byteBuf);
        }

        @Override
        public FullHttpResponse onStream(Closeable closeable) {
            // TODO
            return null;
        }

        @Override
        public FullHttpResponse onView(ViewBody body) {
            try {
                var sw = new StringWriter();
                WebContext.blade().templateEngine().render(body.modelAndView(), sw);
                WebContext.response().contentType(Const.CONTENT_TYPE_HTML);
                return this.onByteBuf(Unpooled.copiedBuffer(sw.toString().getBytes(StandardCharsets.UTF_8)));
            } catch (Exception e) {
                log.error("Render view error", e);
            }
            return null;
        }

        @Override
        public FullHttpResponse onRawBody(RawBody body) {
            return body.httpResponse();
        }

        @Override
        public FullHttpResponse onByteBuf(Object byteBuf) {
            var httpResponse = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(response.statusCode()));
            for (Map.Entry<String, String> next : response.headers().entrySet()) {
                httpResponse.headers().set(next.getKey(), next.getValue());
            }
            // Write the initial line and the header.
            if (request.keepAlive()) {
                httpResponse.headers().set(HttpConst.CONNECTION, KEEP_ALIVE);
            }
            context.write(httpResponse, context.voidPromise());
            ChannelFuture lastContentFuture = context.writeAndFlush(byteBuf);
            if (!request.keepAlive()) {
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
            return null;
        }
    });
    if (request.keepAlive()) {
        fullHttpResponse.headers().set(HttpConst.CONNECTION, KEEP_ALIVE);
    }
    return fullHttpResponse;
}
Also used : Cookie(com.blade.mvc.http.Cookie) ChannelFuture(io.netty.channel.ChannelFuture) lombok.var(lombok.var) Closeable(java.io.Closeable) ByteBuf(io.netty.buffer.ByteBuf) NotFoundException(com.blade.exception.NotFoundException) InternalErrorException(com.blade.exception.InternalErrorException) BladeException(com.blade.exception.BladeException) StringWriter(java.io.StringWriter)

Example 3 with Cookie

use of com.blade.mvc.http.Cookie in project blade by biezhi.

the class HttpRequestTest method testCookie.

@Test
public void testCookie() {
    Map<String, Cookie> cookieMap = new HashMap<>();
    Cookie c1 = new Cookie();
    c1.name("c1");
    c1.value("hello1");
    cookieMap.put("c1", c1);
    Cookie c2 = new Cookie();
    c2.name("c1");
    c2.value("hello1");
    c2.httpOnly(true);
    cookieMap.put("c2", c2);
    Cookie c3 = new Cookie();
    c3.name("c3");
    c3.value("hello3");
    c3.secure(false);
    cookieMap.put("c3", c3);
    Cookie c4 = new Cookie();
    c4.name("c4");
    c4.value("hello4");
    c4.domain("www.github.com");
    c4.path("/github");
    cookieMap.put("c4", c4);
    HttpRequest request = mockHttpRequest("GET");
    when(request.cookies()).thenReturn(cookieMap);
    when(request.cookie("c1")).thenReturn(cookieMap.get("c1").value());
    when(request.cookieRaw("c2")).thenReturn(cookieMap.get("c2"));
    when(request.cookieRaw("c3")).thenReturn(cookieMap.get("c3"));
    when(request.cookieRaw("c4")).thenReturn(cookieMap.get("c4"));
    Assert.assertEquals(request.cookies(), cookieMap);
    Assert.assertEquals(request.cookies().size(), cookieMap.size());
    Assert.assertEquals(request.cookie("c1"), "hello1");
    Assert.assertTrue(request.cookieRaw("c2").httpOnly());
    Assert.assertFalse(request.cookieRaw("c3").secure());
    Assert.assertEquals(request.cookieRaw("c3").path(), "/");
    Assert.assertEquals(request.cookieRaw("c4").domain(), "www.github.com");
    Assert.assertEquals(request.cookieRaw("c4").path(), "/github");
}
Also used : Cookie(com.blade.mvc.http.Cookie) HttpRequest(com.blade.mvc.http.HttpRequest) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.blade.kit.CaseInsensitiveHashMap) Test(org.junit.Test)

Aggregations

Cookie (com.blade.mvc.http.Cookie)3 BladeException (com.blade.exception.BladeException)1 InternalErrorException (com.blade.exception.InternalErrorException)1 NotFoundException (com.blade.exception.NotFoundException)1 CaseInsensitiveHashMap (com.blade.kit.CaseInsensitiveHashMap)1 HttpRequest (com.blade.mvc.http.HttpRequest)1 RememberMe (com.tale.model.dto.RememberMe)1 Options (com.tale.model.entity.Options)1 ByteBuf (io.netty.buffer.ByteBuf)1 ChannelFuture (io.netty.channel.ChannelFuture)1 Closeable (java.io.Closeable)1 StringWriter (java.io.StringWriter)1 HashMap (java.util.HashMap)1 lombok.var (lombok.var)1 Test (org.junit.Test)1