Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21561 ashik.ali 1
package com.spice.profitmandi.web.controller;
21555 kshitij.so 2
 
25008 amit.gupta 3
import java.lang.reflect.Type;
23419 ashik.ali 4
import java.time.LocalDateTime;
22139 amit.gupta 5
import java.util.ArrayList;
25008 amit.gupta 6
import java.util.HashMap;
22111 ashik.ali 7
import java.util.HashSet;
8
import java.util.List;
25008 amit.gupta 9
import java.util.Map;
22111 ashik.ali 10
import java.util.Set;
24976 amit.gupta 11
import java.util.stream.Collectors;
22069 ashik.ali 12
 
21577 ashik.ali 13
import javax.servlet.http.Cookie;
21561 ashik.ali 14
import javax.servlet.http.HttpServletRequest;
21577 ashik.ali 15
import javax.servlet.http.HttpServletResponse;
21561 ashik.ali 16
 
25009 amit.gupta 17
import org.apache.http.NameValuePair;
18
import org.apache.http.client.utils.URLEncodedUtils;
19
import org.apache.http.message.BasicNameValuePair;
23784 ashik.ali 20
import org.apache.logging.log4j.LogManager;
23568 govind 21
import org.apache.logging.log4j.Logger;
21561 ashik.ali 22
import org.springframework.beans.factory.annotation.Autowired;
22079 amit.gupta 23
import org.springframework.beans.factory.annotation.Value;
21555 kshitij.so 24
import org.springframework.stereotype.Controller;
21987 kshitij.so 25
import org.springframework.transaction.annotation.Transactional;
21615 kshitij.so 26
import org.springframework.ui.Model;
21555 kshitij.so 27
import org.springframework.ui.ModelMap;
28
import org.springframework.web.bind.annotation.ModelAttribute;
24383 amit.gupta 29
import org.springframework.web.bind.annotation.PostMapping;
24016 amit.gupta 30
import org.springframework.web.bind.annotation.RequestBody;
21555 kshitij.so 31
import org.springframework.web.bind.annotation.RequestMapping;
32
import org.springframework.web.bind.annotation.RequestMethod;
21561 ashik.ali 33
import org.springframework.web.bind.annotation.RequestParam;
21555 kshitij.so 34
 
25008 amit.gupta 35
import com.google.gson.Gson;
36
import com.google.gson.reflect.TypeToken;
21561 ashik.ali 37
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
24016 amit.gupta 38
import com.spice.profitmandi.common.model.Location;
21561 ashik.ali 39
import com.spice.profitmandi.common.model.ProfitMandiConstants;
25011 amit.gupta 40
import com.spice.profitmandi.common.model.ProfitMandiResponse;
25008 amit.gupta 41
import com.spice.profitmandi.common.web.client.RestClient;
24383 amit.gupta 42
import com.spice.profitmandi.dao.entity.auth.AuthUser;
22111 ashik.ali 43
import com.spice.profitmandi.dao.entity.dtr.Retailer;
23784 ashik.ali 44
import com.spice.profitmandi.dao.entity.dtr.Role;
22111 ashik.ali 45
import com.spice.profitmandi.dao.entity.dtr.User;
23271 ashik.ali 46
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
22111 ashik.ali 47
import com.spice.profitmandi.dao.entity.dtr.UserRole;
24016 amit.gupta 48
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
22111 ashik.ali 49
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
50
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
24383 amit.gupta 51
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
24016 amit.gupta 52
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22111 ashik.ali 53
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
23784 ashik.ali 54
import com.spice.profitmandi.dao.repository.dtr.RoleRepository;
22111 ashik.ali 55
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
56
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
57
import com.spice.profitmandi.dao.repository.dtr.UserRoleRepository;
24383 amit.gupta 58
import com.spice.profitmandi.service.AuthService;
24976 amit.gupta 59
import com.spice.profitmandi.service.authentication.RoleManager;
60
import com.spice.profitmandi.service.user.RetailerService;
22139 amit.gupta 61
import com.spice.profitmandi.web.model.LoginDetails;
22069 ashik.ali 62
import com.spice.profitmandi.web.util.CookiesProcessor;
22111 ashik.ali 63
import com.spice.profitmandi.web.util.GoogleTokenUtil;
21574 ashik.ali 64
import com.spice.profitmandi.web.util.MVCResponseSender;
21561 ashik.ali 65
 
