Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
637 rajveer 1
/**
2
 * 
3
 */
4
package in.shop2020.serving.controllers;
5
 
2263 vikas 6
import in.shop2020.datalogger.EventType;
3830 chandransh 7
import in.shop2020.model.v1.user.Cart;
7825 amar.kumar 8
import in.shop2020.model.v1.user.Sex;
9
import in.shop2020.model.v1.user.ShoppingCartException;
10
import in.shop2020.model.v1.user.TrackLogType;
637 rajveer 11
import in.shop2020.model.v1.user.User;
7825 amar.kumar 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;
815 rajveer 17
import in.shop2020.serving.utils.DesEncrypter;
1175 varun.gupt 18
import in.shop2020.serving.utils.UserMessage;
3126 rajveer 19
import in.shop2020.thrift.clients.UserClient;
2511 vikas 20
import in.shop2020.utils.DataLogger;
637 rajveer 21
 
22
import java.io.IOException;
23
import java.util.Date;
1623 rajveer 24
import java.util.List;
637 rajveer 25
 
7825 amar.kumar 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;
832 rajveer 31
import org.apache.log4j.Logger;
7825 amar.kumar 32
import org.apache.struts2.ServletActionContext;
4222 varun.gupt 33
import org.apache.struts2.convention.annotation.Action;
34
import org.apache.struts2.convention.annotation.Actions;
35
import org.apache.struts2.convention.annotation.InterceptorRef;
637 rajveer 36
import org.apache.struts2.convention.annotation.Result;
925 rajveer 37
import org.apache.struts2.convention.annotation.Results;
7825 amar.kumar 38
import org.apache.thrift.TException;
39
import org.apache.thrift.transport.TTransportException;
40
import org.json.JSONObject;
637 rajveer 41
 
42
/**
43
 * 
44
 * @author rajveer
781 vikas 45
 * 
637 rajveer 46
 */
925 rajveer 47
@Results({
48
	@Result(name="success", type="redirectAction", params = {"actionName" , "home"}),
49
	@Result(name = "redirect", location = "${redirectUrl}", type = "redirect")
50
})
637 rajveer 51
 
781 vikas 52
public class LoginController extends BaseController {
650 rajveer 53
 
781 vikas 54
	/**
55
	 * 
56
	 */
57
	private static final long serialVersionUID = 5390035354379263121L;
650 rajveer 58
 
832 rajveer 59
	private static Logger log = Logger.getLogger(Class.class);
815 rajveer 60
	private DesEncrypter desEncrypter = new DesEncrypter("saholic");
5510 rajveer 61
	private String loginResult = "0";
2933 vikas 62
	private String redirectUrl = "/";
7825 amar.kumar 63
	private String signed_request;
64
	private Long userId = -1L;
65
 
781 vikas 66
	public LoginController() {
637 rajveer 67
		super();
68
	}
4222 varun.gupt 69
	@Actions({
70
		@Action(value="login", interceptorRefs={@InterceptorRef("myDefault")}),
71
		@Action(value="login-mini", interceptorRefs={@InterceptorRef("myDefault")})
72
	})
781 vikas 73
	public String index() throws SecurityException, IOException {
925 rajveer 74
		if(userinfo.isLoggedIn()){
75
    		return "success";
76
    	}
650 rajveer 77
		return "index";
781 vikas 78
	}
637 rajveer 79
 
781 vikas 80
	public String create() throws SecurityException, Exception {
81
		if (loginUser()) {
2959 chandransh 82
			log.info("Will redirect the user to:" + redirectUrl);
2637 vikas 83
            return "redirect";
781 vikas 84
		} else {
1175 varun.gupt 85
			addActionError(UserMessage.USER_AUTHENTICATION_FAILURE);
3185 vikas 86
            DataLogger.logData(EventType.LOGIN_FAILED, getSessionId(), userinfo.getUserId(), this.request.getParameter("email"));
830 vikas 87
			return "login";
781 vikas 88
		}
89
	}
90
 
91
	private boolean loginUser() {
92
		try {
7825 amar.kumar 93
			String email, password = null, isFacebookUser;
781 vikas 94
 
7825 amar.kumar 95
			isFacebookUser = (String)this.request.getAttribute("isFacebookUser");
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")))) {
781 vikas 104
				return false;
105
			}
815 rajveer 106
 
7825 amar.kumar 107
			String encryptedPassword = null;
108
			if(!(password==null)){
109
				encryptedPassword = desEncrypter.encrypt(password);
110
			}
111
 
3126 rajveer 112
			UserClient userContextServiceClient = new UserClient();
1747 varun.gupt 113
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
7825 amar.kumar 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 {
167
				user = userClient.authenticateUser(email, encryptedPassword);
168
			}
793 rajveer 169
			userClient.setUserAsLoggedIn(user.getUserId(),(new Date()).getTime());
170
			String pincode = userClient.getDefaultPincode(user.getUserId());
2637 vikas 171
 
1175 varun.gupt 172
			// TODO: setTotalItems shouldn't be a method on userinfo. This allows
173
			// for potentially updating the item count wrongly. The method setCartId
637 rajveer 174
			// should update the item count as well. Also, there can be a method
1175 varun.gupt 175
			// called refreshItemCount() that automatically updates the number of
637 rajveer 176
			// items currently in the cart.
1625 rajveer 177
			if(userinfo.getUserId() != -1){
1623 rajveer 178
				userClient.mergeCart(userinfo.getCartId(), user.getActiveCartId());
1625 rajveer 179
 
2982 rajveer 180
				List<Long> items = userClient.getBrowseHistoryItems(userinfo.getUserId());
181
				if(items != null){
182
					for(Long itemId: items){
183
						userClient.updateBrowseHistory(user.getUserId(), itemId);
1623 rajveer 184
					}
185
				}
4453 varun.gupt 186
 
2982 rajveer 187
				items = userClient.getMyResearchItems(userinfo.getUserId());
188
				if(items != null){
189
					for(Long itemId: items){
190
						userClient.updateMyResearch(user.getUserId(), itemId);
1625 rajveer 191
					}
192
				}
1623 rajveer 193
			}
194
 
1625 rajveer 195
			userinfo.setUserId(user.getUserId());
196
			userinfo.setEmail(email);
197
			userinfo.setLoggedIn(true);
198
			userinfo.setPincode(pincode);
637 rajveer 199
			userinfo.setCartId(user.getActiveCartId());
3830 chandransh 200
			Cart cart = userClient.getCart(user.getActiveCartId());
201
			userinfo.setTotalItems(cart.getLinesSize());
202
			userinfo.setTotalAmount(cart.getTotalPrice());
2959 chandransh 203
			log.info(userinfo);
2996 vikas 204
			String src = user.getSource();
205
			if (src == null) {
206
			    src = "";
207
			}
11688 amit.gupta 208
			try {
3185 vikas 209
			DataLogger.logData(EventType.LOGIN_SUCCESS, getSessionId(), userinfo.getUserId(),
2996 vikas 210
                    email, src);
11688 amit.gupta 211
			}catch (Exception e) {
212
				log.error("Could not log login success event", e);
213
				// TODO: handle exception
214
			}
2637 vikas 215
    		return true;
781 vikas 216
		} catch (Exception e) {
2959 chandransh 217
			log.error(UserMessage.USER_AUTHENTICATION_FAILURE, e);
781 vikas 218
			return false;
219
		}
220
	}
