Subversion Repositories SmartDukaan

Rev

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