Subversion Repositories SmartDukaan

Rev

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