Subversion Repositories SmartDukaan

Rev

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