Subversion Repositories SmartDukaan

Rev

Rev 2907 | Rev 2973 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.interceptors;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.shop2020.serving.services.UserSessionInfo;
import in.shop2020.serving.utils.DesEncrypter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;

public class UserInterceptor extends AbstractInterceptor implements PreResultListener{

        public static final int SECONDS_IN_YEAR = 60*60*24*365; 
        
        private static final long serialVersionUID = -4125815700236506235L;
        private static Logger log = Logger.getLogger(UserInterceptor.class);
        
        public static final String USER_INFO_COOKIE_NAME = "uic";
        public static final String USER_ID_COOKIE_NAME = "uid";
        
        private Map<String, Cookie> cookiesMap = null;
        private Cookie userCookie = null;
        public static DesEncrypter desEncrypter = new DesEncrypter("shop2020");
        
        private Cookie userinfoCookie = null;
        
        private String cookieDomain = "";
        
        public void setCookieDomain(String cookieDomain) {
                this.cookieDomain = cookieDomain;
        }
        
        @Override
        public String intercept(ActionInvocation invocation) throws Exception {
                final Object action = invocation.getAction();
        
                log.debug("inside user intercepror");
                
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession(); // Get the existing session or create a new one
        
        
                createCookiesMap(request);
                
                UserSessionInfo userInfo = (UserSessionInfo) request.getAttribute(USER_INFO_COOKIE_NAME);

                userCookie = cookiesMap.get(UserInterceptor.USER_ID_COOKIE_NAME);
                userinfoCookie = cookiesMap.get(USER_INFO_COOKIE_NAME);
                
                if(userInfo == null ){
                        if(userinfoCookie!=null){
                                userInfo = UserSessionInfo.getUserSessionInfoFromCookieValue(userinfoCookie.getValue());
                        }else{
                                userInfo = createAndGetSessionFromUIDCookie(session);
                        }
                }
                        
                request.setAttribute(USER_INFO_COOKIE_NAME, userInfo);
                
                
                if (action instanceof UserAware) {
                UserAware sessionAction = (UserAware) action;
                sessionAction.setSession(session);
                sessionAction.setUserSessionInfo(userInfo);
                sessionAction.setCookiesMap(cookiesMap);
                sessionAction.setUserCookie(userCookie);
                sessionAction.setCookieDomainName(cookieDomain);
        }
                
                invocation.addPreResultListener(this);
                
                return invocation.invoke();
        }
        
        
        @Override
        public void beforeResult(ActionInvocation invocation, String resultCode) {
                ActionContext ac = invocation.getInvocationContext();
                HttpServletResponse response = (HttpServletResponse) ac.get(StrutsStatics.HTTP_RESPONSE);
                addCookiesToResponse(invocation.getAction(), response);
        }       

        
        private void addCookiesToResponse(Object action, HttpServletResponse response) {
                if (action instanceof UserAware) {
                        List<Cookie> cookies = ((UserAware) action).getCookies();
                        if (cookies != null) {
                                for (Cookie cookie : cookies) {
                                        response.addCookie(cookie);
                                }
                        }
                }
        }

                  
        private void createCookiesMap(HttpServletRequest request) {
                cookiesMap  = new HashMap<String, Cookie>();
                Cookie[] cookies = request.getCookies();
                if(cookies==null)
                        return;
                for (Cookie cookie : cookies) {
                        if (cookie.getName().equals(UserInterceptor.USER_ID_COOKIE_NAME)) {
                                if (cookie.getDomain() == null || cookie.getDomain().isEmpty()
                                                || !cookie.getDomain().equals(this.cookieDomain)) 
                                {
                                        if (!cookieDomain.isEmpty()) {
                                                cookie.setMaxAge(0);
                                                Cookie newUserCookie = new Cookie(UserInterceptor.USER_ID_COOKIE_NAME, cookie.getValue());
                                                newUserCookie.setMaxAge(SECONDS_IN_YEAR); // one year
                                                newUserCookie.setPath("/");
                                                newUserCookie.setDomain(cookieDomain);
                                                
                                                HttpServletResponse response = ServletActionContext.getResponse();
                                                response.addCookie(newUserCookie);
                                                response.addCookie(cookie);
                                        }
                                        else {
                                            log.error("cookieDomain not set");
                                        }
                                }
                        }
                    cookiesMap.put(cookie.getName(), cookie);
                }
        }
        
        

        
        private UserSessionInfo createAndGetSessionFromUIDCookie(HttpSession session) {
                userCookie = (Cookie) cookiesMap.get(UserInterceptor.USER_ID_COOKIE_NAME);
                UserSessionInfo userInfo = null;
                if(userCookie != null){
                        String uidString = userCookie.getValue();
                        if(uidString != null){
                                try {
                                        Long receivedUID = Long.parseLong(desEncrypter.decrypt(uidString));
                    log.info("Invalid session with user cookie : " + receivedUID);
                                        userInfo = new UserSessionInfo(receivedUID, session.getId());
                                        if(userInfo.getUserId() == -1){
                                            log.error("The User for the UID cookie has been deleted in our database. So cleaning up the UID cookie.");
                                            expireUidCookie();
                                        }
                                } catch (NumberFormatException nfe) {
                                        log.error("The UID cookie contains an unparseable userID");
                                        expireUidCookie();
                                        userInfo = new UserSessionInfo();
                                }
                        }
                }
                else{
                        userInfo = new UserSessionInfo();
                        log.info("Invalid session without user cookie.");
                }
                return userInfo;
        }

    private void expireUidCookie() {
        Cookie newUserCookie = new Cookie(UserInterceptor.USER_ID_COOKIE_NAME, "-1"); //The value here is immaterial
        newUserCookie.setMaxAge(0);                     // Expire this cookie now
        newUserCookie.setPath("/");
        newUserCookie.setDomain(cookieDomain);
        
        HttpServletResponse response = ServletActionContext.getResponse();
        response.addCookie(newUserCookie);
    }

}