21555 kshitij.so 66
@Controller
22148 amit.gupta 67
@Transactional
21555 kshitij.so 68
public class LoginController {
69
 
23568 govind 70
	private static final Logger LOGGER = LogManager.getLogger(LoginController.class);
24016 amit.gupta 71
 
21561 ashik.ali 72
	@Autowired
22927 ashik.ali 73
	private GoogleTokenUtil googleTokenUtil;
24016 amit.gupta 74
 
21574 ashik.ali 75
	@Autowired
24976 amit.gupta 76
	private RoleManager roleManager;
24984 amit.gupta 77
 
24976 amit.gupta 78
	@Autowired
22927 ashik.ali 79
	private RetailerRepository retailerRepository;
24016 amit.gupta 80
 
22111 ashik.ali 81
	@Autowired
24976 amit.gupta 82
	private RetailerService retailerService;
24984 amit.gupta 83
 
24976 amit.gupta 84
	@Autowired
22927 ashik.ali 85
	private UserRepository userRepository;
24016 amit.gupta 86
 
22111 ashik.ali 87
	@Autowired
22927 ashik.ali 88
	private UserAccountRepository userAccountRepository;
24016 amit.gupta 89
 
22111 ashik.ali 90
	@Autowired
22927 ashik.ali 91
	private UserRoleRepository userRoleRepository;
24016 amit.gupta 92
 
22111 ashik.ali 93
	@Autowired
23784 ashik.ali 94
	private RoleRepository roleRepository;
24016 amit.gupta 95
 
23784 ashik.ali 96
	@Autowired
24016 amit.gupta 97
	private FofoStoreRepository fofoStoreRepository;
98
 
99
	@Autowired
22927 ashik.ali 100
	private MVCResponseSender mvcResponseSender;
25243 amit.gupta 101
 
25008 amit.gupta 102
	@Autowired
103
	private RestClient restClient;
24016 amit.gupta 104
 
21578 ashik.ali 105
	@Autowired
22927 ashik.ali 106
	private CookiesProcessor cookiesProcessor;
22079 amit.gupta 107
 
108
	@Value("${google.api.key}")
109
	private String googleApiKey;
24016 amit.gupta 110
 
24383 amit.gupta 111
	@Autowired
112
	private AuthService authService;
113
 
114
	@Autowired
115
	private AuthRepository authRepository;
116
 
21555 kshitij.so 117
	@RequestMapping(value = "/login", method = RequestMethod.GET)
24016 amit.gupta 118
	public String loginPage(HttpServletRequest request, Model model) throws Exception {
22088 amit.gupta 119
		LOGGER.info("Context Path is {}", request.getContextPath());
24016 amit.gupta 120
		try {
23784 ashik.ali 121
			LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
22139 amit.gupta 122
			LOGGER.info("Request session is already exist, should be redirect to as per roles assigned");
23784 ashik.ali 123
			String redirectUrl = null;
24016 amit.gupta 124
 
23784 ashik.ali 125
			Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
126
			Role roleFofo = roleRepository.selectByName(RoleType.RETAILER.toString());
127
			Role roleFofoAdmin = roleRepository.selectByName(RoleType.RETAILER.toString());
24016 amit.gupta 128
			if ((fofoDetails.getRoleIds().contains(roleRetailer.getId())
129
					&& fofoDetails.getRoleIds().contains(roleFofo.getId())
130
					|| (fofoDetails.getRoleIds().contains(roleFofoAdmin.getId())))) {
23784 ashik.ali 131
				redirectUrl = "/dashboard";
132
			} else {
133
				redirectUrl = "/login";
134
			}
135
			return "redirect:" + redirectUrl;
24016 amit.gupta 136
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22079 amit.gupta 137
			model.addAttribute("googleApiKey", googleApiKey);
22086 amit.gupta 138
			model.addAttribute("appContextPath", request.getContextPath());
21577 ashik.ali 139
			return "login";
21574 ashik.ali 140
		}
21555 kshitij.so 141
	}
24016 amit.gupta 142
 
22155 amit.gupta 143
	@RequestMapping(value = "/", method = RequestMethod.GET)
24016 amit.gupta 144
	public String home() {
22860 ashik.ali 145
		return "redirect:/login";
22155 amit.gupta 146
	}
25243 amit.gupta 147
 
25008 amit.gupta 148
	@RequestMapping(value = "/mobileapp", method = RequestMethod.GET)
149
	public String mobileApp(HttpServletRequest request, Model model) throws Exception {
150
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
25243 amit.gupta 151
		if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
25008 amit.gupta 152
			model.addAttribute("authToken", getToken(fofoDetails.getEmailId()));
153
		}
154
		return "mobileapp";
155
	}
