Subversion Repositories SmartDukaan

Rev

Rev 11980 | Rev 11987 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
781 vikas 1
package in.shop2020.serving.interceptors;
2
 
3185 vikas 3
import in.shop2020.serving.services.UserSessionInfo;
4
import in.shop2020.serving.utils.DesEncrypter;
5
 
781 vikas 6
import java.util.HashMap;
2907 rajveer 7
import java.util.List;
781 vikas 8
import java.util.Map;
9
 
10
import javax.servlet.http.Cookie;
11
import javax.servlet.http.HttpServletRequest;
837 vikas 12
import javax.servlet.http.HttpServletResponse;
781 vikas 13
import javax.servlet.http.HttpSession;
14
 
1044 chandransh 15
import org.apache.log4j.Logger;
781 vikas 16
import org.apache.struts2.ServletActionContext;
2907 rajveer 17
import org.apache.struts2.StrutsStatics;
781 vikas 18
 
2907 rajveer 19
import com.opensymphony.xwork2.ActionContext;
781 vikas 20
import com.opensymphony.xwork2.ActionInvocation;
21
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
2907 rajveer 22
import com.opensymphony.xwork2.interceptor.PreResultListener;
781 vikas 23
 
2907 rajveer 24
public class UserInterceptor extends AbstractInterceptor implements PreResultListener{
781 vikas 25
 
2907 rajveer 26
	public static final int SECONDS_IN_YEAR = 60*60*24*365; 
7825 amar.kumar 27
	public static final int FACEBOOK_USER_COOKIE_EXPIRY_TIME = 60*60*24*60; 
837 vikas 28
 
781 vikas 29
	private static final long serialVersionUID = -4125815700236506235L;
1044 chandransh 30
	private static Logger log = Logger.getLogger(UserInterceptor.class);
781 vikas 31
 
2907 rajveer 32
	public static final String USER_INFO_COOKIE_NAME = "uic";
33
	public static final String USER_ID_COOKIE_NAME = "uid";
11980 amit.gupta 34
	public static final String DEAL_COUPON_REMOVED = "dcr";
2998 rajveer 35
	public static final String COOKIE_DECRYPTION_STRING = "shop2020";
781 vikas 36
 
2998 rajveer 37
	private DesEncrypter desEncrypter = new DesEncrypter(COOKIE_DECRYPTION_STRING);
781 vikas 38
 
1658 vikas 39
	private String cookieDomain = "";
40
 
41
	public void setCookieDomain(String cookieDomain) {
42
		this.cookieDomain = cookieDomain;
43
	}
44
 
781 vikas 45
	@Override
46
	public String intercept(ActionInvocation invocation) throws Exception {
47
		final Object action = invocation.getAction();
48
 
1658 vikas 49
		log.debug("inside user intercepror");
4388 rajveer 50
 
51
		HttpServletRequest request = ServletActionContext.getRequest();
3185 vikas 52
        HttpSession session = request.getSession(); // Do not remove it, session id is used for session tracking.
781 vikas 53
 
4388 rajveer 54
        Map<String, Cookie> cookiesMap = createCookiesMap(request);
781 vikas 55
 
2973 chandransh 56
        // CreateUserInterceptor may have set the userinfo object in the request
57
        // itself. If we can get the userinfo object here, we don't need to
58
        // parse the cookies that came in with the request.
2907 rajveer 59
		UserSessionInfo userInfo = (UserSessionInfo) request.getAttribute(USER_INFO_COOKIE_NAME);
60
 
4388 rajveer 61
		Cookie userCookie = cookiesMap.get(UserInterceptor.USER_ID_COOKIE_NAME);
62
		Cookie userinfoCookie = cookiesMap.get(USER_INFO_COOKIE_NAME);
1354 vikas 63
 
2907 rajveer 64
		if(userInfo == null ){
2973 chandransh 65
		    //Okay, we didn't get the userinfo object from the request. Time to parse the UIC cookie.
2907 rajveer 66
			if(userinfoCookie!=null){
67
				userInfo = UserSessionInfo.getUserSessionInfoFromCookieValue(userinfoCookie.getValue());
2973 chandransh 68
				if(userInfo.getUserId() == -1){
69
				    //This means that the cookie couldn't be parsed. So, we should remove the cookie.
70
				    expireUicCookie();
71
				    expireUidCookie();
72
				}
73
			} else {
74
			    //No UIC cookie too. Try the old UID cookie. This method is guaranteed  to return a userinfo object, cookie or not.
4388 rajveer 75
				userInfo = createAndGetSessionFromUIDCookie(session, cookiesMap, userCookie);
1614 rajveer 76
			}
1354 vikas 77
		}
2973 chandransh 78
 
79
		//Set the request attribute for access by other interceptors.
2907 rajveer 80
		request.setAttribute(USER_INFO_COOKIE_NAME, userInfo);
81
 
2973 chandransh 82
		//Set the userinfo object for use by actions.
781 vikas 83
		if (action instanceof UserAware) {
84
        	UserAware sessionAction = (UserAware) action;
85
        	sessionAction.setSession(session);
86
        	sessionAction.setUserSessionInfo(userInfo);
87
        	sessionAction.setCookiesMap(cookiesMap);
88
        	sessionAction.setUserCookie(userCookie);
1713 vikas 89
        	sessionAction.setCookieDomainName(cookieDomain);
781 vikas 90
        }
2907 rajveer 91
 
2973 chandransh 92
        // Ensure that the response of the action is presented to the pre-result
93
        // listened of this interceptor. We want to add the cookies there.
2907 rajveer 94
		invocation.addPreResultListener(this);
95
 
781 vikas 96
		return invocation.invoke();
97
	}
98
 
1614 rajveer 99
 
2907 rajveer 100
	@Override
101
	public void beforeResult(ActionInvocation invocation, String resultCode) {
11986 amit.gupta 102
		try {
103
			log.info("in user interceptor: " + invocation.getResult().toString());
104
		} catch (Exception e) {
105
			// TODO Auto-generated catch block
106
			e.printStackTrace();
107
		}
2907 rajveer 108
		ActionContext ac = invocation.getInvocationContext();
109
		HttpServletResponse response = (HttpServletResponse) ac.get(StrutsStatics.HTTP_RESPONSE);
110
		addCookiesToResponse(invocation.getAction(), response);
111
	}	
112
 
2973 chandransh 113
	/**
114
	 * Adds cookies to the response object after the action has been executed.
115
	 * 
116
	 * @param action
117
	 * @param response
118
	 */
2907 rajveer 119
	private void addCookiesToResponse(Object action, HttpServletResponse response) {
2960 chandransh 120
	    log.debug("Setting cookies in response");
2907 rajveer 121
		if (action instanceof UserAware) {
122
			List<Cookie> cookies = ((UserAware) action).getCookies();
123
			if (cookies != null) {
124
				for (Cookie cookie : cookies) {
2960 chandransh 125
				    log.debug("Adding cookie " + cookie.getName() + " to the response");
2907 rajveer 126
					response.addCookie(cookie);
127
				}
128
			}
129
		}
130
	}
131
 
2973 chandransh 132
    /**
133
     * Expires the UID cookie if the domain is not set or is set as the empty
134
     * domain. Creates a new UID cookie with the cookie domain set.
135
     * 
136
     * This is mostly to handle legacy issue wherein we were not setting the
137
     * cookie domain explicitly to .saholic.com and different cookies were set
138
     * for saholic.com and www.saholic.com.
139
     * 
140
     * @param request
141
     */
4388 rajveer 142
	private Map<String, Cookie> createCookiesMap(HttpServletRequest request) {
143
		Map<String, Cookie> cookiesMap  = new HashMap<String, Cookie>();
781 vikas 144
		Cookie[] cookies = request.getCookies();
145
		if(cookies==null)
4388 rajveer 146
			return cookiesMap;
1658 vikas 147
		for (Cookie cookie : cookies) {
2907 rajveer 148
			if (cookie.getName().equals(UserInterceptor.USER_ID_COOKIE_NAME)) {
1658 vikas 149
				if (cookie.getDomain() == null || cookie.getDomain().isEmpty()
150
						|| !cookie.getDomain().equals(this.cookieDomain)) 
151
				{
152
					if (!cookieDomain.isEmpty()) {
153
						cookie.setMaxAge(0);
2907 rajveer 154
						Cookie newUserCookie = new Cookie(UserInterceptor.USER_ID_COOKIE_NAME, cookie.getValue());
1658 vikas 155
						newUserCookie.setMaxAge(SECONDS_IN_YEAR); // one year
156
						newUserCookie.setPath("/");
157
						newUserCookie.setDomain(cookieDomain);
158
 
159
						HttpServletResponse response = ServletActionContext.getResponse();
160
						response.addCookie(newUserCookie);
161
						response.addCookie(cookie);
2973 chandransh 162
					} else {
1722 vikas 163
					    log.error("cookieDomain not set");
164
					}
1658 vikas 165
				}
166
			}
167
		    cookiesMap.put(cookie.getName(), cookie);
168
		}
4388 rajveer 169
		return cookiesMap;
781 vikas 170
	}
1614 rajveer 171
 
2973 chandransh 172
    /**
173
     * Creates and gets session information from the UID cookie. This should be
174
     * called only when the required information couldn't be had from the UIC
175
     * cookie.
176
     * 
177
     * It also expires the UID cookie if it can't parse the cookie value.
178
     * 
179
     * @param session
180
     * @return A user session info object.
181
     */
4388 rajveer 182
	private UserSessionInfo createAndGetSessionFromUIDCookie(HttpSession session, Map<String, Cookie> cookiesMap, Cookie userCookie) {
781 vikas 183
		UserSessionInfo userInfo = null;
184
		if(userCookie != null){
185
			String uidString = userCookie.getValue();
186
			if(uidString != null){
187
				try {
188
					Long receivedUID = Long.parseLong(desEncrypter.decrypt(uidString));
828 rajveer 189
                    log.info("Invalid session with user cookie : " + receivedUID);
781 vikas 190
					userInfo = new UserSessionInfo(receivedUID, session.getId());
2935 chandransh 191
					if(userInfo.getUserId() == -1){
192
					    log.error("The User for the UID cookie has been deleted in our database. So cleaning up the UID cookie.");
193
					    expireUidCookie();
194
					}
781 vikas 195
				} catch (NumberFormatException nfe) {
196
					log.error("The UID cookie contains an unparseable userID");
2935 chandransh 197
					expireUidCookie();
2473 chandransh 198
					userInfo = new UserSessionInfo();
781 vikas 199
				}
200
			}
2973 chandransh 201
		} else{
202
		    log.info("Invalid session without user cookie.");
203
		    userInfo = new UserSessionInfo();
830 vikas 204
		}
781 vikas 205
		return userInfo;
206
	}
2907 rajveer 207
 
2973 chandransh 208
	/**
209
	 * Expires the UIC cookie.
210
	 */
211
    private void expireUicCookie() {
212
        Cookie newUserCookie = new Cookie(UserInterceptor.USER_INFO_COOKIE_NAME, "-1"); //The value here is immaterial
213
        newUserCookie.setMaxAge(0);                     // Expire this cookie now
214
        newUserCookie.setPath("/");
215
        newUserCookie.setDomain(cookieDomain);
216
 
217
        HttpServletResponse response = ServletActionContext.getResponse();
218
        response.addCookie(newUserCookie);
219
    }	
220
 
221
    /**
222
     * Expires the UID cookie.
223
     */
2935 chandransh 224
    private void expireUidCookie() {
225
        Cookie newUserCookie = new Cookie(UserInterceptor.USER_ID_COOKIE_NAME, "-1"); //The value here is immaterial
226
        newUserCookie.setMaxAge(0);                     // Expire this cookie now
227
        newUserCookie.setPath("/");
228
        newUserCookie.setDomain(cookieDomain);
229
 
230
        HttpServletResponse response = ServletActionContext.getResponse();
231
        response.addCookie(newUserCookie);
232
    }
233
 
781 vikas 234
}