Subversion Repositories SmartDukaan

Rev

Rev 25009 | Rev 25243 | 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;
25008 amit.gupta 101
 
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
	}
25008 amit.gupta 147
 
148
	@RequestMapping(value = "/mobileapp", method = RequestMethod.GET)
149
	public String mobileApp(HttpServletRequest request, Model model) throws Exception {
150
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
151
		if(roleManager.isAdmin(fofoDetails.getRoleIds())) {
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));
25009 amit.gupta 161
		String queryString=URLEncodedUtils.format(nameValuePairs, "UTF-8");
25011 amit.gupta 162
		String response = restClient.post("http://app.profitmandi.com:8080/profitmandi-web/user/admin?" + queryString, new HashMap<>(), new HashMap<>());
163
		Type t = new TypeToken<ProfitMandiResponse<Map<String,Object>>>() {}.getType();
164
		ProfitMandiResponse <Map<String,Object>> apiResponse = new Gson().fromJson(response, t);
165
		if(apiResponse.getStatusCode().equals("200")) {
166
			return (new StringBuilder((String)apiResponse.getResponse().get("token")).reverse().toString());
25008 amit.gupta 167
		} else {
25009 amit.gupta 168
			throw new Exception("Unauthorised access");
25008 amit.gupta 169
		}
170
 
171
	}
24976 amit.gupta 172
	@RequestMapping(value = "/login-as-partner", method = RequestMethod.GET)
173
	public String adminLogin(HttpServletRequest request, Model model, HttpServletResponse response,
174
			@RequestParam int fofoId) throws Exception {
175
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
24984 amit.gupta 176
		if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
177
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
178
			User user = userRepository.selectById(userId);
179
			Set<Integer> roleIds = userRoleRepository
180
					.selectByUserId(userId).stream()
181
					.map(x -> x.getRoleId()).collect(Collectors.toSet());
24976 amit.gupta 182
			LoginDetails newFofoDetails = new LoginDetails();
183
			newFofoDetails.setFofoId(fofoId);
184
			newFofoDetails.setRoleIds(roleIds);
24984 amit.gupta 185
			newFofoDetails.setEmailId(user.getEmailId());
24981 amit.gupta 186
			model.addAttribute("response", true);
24983 amit.gupta 187
			this.addCookiesToResponse(newFofoDetails, request, response);
24976 amit.gupta 188
		} else {
189
			throw new ProfitMandiBusinessException("", "", "");
190
		}
24981 amit.gupta 191
		return "response";
24976 amit.gupta 192
	}
193
 
21555 kshitij.so 194
	@RequestMapping(value = "/login", method = RequestMethod.POST)