24016 amit.gupta 156
 
25008 amit.gupta 157
	private String getToken(String emailId) throws Exception {
25009 amit.gupta 158
		List<NameValuePair> nameValuePairs = new ArrayList<>();
159
		nameValuePairs.add(new BasicNameValuePair("adminToken", "ecip$stgMay2014"));
25011 amit.gupta 160
		nameValuePairs.add(new BasicNameValuePair("emailId", emailId));
25243 amit.gupta 161
		String queryString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
162
		String response = restClient.post("http://app.profitmandi.com:8080/profitmandi-web/user/admin?" + queryString,
163
				new HashMap<>(), new HashMap<>());
164
		Type t = new TypeToken<ProfitMandiResponse<Map<String, Object>>>() {
165
		}.getType();
166
		ProfitMandiResponse<Map<String, Object>> apiResponse = new Gson().fromJson(response, t);
167
		if (apiResponse.getStatusCode().equals("200")) {
168
			return (new StringBuilder((String) apiResponse.getResponse().get("token")).reverse().toString());
25008 amit.gupta 169
		} else {
25009 amit.gupta 170
			throw new Exception("Unauthorised access");
25008 amit.gupta 171
		}
25243 amit.gupta 172
 
25008 amit.gupta 173
	}
25243 amit.gupta 174
 
24976 amit.gupta 175
	@RequestMapping(value = "/login-as-partner", method = RequestMethod.GET)
176
	public String adminLogin(HttpServletRequest request, Model model, HttpServletResponse response,
177
			@RequestParam int fofoId) throws Exception {
178
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
24984 amit.gupta 179
		if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
180
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
181
			User user = userRepository.selectById(userId);
25243 amit.gupta 182
			Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
183
					.collect(Collectors.toSet());
24976 amit.gupta 184
			LoginDetails newFofoDetails = new LoginDetails();
185
			newFofoDetails.setFofoId(fofoId);
186
			newFofoDetails.setRoleIds(roleIds);
24984 amit.gupta 187
			newFofoDetails.setEmailId(user.getEmailId());
24981 amit.gupta 188
			model.addAttribute("response", true);
24983 amit.gupta 189
			this.addCookiesToResponse(newFofoDetails, request, response);
24976 amit.gupta 190
		} else {
191
			throw new ProfitMandiBusinessException("", "", "");
192
		}
24981 amit.gupta 193
		return "response";
24976 amit.gupta 194
	}
195
 
21555 kshitij.so 196
	@RequestMapping(value = "/login", method = RequestMethod.POST)
