/*
* Copyright (C) butor.com. All rights reserved.
*
* This software is published under the terms of the GNU Library General
* Public License (GNU LGPL), a copy of which has been included with this
* distribution in the LICENSE.txt file.
*/
package org.butor.sso;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
*
* @author asawan
* @date 30-Jan-09
*/
public class SSOHelper {
private static final Logger logger = LoggerFactory.getLogger(SSOHelper.class);
public static String getCookie(HttpServletRequest req_, String cookieName_) {
Cookie cookie = null;
Cookie[] cookies = req_.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if (cookie != null) {
if (cookie.getName().equalsIgnoreCase(cookieName_)) {
return cookie.getValue();
}
}
}
}
return null;
}
public static void setCookie(HttpServletResponse resp_, String name_, String value_, int age_, String path_) {
// set cookie
logger.info(String.format("Set cookie %s=%s with path=%s", name_, value_, path_));
Cookie ssoCookie = new Cookie(name_, value_);
ssoCookie.setMaxAge(age_);
ssoCookie.setPath(path_);
resp_.addCookie(ssoCookie);
}
public static void removeCookie(HttpServletResponse resp_, String name_, String path_) {
// set cookie
logger.info("Destroyed cookie={} with path={}", name_, path_);
Cookie ssoCookie = new Cookie(name_, "");
ssoCookie.setMaxAge(0);
ssoCookie.setPath(path_);
resp_.addCookie(ssoCookie);
}
public static void removeSSOIdCookie() {
// set cookie
logger.info("Destroyed sso cookie");
Cookie ssoCookie = new Cookie(SSOConstants.SSO_SSO_ID, "");
ssoCookie.setMaxAge(0);
ssoCookie.setPath("/");
WebContextFactory.get().getHttpServletResponse().addCookie(ssoCookie);
}
public static String getUserSSOId() {
WebContext webContext = WebContextFactory.get();
String ssoId = null;
HttpServletRequest req = webContext.getHttpServletRequest();
if (req != null) {
HttpSession ss = req.getSession();
if (ss != null) {
ssoId = (String)ss.getAttribute(SSOConstants.SSO_SSO_ID);
if (ssoId != null) {
return ssoId;
}
}
}
return SSOHelper.getCookie( webContext.getHttpServletRequest(), SSOConstants.SSO_SSO_ID);
}
public static void setSSOCookie(String id_, String ssoId_) {
if (ssoId_ == null) {
return;
}
WebContext webContext = WebContextFactory.get();
Cookie ssoCookie = new Cookie(SSOConstants.SSO_SSO_ID, ssoId_);
ssoCookie.setMaxAge(-1); // when browser is closed.
ssoCookie.setPath("/");
webContext.getHttpServletResponse().addCookie(ssoCookie);
HttpServletRequest req = webContext.getHttpServletRequest();
if (req != null) {
HttpSession ss = req.getSession(true);
ss.setAttribute(SSOConstants.SSO_ID, id_);
ss.setAttribute(SSOConstants.SSO_SSO_ID, ssoId_);
}
}
}