Subversion Repositories SmartDukaan

Rev

Rev 7039 | Rev 11688 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 7039 Rev 7825
Line 3... Line 3...
3
 */
3
 */
4
package in.shop2020.serving.controllers;
4
package in.shop2020.serving.controllers;
5
 
5
 
6
import in.shop2020.datalogger.EventType;
6
import in.shop2020.datalogger.EventType;
7
import in.shop2020.model.v1.user.Cart;
7
import in.shop2020.model.v1.user.Cart;
-
 
8
import in.shop2020.model.v1.user.Sex;
-
 
9
import in.shop2020.model.v1.user.ShoppingCartException;
-
 
10
import in.shop2020.model.v1.user.TrackLogType;
8
import in.shop2020.model.v1.user.User;
11
import in.shop2020.model.v1.user.User;
-
 
12
import in.shop2020.model.v1.user.UserAffiliateException;
-
 
13
import in.shop2020.model.v1.user.UserContextException;
-
 
14
import in.shop2020.model.v1.user.WidgetException;
-
 
15
import in.shop2020.serving.interceptors.TrackingInterceptor;
-
 
16
import in.shop2020.serving.interceptors.UserInterceptor;
9
import in.shop2020.serving.utils.DesEncrypter;
17
import in.shop2020.serving.utils.DesEncrypter;
10
import in.shop2020.serving.utils.UserMessage;
18
import in.shop2020.serving.utils.UserMessage;
11
import in.shop2020.thrift.clients.UserClient;
19
import in.shop2020.thrift.clients.UserClient;
12
import in.shop2020.utils.DataLogger;
20
import in.shop2020.utils.DataLogger;
13
 
21
 
14
import java.io.IOException;
22
import java.io.IOException;
15
import java.util.Date;
23
import java.util.Date;
16
import java.util.List;
24
import java.util.List;
17
 
25
 
-
 
26
import javax.servlet.http.Cookie;
-
 
27
import javax.servlet.http.HttpServletResponse;
-
 
28
 
-
 
29
import org.apache.commons.codec.binary.Base64;
-
 
30
import org.apache.commons.lang.RandomStringUtils;
18
import org.apache.log4j.Logger;
31
import org.apache.log4j.Logger;
-
 
32
import org.apache.struts2.ServletActionContext;
19
import org.apache.struts2.convention.annotation.Action;
33
import org.apache.struts2.convention.annotation.Action;
20
import org.apache.struts2.convention.annotation.Actions;
34
import org.apache.struts2.convention.annotation.Actions;
21
import org.apache.struts2.convention.annotation.InterceptorRef;
35
import org.apache.struts2.convention.annotation.InterceptorRef;
22
import org.apache.struts2.convention.annotation.Result;
36
import org.apache.struts2.convention.annotation.Result;
23
import org.apache.struts2.convention.annotation.Results;
37
import org.apache.struts2.convention.annotation.Results;
-
 
38
import org.apache.thrift.TException;
-
 
39
import org.apache.thrift.transport.TTransportException;
-
 
40
import org.json.JSONObject;
24
 
41
 
