Subversion Repositories SmartDukaan

Rev

Rev 1722 | Rev 2935 | 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.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 com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class UserInterceptor extends AbstractInterceptor {

        private 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 = "userinfo";
        
        private Map<String, Cookie> cookiesMap = null;
        private Cookie userCookie = null;
        private DesEncrypter desEncrypter = new DesEncrypter("shop2020");
        
        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
        
        //getCookiesMap(request);
                createCookiesMap(request);
                
                // If the request is for an active session.
                UserSessionInfo userInfo = (UserSessionInfo) session.getAttribute(USER_INFO);
                
                // Set the userinfo and the uid cookie if they're not already set.
                if (userInfo == null) {
                        userInfo = createAndGetSessionFromUIDCookie(session);
                        session.setAttribute(USER_INFO, userInfo);
                }
                else {
                        // Update user cookie in case of new registration and login.
                        if(userInfo.getUserId() != -1){
                                createUserCookie(userInfo.getUserId(), false);
                        }
                }
        
                if (action instanceof UserAware) {
                UserAware sessionAction = (UserAware) action;
                sessionAction.setSession(session);
                sessionAction.setUserSessionInfo(userInfo);
                sessionAction.setCookiesMap(cookiesMap);
                sessionAction.setUserCookie(userCookie);
                sessionAction.setCookieDomainName(cookieDomain);
        }

                return invocation.invoke();
        }
        
        
        private void createCookiesMap(HttpServletRequest request) {
                cookiesMap  = new HashMap<String, Cookie>();
                Cookie[] cookies = request.getCookies();
                // This check is necessary for the first request when no cookies are
                // sent.
                if(cookies==null)
                        return;
                for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("uid")) {
                                if (cookie.getDomain() == null || cookie.getDomain().isEmpty()
                                                || !cookie.getDomain().equals(this.cookieDomain)) 
                                {
                                        if (!cookieDomain.isEmpty()) {
                                                cookie.setMaxAge(0);
                                                Cookie newUserCookie = new Cookie("uid", 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 void createUserCookie(long userId, boolean force) {
                userCookie = (Cookie) cookiesMap.get("uid");
                String encryptedUserId = desEncrypter.encrypt(userId + "");
                if(force || userCookie == null || !(encryptedUserId + "").equals(userCookie.getValue())){
                        userCookie = new Cookie("uid", encryptedUserId);
                        userCookie.setMaxAge(SECONDS_IN_YEAR); // one year
                        userCookie.setPath("/");
                        if(!cookieDomain.isEmpty()) {
                                userCookie.setDomain(cookieDomain);
                        }
                        log.info("Created new cookie.");
                        cookiesMap.put("uid", userCookie);
                        HttpServletResponse response = ServletActionContext.getResponse();
                response.addCookie(userCookie);
                }
        }

        
        private UserSessionInfo createAndGetSessionFromUIDCookie(HttpSession session) {
                userCookie = (Cookie) cookiesMap.get("uid");
                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());
                                        session.setAttribute(USER_INFO, userInfo);
                                } catch (NumberFormatException nfe) {
                                        log.error("The UID cookie contains an unparseable userID");
                                        Cookie newUserCookie = new Cookie("uid", "-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);
                                        
                                        userInfo = new UserSessionInfo();
                                        session.setAttribute(USER_INFO, userInfo);
                                }
                        }
                }
                else{
                        userInfo = new UserSessionInfo();
                        session.setAttribute(USER_INFO, userInfo);
                        log.info("Invalid session without user cookie.");
                        //createUserCookie(userInfo.getUserId(), true);
                }
                return userInfo;
        }
}