24016 amit.gupta 195
	public String login(HttpServletRequest request, HttpServletResponse response,
24383 amit.gupta 196
			@RequestParam(name = ProfitMandiConstants.TOKEN) String token,
197
			@RequestParam(name = ProfitMandiConstants.EMAIL_ID_OR_MOBILE_NUMBER, defaultValue = "") String emailIdOrMobileNumber,
198
			@RequestParam(name = "password", defaultValue = "") String password, Model model) throws Exception {
199
 
22139 amit.gupta 200
		LoginDetails fofoDetails = new LoginDetails();
23784 ashik.ali 201
		Set<Integer> roleIds = new HashSet<>();
202
		fofoDetails.setRoleIds(roleIds);
24383 amit.gupta 203
		String emailId = null;
24976 amit.gupta 204
		String name = null;
24016 amit.gupta 205
		try {
206
			// if role is retailer then FOFO_ID is retailerId else it is userid as normal
207
			// user's wont have retailer id.
24383 amit.gupta 208
			if (token == "") {
209
				if (authService.authenticate(emailIdOrMobileNumber, password)) {
210
					AuthUser authUser = authRepository.selectByEmailOrMobile(emailIdOrMobileNumber);
24976 amit.gupta 211
					if (authUser == null) {
212
						throw new ProfitMandiBusinessException("Authentication", "Email or Mobile",
213
								"Invalid Email Or Mobile");
24383 amit.gupta 214
					}
215
					emailId = authUser.getEmailId();
24976 amit.gupta 216
					name = authUser.getFirstName() + " " + authUser.getLastName();
24383 amit.gupta 217
					authUser.setLastLoginTimestamp(LocalDateTime.now());
218
					authRepository.persist(authUser);
219
				}
220
 
221
			} else {
222
				emailId = googleTokenUtil.getEmailId(token);
24976 amit.gupta 223
				if (ProfitMandiConstants.BLOCKED_EMAILS.contains(emailId)) {
24527 amit.gupta 224
				}
24383 amit.gupta 225
			}
22139 amit.gupta 226
			fofoDetails.setEmailId(emailId);
227
			fofoDetails.setFofoId(-1);
24016 amit.gupta 228
			// fofoDetails.setFofo(false);
22111 ashik.ali 229
			User user = null;
24016 amit.gupta 230
			try {
22111 ashik.ali 231
				user = userRepository.selectByEmailId(emailId);
24016 amit.gupta 232
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23628 ashik.ali 233
				LOGGER.error("User not found with given emailId [{}]", emailId);
23203 ashik.ali 234
			}
24016 amit.gupta 235
			if (user == null) {
236
				try {
23203 ashik.ali 237
					user = userRepository.selectBySecondryEmailId(emailId);
24016 amit.gupta 238
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23203 ashik.ali 239
					LOGGER.error("User not found with given emailId", profitMandiBusinessException);
24527 amit.gupta 240
					model.addAttribute("response", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
24976 amit.gupta 241
							request.getContextPath() + "/login", "Email"));
24527 amit.gupta 242
					return "response";
23203 ashik.ali 243
				}
244
			}
24016 amit.gupta 245
			if (user != null) {
22139 amit.gupta 246
				fofoDetails.setFofoId(user.getId());
247
				try {
248
					List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
24016 amit.gupta 249
					for (int index = 0; index < userRoles.size(); index++) {
23784 ashik.ali 250
						roleIds.add(userRoles.get(index).getRoleId());
22139 amit.gupta 251
					}
23784 ashik.ali 252
					List<Role> roles = roleRepository.selectByIds(roleIds);
24016 amit.gupta 253
					for (Role role : roles) {
254
						if (role.getName().equals(RoleType.RETAILER.toString())) {
255
							UserAccount userAccounts = userAccountRepository.selectByUserIdType(user.getId(),
256
									AccountType.saholic);
23784 ashik.ali 257
							Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
258
							fofoDetails.setFofoId(retailer.getId());
24016 amit.gupta 259
							// fofoDetails.setFofo(retailer.isFofo());
23784 ashik.ali 260
						}
22166 amit.gupta 261
					}
24016 amit.gupta 262
				} catch (ProfitMandiBusinessException pmbe) {
22139 amit.gupta 263
					LOGGER.error("Data Inconsistent", pmbe);
264
				}
22111 ashik.ali 265
			}
23784 ashik.ali 266
			String redirectUrl = null;
24016 amit.gupta 267
 
23784 ashik.ali 268
			Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
269
			Role roleFofo = roleRepository.selectByName(RoleType.RETAILER.toString());
270
			Role roleFofoAdmin = roleRepository.selectByName(RoleType.RETAILER.toString());
24016 amit.gupta 271
 
272
			if ((fofoDetails.getRoleIds().contains(roleRetailer.getId())
273
					&& fofoDetails.getRoleIds().contains(roleFofo.getId())
274
					|| (fofoDetails.getRoleIds().contains(roleFofoAdmin.getId())))) {
23784 ashik.ali 275
				redirectUrl = "/dashboard";
276
			} else {
277
				redirectUrl = "/login";
278
			}
24016 amit.gupta 279
 
280
			if (!redirectUrl.equals("/login")) {
23419 ashik.ali 281
				user.setLoginTimestamp(LocalDateTime.now());
282
				userRepository.persist(user);
23173 ashik.ali 283
				this.addCookiesToResponse(fofoDetails, request, response);
24016 amit.gupta 284
				LOGGER.info("Requested token email_id is valid, user login to system, shoud be redirect to {}",
285
						redirectUrl);
286
				model.addAttribute("response", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
24976 amit.gupta 287
						request.getContextPath() + redirectUrl, name));
24016 amit.gupta 288
			} else {
23173 ashik.ali 289
				LOGGER.error("Requested token email_id is not valid, please try to login");
24016 amit.gupta 290
				throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId(),
291
						"RTLR_1000");
23173 ashik.ali 292
			}
21578 ashik.ali 293
			return "response";
24016 amit.gupta 294
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
21568 ashik.ali 295
			LOGGER.error("Error : ", profitMandiBusinessException);
24016 amit.gupta 296
			model.addAttribute("response",
297
					mvcResponseSender.createResponseString(profitMandiBusinessException.getCode(), false, "/error"));