637 rajveer 221
 
7825 amar.kumar 222
 
223
 
224
 
225
	private boolean createNewUserForFacebook(String email) {
226
    	String password;
227
    	password = RandomStringUtils.randomAlphabetic(8);
228
 
229
    	String name = (String)this.request.getAttribute("name");
230
    	String accessToken = (String)this.request.getAttribute("accessToken");
231
    	String facebookId = (String)this.request.getAttribute("facebookId");
232
		User user = new User();
233
		user.setEmail(email);
234
		String encryptedPassword = desEncrypter.encrypt(password);
235
		user.setPassword(encryptedPassword);
236
		user.setCommunicationEmail(email);
237
		user.setName(name);
238
		user.setFacebookAccessToken(accessToken);
239
		if(user.getFacebookId()==null || user.getFacebookId().isEmpty()) {
240
			user.setFacebookId(facebookId);
241
		}
242
		Cookie sourceCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SRC_COOKIE);
243
        if (sourceCookie != null) {
244
            DesEncrypter des = new DesEncrypter(TrackingInterceptor.ENCRIPTION_STRING);
245
            String sourceCookieVal = des.decrypt(sourceCookie.getValue());
246
            user.setSource(sourceCookieVal);
247
        }
248
 
249
        Cookie sourceTimeCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SRC_TIME_COOKIE);
250
        long sourceTime = 0;
251
        if (sourceTimeCookie != null) {
252
            try {
253
                sourceTime = Long.parseLong(sourceTimeCookie.getValue());
254
            }
255
            catch (Exception e) {
256
                log.warn("Unable to parse session src time cookie.");
257
            }
258
            user.setSourceStartTime(sourceTime);
259
        }
260
 
261
		user.setSex(Sex.WONT_SAY);
262
		user.setIsFacebookUser(true);
263
 
264
		UserClient userContextServiceClient;