25
/**
42
/**
26
 * 
43
 * 
27
 * @author rajveer
44
 * @author rajveer
28
 * 
45
 * 
Line 41... Line 58...
41
 
58
 
42
	private static Logger log = Logger.getLogger(Class.class);
59
	private static Logger log = Logger.getLogger(Class.class);
43
	private DesEncrypter desEncrypter = new DesEncrypter("saholic");
60
	private DesEncrypter desEncrypter = new DesEncrypter("saholic");
44
	private String loginResult = "0";
61
	private String loginResult = "0";
45
	private String redirectUrl = "/";
62
	private String redirectUrl = "/";
-
 
63
	private String signed_request;
-
 
64
	private Long userId = -1L;
46
 
65
	
47
	public LoginController() {
66
	public LoginController() {
48
		super();
67
		super();
49
	}
68
	}
50
	@Actions({
69
	@Actions({
51
		@Action(value="login", interceptorRefs={@InterceptorRef("myDefault")}),
70
		@Action(value="login", interceptorRefs={@InterceptorRef("myDefault")}),
Line 69... Line 88...
69
		}
88
		}
70
	}
89
	}
71
 
90
 
72
	private boolean loginUser() {
91
	private boolean loginUser() {
73
		try {
92
		try {
74
			String email, password;
93
			String email, password = null, isFacebookUser;
75
 
-
 
76
			email = this.request.getParameter("email");
-
 
77
			password = this.request.getParameter("password");
-
 
78
 
94
 
-
 
95
			isFacebookUser = (String)this.request.getAttribute("isFacebookUser");
79
			if (email == null || password == null) {
96
			if (isFacebookUser!=null && isFacebookUser.equals("true")) {
-
 
97
				email = (String)this.request.getAttribute("email");
-
 
98
			} else {
-
 
99
				email = this.request.getParameter("email");
-
 
100
				password = this.request.getParameter("password");
-
 
101
			}
-
 
102
			
-
 
103
			if (email == null || (password == null && (isFacebookUser==null || !isFacebookUser.equals("true")))) {
80
				return false;
104
				return false;
81
			}
105
			}
82
 
106
			
-
 
107
			String encryptedPassword = null;
-
 
108
			if(!(password==null)){
83
			String encryptedPassword = desEncrypter.encrypt(password);
109
				encryptedPassword = desEncrypter.encrypt(password);
-
 
110
			}
84
			
111
			
85
			UserClient userContextServiceClient = new UserClient();
112
			UserClient userContextServiceClient = new UserClient();
86
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
113
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
-
 
114
 
-
 
115
			User user = null;
-
 
116
			
-
 
117
			boolean shouldChangeCookieExpiry = false;
-
 
118
			boolean isNewFacebookUser = false;
-
 
119
			if (isFacebookUser!=null && isFacebookUser.equals("true") && !email.equals("undefined")) {
-
 
120
				String accessToken = (String)this.request.getAttribute("accessToken");
-
 
121
				String facebookId = (String)this.request.getAttribute("facebookId");
-
 
122
				if (userClient.userExists(email)){
-
 
123
					shouldChangeCookieExpiry = true;
-
 
124
					user = userClient.getUserByEmail(email);
-
 
125
					userId = user.getUserId();
-
 
126
					if(!user.isIsFacebookUser()) {
-
 
127
						user.setIsFacebookUser(true);						
-
 
128
						user.setFacebookAccessToken(accessToken);
-
 
129
						user.setFacebookId(facebookId);
-
 
130
						userClient.updateUser(user);
-
 
131
					} else if(user.getFacebookAccessToken() == null || (accessToken!=null && !accessToken.equals(user.getFacebookAccessToken()))){
-
 
132
						user.setFacebookAccessToken(accessToken);
-
 
133
						if(facebookId!=null) {
-
 
134
							user.setFacebookId(facebookId);
-
 
135
						}
-
 
136
						userClient.updateUser(user);
-
 
137
					}
-
 
138
				} else {
-
 
139
					isNewFacebookUser = createNewUserForFacebook(email);
-
 
140
				}
-
 
141
				if(shouldChangeCookieExpiry || isNewFacebookUser) {
-
 
142
					Cookie uidCookie = (Cookie) cookiesMap.get(UserInterceptor.USER_ID_COOKIE_NAME);
-
 
143
					Cookie uicCookie = (Cookie) cookiesMap.get(UserInterceptor.USER_INFO_COOKIE_NAME);
-
 
144
					HttpServletResponse response = ServletActionContext.getResponse();
-
 
145
					if (uidCookie == null) {
-
 
146
						DesEncrypter cookieEncryter = new DesEncrypter(UserInterceptor.COOKIE_DECRYPTION_STRING);
-
 
147
						uidCookie = new Cookie(UserInterceptor.USER_ID_COOKIE_NAME, cookieEncryter.encrypt(userId + ""));
-
 
148
						uidCookie.setPath("/");
-
 
149
						if(!domainName.isEmpty()) {
-
 
150
							uidCookie.setDomain(domainName);
-
 
151
						}
-
 
152
					}
-
 
153
					if (uicCookie != null) {
-
 
154
						uicCookie.setMaxAge(UserInterceptor.FACEBOOK_USER_COOKIE_EXPIRY_TIME);
-
 
155
						cookiesMap.put(UserInterceptor.USER_INFO_COOKIE_NAME, uicCookie);
-
 
156
				        response.addCookie(uicCookie);
-
 
157
					}
-
 
158
					uidCookie.setMaxAge(UserInterceptor.FACEBOOK_USER_COOKIE_EXPIRY_TIME);
-
 
159
					cookiesMap.put(UserInterceptor.USER_ID_COOKIE_NAME, uidCookie);
-
 
160
			        response.addCookie(uidCookie);
-
 
161
			        
-
 
162
			        if(isNewFacebookUser) {
-
 
163
			        	return true;
-
 
164
			        }
-
 
165
				}
-
 
166
			} else {
87
			User user = userClient.authenticateUser(email, encryptedPassword);
167
				user = userClient.authenticateUser(email, encryptedPassword);
-
 
168
			}
88
			userClient.setUserAsLoggedIn(user.getUserId(),(new Date()).getTime());
169
			userClient.setUserAsLoggedIn(user.getUserId(),(new Date()).getTime());
89
			String pincode = userClient.getDefaultPincode(user.getUserId());
170
			String pincode = userClient.getDefaultPincode(user.getUserId());
90
			
171
			
91
			// TODO: setTotalItems shouldn't be a method on userinfo. This allows
172
			// TODO: setTotalItems shouldn't be a method on userinfo. This allows
92
			// for potentially updating the item count wrongly. The method setCartId
173
			// for potentially updating the item count wrongly. The method setCartId
Line 131... Line 212...
131
			log.error(UserMessage.USER_AUTHENTICATION_FAILURE, e);
212
			log.error(UserMessage.USER_AUTHENTICATION_FAILURE, e);
132
			return false;
213
			return false;
133
		}
214
		}
134
	}
215
	}
135
 
216
 
-
 
217
	
-
 
218
	
-
 
219
	
-
 
220
	private boolean createNewUserForFacebook(String email) {
-
 
221
    	String password;
-
 
222
    	password = RandomStringUtils.randomAlphabetic(8);
-
 
223
    	
-
 
224
    	String name = (String)this.request.getAttribute("name");
-
 
225
    	String accessToken = (String)this.request.getAttribute("accessToken");
-
 
226
    	String facebookId = (String)this.request.getAttribute("facebookId");
-
 
227
		User user = new User();
-
 
228
		user.setEmail(email);
-
 
229
		String encryptedPassword = desEncrypter.encrypt(password);
-
 
230
		user.setPassword(encryptedPassword);
-
 
231
		user.setCommunicationEmail(email);
-
 
232
		user.setName(name);
-
 
233
		user.setFacebookAccessToken(accessToken);
-
 
234
		if(user.getFacebookId()==null || user.getFacebookId().isEmpty()) {
-
 
235
			user.setFacebookId(facebookId);
-
 
236
		}
-
 
237
		Cookie sourceCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SRC_COOKIE);
-
 
238
        if (sourceCookie != null) {
-
 
239
            DesEncrypter des = new DesEncrypter(TrackingInterceptor.ENCRIPTION_STRING);
-
 
240
            String sourceCookieVal = des.decrypt(sourceCookie.getValue());
-
 
241
            user.setSource(sourceCookieVal);
-
 
242
        }
-
 
243
        
-
 
244
        Cookie sourceTimeCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SRC_TIME_COOKIE);
-
 
245
        long sourceTime = 0;
-
 
246
        if (sourceTimeCookie != null) {
-
 
247
            try {
-
 
248
                sourceTime = Long.parseLong(sourceTimeCookie.getValue());
-
 
249
            }
-
 
250
            catch (Exception e) {
-
 
251
                log.warn("Unable to parse session src time cookie.");
-
 
252
            }
-
 
253
            user.setSourceStartTime(sourceTime);
-
 
254
        }
-
 
255
		
-
 
256
		user.setSex(Sex.WONT_SAY);
-
 
257
		user.setIsFacebookUser(true);
-
 
258
		
-
 
259
		UserClient userContextServiceClient;
-
 
260
		try {
-
 
261
			userContextServiceClient = new UserClient();
-
 
262
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
-
 
263
			try{
-
 
264
				user = userClient.createUser(user);
-
 
265
			}catch (UserContextException ux){
-
 
266
				addActionError("User already exists with this email id.");
-
 
267
				DataLogger.logData(EventType.REGISTER_FAILED_USER_EXISTS, getSessionId(), userinfo.getUserId(), email, "", email);
-
 
268
				return false;				
-
 
269
			}
-
 
270
			this.userId = user.getUserId();
-
 
271
			long userId = user.getUserId();
-
 
272
			userClient.setUserAsLoggedIn(userId, (new Date()).getTime());
-
 
273
			String pincode = userClient.getDefaultPincode(user.getUserId());
-
 
274
		
-
 
275
			if(userinfo.getUserId() != -1){
-
 
276
				userClient.mergeCart(userinfo.getCartId(), user.getActiveCartId());
-
 
277
			
-
 
278
				List<Long> items = userClient.getBrowseHistoryItems(userinfo.getUserId());
-
 
279
				if(items != null){
-
 
280
					for(Long itemId: items){
-
 
281
						userClient.updateBrowseHistory(user.getUserId(), itemId);
-
 
282
					}
-
 
283
				}
-
 
284
			
-
 
285
				items = userClient.getMyResearchItems(userinfo.getUserId());
-
 
286
				if(items != null){
-
 
287
					for(Long itemId: items){
-
 
288
						userClient.updateMyResearch(user.getUserId(), itemId);
-
 
289
					}
-
 
290
				}
-
 
291
			}
-
 
292
			
-
 
293
			userinfo.setUserId(userId);
-
 
294
			userinfo.setEmail(email);
-
 
295
			userinfo.setLoggedIn(true);
-
 
296
			userinfo.setPincode(pincode);
-
 
297
			userinfo.setCartId(user.getActiveCartId());
-
 
298
			Cart cart = userClient.getCart(userinfo.getCartId());
-
 
299
			userinfo.setTotalItems(cart.getLinesSize());
-
 
300
			userinfo.setTotalAmount(cart.getTotalPrice());
-
 
301
			
-
 
302
	        if (cookiesMap.containsKey(TrackingInterceptor.AFF_COOKIE)) {
-
 
303
	            long affId = Long.parseLong(cookiesMap.get(TrackingInterceptor.AFF_COOKIE).getValue());
-
 
304
	            userClient.addTrackLog(affId, userId, TrackLogType.NEW_REGISTRATION, "",email, (new Date()).getTime());
-
 
305
	        }
-
 
306
	        DataLogger.logData(EventType.REGISTER_SUCCESS, getSessionId(), userinfo.getUserId(), email, "", email);
-
 
307
	
-
 
308
			return true;
-
 
309
		} catch (TTransportException e) {
-
 
310
			log.error("Unable to register user." + e);
-
 
311
		} catch (UserContextException e) {
-
 
312
			log.error("Unable to register user." + e);
-
 
313
		} catch (TException e) {
-
 
314
			log.error("Unable to register user." + e);
-
 
315
		} catch (UserAffiliateException e) {
-
 
316
			log.error("Unable to register user." + e);
-
 
317
		} catch (ShoppingCartException e) {
-
 
318
			log.error("Unable to register user." + e);
-
 
319
		} catch (WidgetException e) {
-
 
320
			log.error("Unable to register user." + e);
-
 
321
		}
-
 
322
		return false;
-
 
323
	}
-
 
324
	
-
 
325
	public String facebooklogin(){
-
 
326
		try {
-
 
327
			String dataResponse = signed_request.split("\\.")[1];
-
 
328
			String encoded_json = dataResponse.replace("-", "+").replace("_", "/");
-
 
329
			byte[] decoded_json  = Base64.decodeBase64(encoded_json);
-
 
330
			JSONObject json_data = new JSONObject(new String(decoded_json, "UTF-8"));
-
 
331
			this.request.setAttribute("name", (new JSONObject(json_data.get("registration").toString())).get("name"));
-
 
332
			this.request.setAttribute("email", (new JSONObject(json_data.get("registration").toString())).get("email"));
-
 
333
			this.request.setAttribute("accessToken", json_data.get("oauth_token").toString());
-
 
334
			this.request.setAttribute("facebookId", json_data.get("user_id").toString());
-
 
335
			this.request.setAttribute("isFacebookUser", "true");
-
 
336
			if(loginUser()){
-
 
337
				return "redirect";
-
 
338
			} else {
-
 
339
				log.error("Error in logging through facebook");
-
 
340
				addActionError(UserMessage.FACEBOOK_USER_AUTH_FAILURE);
-
 
341
				return "login";
-
 
342
			}
-
 
343
		} catch (Exception e ) {
-
 
344
			log.error("Error in reading facebook response for login", e);
-
 
345
			addActionError(UserMessage.FACEBOOK_USER_AUTH_FAILURE);
-
 
346
			return "login";
-
 
347
		}
-
 
348
	}
-
 
349
	
136
	public String authenticateUser() {
350
	public String authenticateUser() {
137
		String email, password;
351
		String email, password;
138
 
352
 
139
		email = this.request.getParameter("email");
353
		email = this.request.getParameter("email");
140
		password = this.request.getParameter("password");
354
		password = this.request.getParameter("password");
Line 167... Line 381...
167
 
381
 
168
	public void setRedirectUrl(String redirectUrl) {
382
	public void setRedirectUrl(String redirectUrl) {
169
		this.redirectUrl = redirectUrl;
383
		this.redirectUrl = redirectUrl;
170
	}
384
	}
171
	
385
	
-
 
386
	public String getSigned_request() {
-
 
387
		return signed_request;
-
 
388
	}
-
 
389
	public void setSigned_request(String signed_request) {
-
 
390
		this.signed_request = signed_request;
-
 
391
	}
-
 
392
	
172
	public static void main(String[] args) {
393
	public static void main(String[] args) {
173
        DesEncrypter des = new DesEncrypter("saholic");
394
        DesEncrypter des = new DesEncrypter("saholic");
174
        System.out.println(des.decrypt("XvrWIvmYrUAdXqxhovZMSw"));
395
        System.out.println(des.decrypt("XvrWIvmYrUAdXqxhovZMSw"));
175
    }
396
    }
176
}
397
}