24016 amit.gupta 197
	public String login(HttpServletRequest request, HttpServletResponse response,
24383 amit.gupta 198
			@RequestParam(name = ProfitMandiConstants.TOKEN) String token,
199
			@RequestParam(name = ProfitMandiConstants.EMAIL_ID_OR_MOBILE_NUMBER, defaultValue = "") String emailIdOrMobileNumber,
200
			@RequestParam(name = "password", defaultValue = "") String password, Model model) throws Exception {
201
 
22139 amit.gupta 202
		LoginDetails fofoDetails = new LoginDetails();
23784 ashik.ali 203
		Set<Integer> roleIds = new HashSet<>();
204
		fofoDetails.setRoleIds(roleIds);
24383 amit.gupta 205
		String emailId = null;
24976 amit.gupta 206
		String name = null;
24016 amit.gupta 207
		try {
208
			// if role is retailer then FOFO_ID is retailerId else it is userid as normal
209
			// user's wont have retailer id.
24383 amit.gupta 210
			if (token == "") {
211
				if (authService.authenticate(emailIdOrMobileNumber, password)) {
212
					AuthUser authUser = authRepository.selectByEmailOrMobile(emailIdOrMobileNumber);
24976 amit.gupta 213
					if (authUser == null) {
214
						throw new ProfitMandiBusinessException("Authentication", "Email or Mobile",
215
								"Invalid Email Or Mobile");
24383 amit.gupta 216
					}
217
					emailId = authUser.getEmailId();
24976 amit.gupta 218
					name = authUser.getFirstName() + " " + authUser.getLastName();
24383 amit.gupta 219
					authUser.setLastLoginTimestamp(LocalDateTime.now());
220
					authRepository.persist(authUser);
221
				}
222
 
223
			} else {
25243 amit.gupta 224
				try {
225
					emailId = googleTokenUtil.getEmailId(token);
226
				} catch(Exception e) {
227
					//in case we cannot connect to google server.
228
					emailId = emailIdOrMobileNumber;
229
				}
24976 amit.gupta 230
				if (ProfitMandiConstants.BLOCKED_EMAILS.contains(emailId)) {
24527 amit.gupta 231
				}
24383 amit.gupta 232
			}
22139 amit.gupta 233
			fofoDetails.setEmailId(emailId);
234
			fofoDetails.setFofoId(-1);
24016 amit.gupta 235
			// fofoDetails.setFofo(false);
22111 ashik.ali 236
			User user = null;
24016 amit.gupta 237
			try {
22111 ashik.ali 238
				user = userRepository.selectByEmailId(emailId);
24016 amit.gupta 239
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23628 ashik.ali 240
				LOGGER.error("User not found with given emailId [{}]", emailId);
23203 ashik.ali 241
			}
24016 amit.gupta 242
			if (user == null) {
243
				try {
23203 ashik.ali 244
					user = userRepository.selectBySecondryEmailId(emailId);
24016 amit.gupta 245
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23203 ashik.ali 246
					LOGGER.error("User not found with given emailId", profitMandiBusinessException);
24527 amit.gupta 247
					model.addAttribute("response", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
24976 amit.gupta 248
							request.getContextPath() + "/login", "Email"));
24527 amit.gupta 249
					return "response";
23203 ashik.ali 250
				}
251
			}
24016 amit.gupta 252
			if (user != null) {
22139 amit.gupta 253
				fofoDetails.setFofoId(user.getId());
254
				try {
255
					List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
24016 amit.gupta 256
					for (int index = 0; index < userRoles.size(); index++) {
23784 ashik.ali 257
						roleIds.add(userRoles.get(index).getRoleId());
22139 amit.gupta 258
					}
23784 ashik.ali 259
					List<Role> roles = roleRepository.selectByIds(roleIds);
24016 amit.gupta 260
					for (Role role : roles) {
261
						if (role.getName().equals(RoleType.RETAILER.toString())) {
262
							UserAccount userAccounts = userAccountRepository.selectByUserIdType(user.getId(),
263
									AccountType.saholic);
23784 ashik.ali 264
							Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
265
							fofoDetails.setFofoId(retailer.getId());
24016 amit.gupta 266
							// fofoDetails.setFofo(retailer.isFofo());
23784 ashik.ali 267
						}
22166 amit.gupta 268
					}
24016 amit.gupta 269
				} catch (ProfitMandiBusinessException pmbe) {
22139 amit.gupta 270
					LOGGER.error("Data Inconsistent", pmbe);
271
				}
22111 ashik.ali 272
			}
23784 ashik.ali 273
			String redirectUrl = null;
24016 amit.gupta 274
 
25243 amit.gupta 275
			Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
276
			Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
24016 amit.gupta 277
 
25243 amit.gupta 278
			if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
23784 ashik.ali 279
				redirectUrl = "/dashboard";
25243 amit.gupta 280
				if(fofoDetails.getRoleIds().contains(roleFofo.getId())) {
281
 
282
				}
23784 ashik.ali 283
			} else {
284
				redirectUrl = "/login";
285
			}
24016 amit.gupta 286
 
25243 amit.gupta 287
			if (redirectUrl.equals("/dashboard")) {
23419 ashik.ali 288
				user.setLoginTimestamp(LocalDateTime.now());
23173 ashik.ali 289
				this.addCookiesToResponse(fofoDetails, request, response);
24016 amit.gupta 290
				LOGGER.info("Requested token email_id is valid, user login to system, shoud be redirect to {}",
291
						redirectUrl);
292
				model.addAttribute("response", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
24976 amit.gupta 293
						request.getContextPath() + redirectUrl, name));
24016 amit.gupta 294
			} else {
23173 ashik.ali 295
				LOGGER.error("Requested token email_id is not valid, please try to login");
25243 amit.gupta 296
				/**
297
				 * TODO:Amit
298
				 * This redirect should be handle.
299
				 */
24016 amit.gupta 300
				throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId(),
301
						"RTLR_1000");
23173 ashik.ali 302
			}
21578 ashik.ali 303
			return "response";
24016 amit.gupta 304
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
21568 ashik.ali 305
			LOGGER.error("Error : ", profitMandiBusinessException);
24016 amit.gupta 306
			model.addAttribute("response",
307
					mvcResponseSender.createResponseString(profitMandiBusinessException.getCode(), false, "/error"));