265
		try {
266
			userContextServiceClient = new UserClient();
267
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
268
			try{
269
				user = userClient.createUser(user);
270
			}catch (UserContextException ux){
271
				addActionError("User already exists with this email id.");
272
				DataLogger.logData(EventType.REGISTER_FAILED_USER_EXISTS, getSessionId(), userinfo.getUserId(), email, "", email);
273
				return false;				
274
			}
275
			this.userId = user.getUserId();
276
			long userId = user.getUserId();
277
			userClient.setUserAsLoggedIn(userId, (new Date()).getTime());
278
			String pincode = userClient.getDefaultPincode(user.getUserId());
279
 
280
			if(userinfo.getUserId() != -1){
281
				userClient.mergeCart(userinfo.getCartId(), user.getActiveCartId());
282
 
283
				List<Long> items = userClient.getBrowseHistoryItems(userinfo.getUserId());
284
				if(items != null){
285
					for(Long itemId: items){
286
						userClient.updateBrowseHistory(user.getUserId(), itemId);
287
					}
288
				}
289
 
290
				items = userClient.getMyResearchItems(userinfo.getUserId());
291
				if(items != null){
292
					for(Long itemId: items){
293
						userClient.updateMyResearch(user.getUserId(), itemId);
294
					}
295
				}
296
			}
297
 
298
			userinfo.setUserId(userId);
299
			userinfo.setEmail(email);
300
			userinfo.setLoggedIn(true);
301
			userinfo.setPincode(pincode);
302
			userinfo.setCartId(user.getActiveCartId());
303
			Cart cart = userClient.getCart(userinfo.getCartId());
304
			userinfo.setTotalItems(cart.getLinesSize());
305
			userinfo.setTotalAmount(cart.getTotalPrice());
306
 
307
	        if (cookiesMap.containsKey(TrackingInterceptor.AFF_COOKIE)) {
308
	            long affId = Long.parseLong(cookiesMap.get(TrackingInterceptor.AFF_COOKIE).getValue());
309
	            userClient.addTrackLog(affId, userId, TrackLogType.NEW_REGISTRATION, "",email, (new Date()).getTime());
310
	        }
311
	        DataLogger.logData(EventType.REGISTER_SUCCESS, getSessionId(), userinfo.getUserId(), email, "", email);
312
 
313
			return true;
314
		} catch (TTransportException e) {
315
			log.error("Unable to register user." + e);
316
		} catch (UserContextException e) {
317
			log.error("Unable to register user." + e);
318
		} catch (TException e) {
319
			log.error("Unable to register user." + e);
320
		} catch (UserAffiliateException e) {
321
			log.error("Unable to register user." + e);
322
		} catch (ShoppingCartException e) {
323
			log.error("Unable to register user." + e);
324
		} catch (WidgetException e) {
325
			log.error("Unable to register user." + e);
326
		}
327
		return false;
328
	}
329
 
330
	public String facebooklogin(){
331
		try {
332
			String dataResponse = signed_request.split("\\.")[1];
333
			String encoded_json = dataResponse.replace("-", "+").replace("_", "/");
334
			byte[] decoded_json  = Base64.decodeBase64(encoded_json);
335
			JSONObject json_data = new JSONObject(new String(decoded_json, "UTF-8"));
336
			this.request.setAttribute("name", (new JSONObject(json_data.get("registration").toString())).get("name"));
337
			this.request.setAttribute("email", (new JSONObject(json_data.get("registration").toString())).get("email"));
338
			this.request.setAttribute("accessToken", json_data.get("oauth_token").toString());
339
			this.request.setAttribute("facebookId", json_data.get("user_id").toString());
340
			this.request.setAttribute("isFacebookUser", "true");
341
			if(loginUser()){
342
				return "redirect";
343
			} else {
344
				log.error("Error in logging through facebook");
345
				addActionError(UserMessage.FACEBOOK_USER_AUTH_FAILURE);
346
				return "login";
347
			}
348
		} catch (Exception e ) {
349
			log.error("Error in reading facebook response for login", e);
350
			addActionError(UserMessage.FACEBOOK_USER_AUTH_FAILURE);
351
			return "login";
352
		}
353
	}
354
 
5510 rajveer 355
	public String authenticateUser() {
356
		String email, password;
357
 
358
		email = this.request.getParameter("email");
359
		password = this.request.getParameter("password");
360
 
361
		if (email == null || password == null) {
362
			loginResult = "0";
363
			return "result";
364
		}
365
 
366
		String encryptedPassword = desEncrypter.encrypt(password);
367
		try{
368
			UserClient userContextServiceClient = new UserClient();
369
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
370
			userClient.authenticateUser(email, encryptedPassword);
371
		}catch (Exception e) {
372
			loginResult = "0";
373
			return "result";
374
		}
375
		loginResult = "1";
376
		return "result";
377
	}
378
 
379
	public String getLoginResult() {
380
		return loginResult;
381
	}
382
 
924 vikas 383
	public String getRedirectUrl() {
384
		return redirectUrl;
781 vikas 385
	}
386
 
924 vikas 387
	public void setRedirectUrl(String redirectUrl) {
388
		this.redirectUrl = redirectUrl;
389
	}
6903 anupam.sin 390
 
7825 amar.kumar 391
	public String getSigned_request() {
392
		return signed_request;
393
	}
394
	public void setSigned_request(String signed_request) {
395
		this.signed_request = signed_request;
396
	}
397
 
6903 anupam.sin 398
	public static void main(String[] args) {
399
        DesEncrypter des = new DesEncrypter("saholic");
400
        System.out.println(des.decrypt("XvrWIvmYrUAdXqxhovZMSw"));
401
    }
637 rajveer 402
}