Java tutorial
/* * This file is a component of thundr, a software library from 3wks. * Read more: http://www.3wks.com.au/thundr * Copyright (C) 2015 3wks, <thundr@3wks.com.au> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.threewks.thundr.session; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.joda.time.Duration; import com.threewks.thundr.configuration.Environment; import com.threewks.thundr.http.Cookie; import com.threewks.thundr.request.Request; import com.threewks.thundr.request.Response; public class CookieSessionStore implements SessionStore { public static final String CookieName = "__userAuth"; public static final Duration CookieDuration = Duration.standardDays(60); protected Request req; protected Response resp; protected String cookieName; protected Duration cookieDuration; public CookieSessionStore(Request request, Response response) { this(request, response, CookieName, CookieDuration); } public CookieSessionStore(Request req, Response resp, String cookieName, Duration duration) { super(); this.req = req; this.resp = resp; this.cookieName = cookieName; this.cookieDuration = duration; } @Override public String get() { if (req == null) { return null; } if (!req.isSecure() && requiresHttps()) { return null; } Cookie cookie = req.getCookie(cookieName); return cookie == null ? null : cookie.getValue(); } @Override public void put(String sessionId) { resp.withCookie(cookie(cookieName, sessionId, cookieDuration)); } @Override public void clear() { resp.withCookie(cookie(cookieName, "", Duration.ZERO)); } protected Cookie cookie(String name, String value, Duration duration) { boolean secure = requiresHttps(); // @formatter:off return Cookie.build(name).withValue(value).withSecure(secure).withMaxAge(duration).withPath("/").build(); // @formatter:on } protected boolean requiresHttps() { return !Environment.is(Environment.DEV); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj, true); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, true); } }