21578 ashik.ali 298
			return "response";
21561 ashik.ali 299
		}
21555 kshitij.so 300
	}
24976 amit.gupta 301
 
24383 amit.gupta 302
	@PostMapping(value = "/forgetPassword")
24976 amit.gupta 303
	public String forgetPasswordPage(
304
			@RequestParam(name = ProfitMandiConstants.EMAIL_ID, defaultValue = "") String emailId, Model model)
305
			throws Exception {
24383 amit.gupta 306
		LOGGER.info(emailId);
307
		authService.resetPassword(emailId);
308
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
309
		LOGGER.info("completed");
310
		return "response";
311
	}
24016 amit.gupta 312
 
313
	private void addCookiesToResponse(LoginDetails fofoDetails, HttpServletRequest request,
314
			HttpServletResponse response) {
23784 ashik.ali 315
		List<String> roleIds = new ArrayList<>();
24016 amit.gupta 316
 
317
		for (int roleId : fofoDetails.getRoleIds()) {
23784 ashik.ali 318
			roleIds.add(String.valueOf(roleId));
22139 amit.gupta 319
		}
23784 ashik.ali 320
		Cookie cookieRoleIds = new Cookie(ProfitMandiConstants.ROLE_IDS, String.join(",", roleIds));
321
		cookieRoleIds.setDomain(request.getServerName());
322
		cookieRoleIds.setPath(request.getContextPath());
24016 amit.gupta 323
 
22139 amit.gupta 324
		Cookie cookieFofoId = new Cookie(ProfitMandiConstants.FOFO_ID, String.valueOf(fofoDetails.getFofoId()));
325
		cookieFofoId.setDomain(request.getServerName());
22160 amit.gupta 326
		cookieFofoId.setPath(request.getContextPath());
24016 amit.gupta 327
 
22139 amit.gupta 328
		Cookie cookieEmailId = new Cookie(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId());
329
		cookieEmailId.setDomain(request.getServerName());
22160 amit.gupta 330
		cookieEmailId.setPath(request.getContextPath());
24984 amit.gupta 331
 
22139 amit.gupta 332
		response.addCookie(cookieFofoId);
333
		response.addCookie(cookieEmailId);
23784 ashik.ali 334
		response.addCookie(cookieRoleIds);
22139 amit.gupta 335
	}
24016 amit.gupta 336
 
22069 ashik.ali 337
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
24016 amit.gupta 338
	public String logout(HttpServletRequest request, @ModelAttribute("model") ModelMap model,
339
			HttpServletResponse response) throws Exception {
340
		try {
23419 ashik.ali 341
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
342
			User user = null;
24016 amit.gupta 343
			try {
23419 ashik.ali 344
				user = userRepository.selectByEmailId(loginDetails.getEmailId());
24016 amit.gupta 345
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23419 ashik.ali 346
				LOGGER.error("User not found with given emailId", profitMandiBusinessException);
347
			}
24016 amit.gupta 348
			if (user == null) {
23419 ashik.ali 349
				user = userRepository.selectBySecondryEmailId(loginDetails.getEmailId());
350
			}
351
			user.setLogoutTimestamp(LocalDateTime.now());
352
			userRepository.persist(user);
22069 ashik.ali 353
			cookiesProcessor.removeCookies(request, response);
354
			LOGGER.info("Logout is successfull, should be redirect to /login");
22085 amit.gupta 355
			return "redirect:/login";
24016 amit.gupta 356
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22069 ashik.ali 357
			LOGGER.info("Error occured while removing requested cookies, should be redirect to /login");
22085 amit.gupta 358
			return "redirect:/login";
22069 ashik.ali 359
		}
360
	}
24016 amit.gupta 361
 
362
	@RequestMapping(value = "/partner/location", method = RequestMethod.PUT)
363
	public String setLocation(HttpServletRequest request, Model model, @RequestBody Location location)
364
			throws Exception {
365
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
366
		boolean response = true;
24976 amit.gupta 367
		try {
368
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
369
			if (fs.getLatitude() == null) {
370
				fs.setLatitude(location.getLatitude());
371
				fs.setLongitude(location.getLongitude());
372
				fofoStoreRepository.persist(fs);
373
			}
374
			model.addAttribute("response", response);
375
		} catch (Exception e) {
24383 amit.gupta 376
			LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
377
		}
24016 amit.gupta 378
		return "response";
379
	}
21555 kshitij.so 380
}