21578 ashik.ali 308
			return "response";
21561 ashik.ali 309
		}
21555 kshitij.so 310
	}
24976 amit.gupta 311
 
24383 amit.gupta 312
	@PostMapping(value = "/forgetPassword")
24976 amit.gupta 313
	public String forgetPasswordPage(
314
			@RequestParam(name = ProfitMandiConstants.EMAIL_ID, defaultValue = "") String emailId, Model model)
315
			throws Exception {
24383 amit.gupta 316
		LOGGER.info(emailId);
317
		authService.resetPassword(emailId);
318
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
319
		LOGGER.info("completed");
320
		return "response";
321
	}
24016 amit.gupta 322
 
323
	private void addCookiesToResponse(LoginDetails fofoDetails, HttpServletRequest request,
324
			HttpServletResponse response) {
23784 ashik.ali 325
		List<String> roleIds = new ArrayList<>();
24016 amit.gupta 326
 
327
		for (int roleId : fofoDetails.getRoleIds()) {
23784 ashik.ali 328
			roleIds.add(String.valueOf(roleId));
22139 amit.gupta 329
		}
23784 ashik.ali 330
		Cookie cookieRoleIds = new Cookie(ProfitMandiConstants.ROLE_IDS, String.join(",", roleIds));
331
		cookieRoleIds.setDomain(request.getServerName());
332
		cookieRoleIds.setPath(request.getContextPath());
24016 amit.gupta 333
 
22139 amit.gupta 334
		Cookie cookieFofoId = new Cookie(ProfitMandiConstants.FOFO_ID, String.valueOf(fofoDetails.getFofoId()));
335
		cookieFofoId.setDomain(request.getServerName());
22160 amit.gupta 336
		cookieFofoId.setPath(request.getContextPath());
24016 amit.gupta 337
 
22139 amit.gupta 338
		Cookie cookieEmailId = new Cookie(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId());
339
		cookieEmailId.setDomain(request.getServerName());
22160 amit.gupta 340
		cookieEmailId.setPath(request.getContextPath());
24984 amit.gupta 341
 
22139 amit.gupta 342
		response.addCookie(cookieFofoId);
343
		response.addCookie(cookieEmailId);
23784 ashik.ali 344
		response.addCookie(cookieRoleIds);
22139 amit.gupta 345
	}
24016 amit.gupta 346
 
22069 ashik.ali 347
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
24016 amit.gupta 348
	public String logout(HttpServletRequest request, @ModelAttribute("model") ModelMap model,
349
			HttpServletResponse response) throws Exception {
350
		try {
23419 ashik.ali 351
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
352
			User user = null;
24016 amit.gupta 353
			try {
23419 ashik.ali 354
				user = userRepository.selectByEmailId(loginDetails.getEmailId());
24016 amit.gupta 355
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23419 ashik.ali 356
				LOGGER.error("User not found with given emailId", profitMandiBusinessException);
357
			}
24016 amit.gupta 358
			if (user == null) {
23419 ashik.ali 359
				user = userRepository.selectBySecondryEmailId(loginDetails.getEmailId());
360
			}
361
			user.setLogoutTimestamp(LocalDateTime.now());
362
			userRepository.persist(user);
22069 ashik.ali 363
			cookiesProcessor.removeCookies(request, response);
364
			LOGGER.info("Logout is successfull, should be redirect to /login");
22085 amit.gupta 365
			return "redirect:/login";
24016 amit.gupta 366
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22069 ashik.ali 367
			LOGGER.info("Error occured while removing requested cookies, should be redirect to /login");
22085 amit.gupta 368
			return "redirect:/login";
22069 ashik.ali 369
		}
370
	}
24016 amit.gupta 371
 
372
	@RequestMapping(value = "/partner/location", method = RequestMethod.PUT)
373
	public String setLocation(HttpServletRequest request, Model model, @RequestBody Location location)
374
			throws Exception {
375
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
376
		boolean response = true;
24976 amit.gupta 377
		try {
378
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
379
			if (fs.getLatitude() == null) {
380
				fs.setLatitude(location.getLatitude());
381
				fs.setLongitude(location.getLongitude());
382
				fofoStoreRepository.persist(fs);
383
			}
384
			model.addAttribute("response", response);
385
		} catch (Exception e) {
24383 amit.gupta 386
			LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
387
		}
24016 amit.gupta 388
		return "response";
389
	}
21555 kshitij.so 390
}