Subversion Repositories SmartDukaan

Rev

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

Rev 32559 Rev 32570
Line 21... Line 21...
21
import com.spice.profitmandi.service.user.RetailerService;
21
import com.spice.profitmandi.service.user.RetailerService;
22
import com.spice.profitmandi.web.model.LoginDetails;
22
import com.spice.profitmandi.web.model.LoginDetails;
23
import com.spice.profitmandi.web.util.CookiesProcessor;
23
import com.spice.profitmandi.web.util.CookiesProcessor;
24
import com.spice.profitmandi.web.util.GoogleTokenUtil;
24
import com.spice.profitmandi.web.util.GoogleTokenUtil;
25
import com.spice.profitmandi.web.util.MVCResponseSender;
25
import com.spice.profitmandi.web.util.MVCResponseSender;
-
 
26
import org.apache.commons.lang.StringUtils;
26
import org.apache.http.NameValuePair;
27
import org.apache.http.NameValuePair;
27
import org.apache.http.client.utils.URLEncodedUtils;
28
import org.apache.http.client.utils.URLEncodedUtils;
28
import org.apache.http.message.BasicNameValuePair;
29
import org.apache.http.message.BasicNameValuePair;
29
import org.apache.logging.log4j.LogManager;
30
import org.apache.logging.log4j.LogManager;
30
import org.apache.logging.log4j.Logger;
31
import org.apache.logging.log4j.Logger;
Line 46... Line 47...
46
 
47
 
47
@Controller
48
@Controller
48
@Transactional
49
@Transactional
49
public class LoginController {
50
public class LoginController {
50
 
51
 
51
	private static final Logger LOGGER = LogManager.getLogger(LoginController.class);
52
    private static final Logger LOGGER = LogManager.getLogger(LoginController.class);
52
 
53
 
53
	@Autowired
54
    @Autowired
54
	private GoogleTokenUtil googleTokenUtil;
55
    private GoogleTokenUtil googleTokenUtil;
55
 
56
 
56
	@Autowired
57
    @Autowired
57
	private RoleManager roleManager;
58
    private RoleManager roleManager;
58
 
59
 
59
	@Autowired
60
    @Autowired
60
	private DeviceRepository deviceRepository;
61
    private DeviceRepository deviceRepository;
61
 
62
 
62
	@Autowired
63
    @Autowired
63
	private RetailerRepository retailerRepository;
64
    private RetailerRepository retailerRepository;
64
 
65
 
65
	@Autowired
66
    @Autowired
66
	private RetailerService retailerService;
67
    private RetailerService retailerService;
67
 
68
 
68
	@Autowired
69
    @Autowired
69
	private UserRepository userRepository;
70
    private UserRepository userRepository;
70
 
71
 
71
	@Autowired
72
    @Autowired
72
	private UserAccountRepository userAccountRepository;
73
    private UserAccountRepository userAccountRepository;
73
 
74
 
74
	@Autowired
75
    @Autowired
75
	private UserRoleRepository userRoleRepository;
76
    private UserRoleRepository userRoleRepository;
76
 
77
 
77
	@Autowired
78
    @Autowired
78
	private RoleRepository roleRepository;
79
    private RoleRepository roleRepository;
79
 
80
 
80
	@Autowired
81
    @Autowired
81
	private FofoStoreRepository fofoStoreRepository;
82
    private FofoStoreRepository fofoStoreRepository;
82
 
83
 
83
	@Autowired
84
    @Autowired
84
	private MVCResponseSender mvcResponseSender;
85
    private MVCResponseSender mvcResponseSender;
85
 
86
 
86
	@Autowired
87
    @Autowired
87
	private RestClient restClient;
88
    private RestClient restClient;
88
 
89
 
89
	@Autowired
90
    @Autowired
90
	private CookiesProcessor cookiesProcessor;
91
    private CookiesProcessor cookiesProcessor;
91
 
92
 
92
	@Value("${google.api.key}")
93
    @Value("${google.api.key}")
93
	private String googleApiKey;
94
    private String googleApiKey;
94
	
95
 
95
	@Value("${app.token.url}")
96
    @Value("${app.token.url}")
96
	private String appTokenUrl;
97
    private String appTokenUrl;
97
	
98
 
98
	@Value("${angular.app.url}")
99
    @Value("${angular.app.url}")
99
	private String appUrl;
100
    private String appUrl;
100
	
101
 
101
	@Value("${admin.token}")
102
    @Value("${admin.token}")
102
	private String adminToken;
103
    private String adminToken;
103
 
104
 
104
	@Autowired
105
    @Autowired
105
	private AuthService authService;
106
    private AuthService authService;
106
 
107
 
107
	@Autowired
108
    @Autowired
108
	private AuthRepository authRepository;
109
    private AuthRepository authRepository;
109
 
110
 
110
	@RequestMapping(value = "/login", method = RequestMethod.GET)
111
    @RequestMapping(value = "/login", method = RequestMethod.GET)
111
	public String loginPage(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
112
    public String loginPage(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
112
		LOGGER.info("Context Path is {}", request.getContextPath());
113
        LOGGER.info("Context Path is {}", request.getContextPath());
113
		try {
114
        try {
114
			LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
115
            LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
115
			LOGGER.info("Request session is already exist, should be redirect to as per roles assigned");
116
            LOGGER.info("Request session is already exist, should be redirect to as per roles assigned");
116
			String redirectUrl = null;
117
            String redirectUrl = null;
117
 
118
 
118
			Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
119
            Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
119
			Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
120
            Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
120
			Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
121
            Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
121
			if (fofoDetails.getRoleIds().contains(roleFofoAdmin.getId())) {
122
            if (fofoDetails.getRoleIds().contains(roleFofoAdmin.getId())) {
122
				redirectUrl = "/dashboard";
123
                redirectUrl = "/dashboard";
123
			} else if (fofoDetails.getRoleIds().contains(roleRetailer.getId())
124
            } else if (fofoDetails.getRoleIds().contains(roleRetailer.getId())
124
					&& fofoDetails.getRoleIds().contains(roleFofo.getId())) {
125
                    && fofoDetails.getRoleIds().contains(roleFofo.getId())) {
125
				FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoDetails.getFofoId());
126
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoDetails.getFofoId());
126
				if (!fofoStore.isActive()) {
127
                if (!fofoStore.isActive()) {
127
					cookiesProcessor.removeCookies(request, response);
128
                    cookiesProcessor.removeCookies(request, response);
128
					throw new ProfitMandiBusinessException("", "", "");
129
                    throw new ProfitMandiBusinessException("", "", "");
129
				}
130
                }
130
				redirectUrl = "/dashboard";
131
                redirectUrl = "/dashboard";
131
 
132
 
132
			} else {
133
            } else {
133
				redirectUrl = "/login";
134
                redirectUrl = "/login";
134
			}
135
            }
135
			return "redirect:" + redirectUrl;
136
            return "redirect:" + redirectUrl;
136
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
137
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
137
			model.addAttribute("googleApiKey", googleApiKey);
138
            model.addAttribute("googleApiKey", googleApiKey);
138
			model.addAttribute("appContextPath", request.getContextPath());
139
            model.addAttribute("appContextPath", request.getContextPath());
139
			return "login";
140
            return "login";
140
		}
141
        }
141
	}
142
    }
142
 
143
 
143
	@RequestMapping(value = "/", method = RequestMethod.GET)
144
    @RequestMapping(value = "/", method = RequestMethod.GET)
144
	public String home() {
145
    public String home() {
145
		return "redirect:/login";
146
        return "redirect:/login";
146
	}
147
    }
147
 
148
 
148
	@RequestMapping(value = "/mobileapp", method = RequestMethod.GET)
149
    @RequestMapping(value = "/mobileapp", method = RequestMethod.GET)
149
	public String mobileApp(HttpServletRequest request, Model model, @RequestParam(defaultValue = "") String emailId)
150
    public String mobileApp(HttpServletRequest request, Model model, @RequestParam(defaultValue = "") String emailId)
150
			throws Exception {
151
            throws Exception {
151
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
152
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
152
		if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
153
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
153
			if (emailId.equals("")) {
154
            if (emailId.equals("")) {
154
				AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
155
                AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
155
				model.addAttribute("authToken", getToken(authUser.getGmailId()));
156
                model.addAttribute("authToken", getToken(authUser.getGmailId()));
156
			} else {
157
            } else {
157
				model.addAttribute("authToken", getToken(emailId));
158
                model.addAttribute("authToken", getToken(emailId));
158
				model.addAttribute("androidId", getAndroidId(emailId));
159
                model.addAttribute("androidId", getAndroidId(emailId));
159
			}
160
            }
160
		} else {
161
        } else {
161
			emailId = fofoDetails.getEmailId();
162
            emailId = fofoDetails.getEmailId();
162
			model.addAttribute("authToken", getToken(emailId));
163
            model.addAttribute("authToken", getToken(emailId));
163
			model.addAttribute("androidId", getAndroidId(emailId));
164
            model.addAttribute("androidId", getAndroidId(emailId));
164
		}
165
        }
165
		model.addAttribute("appUrl", appUrl);
166
        model.addAttribute("appUrl", appUrl);
166
		return "mobileapp";
167
        return "mobileapp";
167
	}
168
    }
168
 
169
 
169
	private String getAndroidId(String emailId) throws Exception {
170
    private String getAndroidId(String emailId) throws Exception {
170
		User user = userRepository.selectByEmailId(emailId);
171
        User user = userRepository.selectByEmailId(emailId);
171
		List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(Arrays.asList(user.getId()),
172
        List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(Arrays.asList(user.getId()),
172
				LocalDateTime.now().minusYears(2), LocalDateTime.now());
173
                LocalDateTime.now().minusYears(2), LocalDateTime.now());
173
		if (devices.size() > 0) {
174
        if (devices.size() > 0) {
174
			Device device = devices.get(0);
175
            Device device = devices.get(0);
175
			return device.getAndroidId();
176
            return device.getAndroidId();
176
		} else {
177
        } else {
177
			return "";
178
            return "";
178
		}
179
        }
179
	}
180
    }
180
 
181
 
181
	private String getToken(String emailId) throws Exception {
182
    private String getToken(String emailId) throws Exception {
182
		List<NameValuePair> nameValuePairs = new ArrayList<>();
183
        List<NameValuePair> nameValuePairs = new ArrayList<>();
183
		nameValuePairs.add(new BasicNameValuePair("adminToken", this.adminToken));
184
        nameValuePairs.add(new BasicNameValuePair("adminToken", this.adminToken));
184
		nameValuePairs.add(new BasicNameValuePair("emailId", emailId));
185
        nameValuePairs.add(new BasicNameValuePair("emailId", emailId));
185
		String queryString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
186
        String queryString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
186
		String response = restClient.post(this.appTokenUrl + queryString,
187
        String response = restClient.post(this.appTokenUrl + queryString,
187
				new HashMap<>(), new HashMap<>());
188
                new HashMap<>(), new HashMap<>());
188
		Type t = new TypeToken<ProfitMandiResponse<Map<String, Object>>>() {
189
        Type t = new TypeToken<ProfitMandiResponse<Map<String, Object>>>() {
189
		}.getType();
190
        }.getType();
190
		ProfitMandiResponse<Map<String, Object>> apiResponse = new Gson().fromJson(response, t);
191
        ProfitMandiResponse<Map<String, Object>> apiResponse = new Gson().fromJson(response, t);
191
		if (apiResponse.getStatusCode().equals("200")) {
192
        if (apiResponse.getStatusCode().equals("200")) {
192
			return (new StringBuilder((String) apiResponse.getResponse().get("token")).reverse().toString());
193
            return (new StringBuilder((String) apiResponse.getResponse().get("token")).reverse().toString());
193
		} else {
194
        } else {
194
			throw new Exception("Unauthorised access");
195
            throw new Exception("Unauthorised access");
195
		}
196
        }
196
 
197
 
197
	}
198
    }
198
 
199
 
199
	@RequestMapping(value = "/login-as-partner", method = RequestMethod.GET)
200
    @RequestMapping(value = "/login-as-partner", method = RequestMethod.GET)
200
	public String adminLogin(HttpServletRequest request, Model model, HttpServletResponse response,
201
    public String adminLogin(HttpServletRequest request, Model model, HttpServletResponse response,
201
			@RequestParam int fofoId) throws Exception {
202
                             @RequestParam int fofoId) throws Exception {
202
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
203
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
203
		if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
204
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
204
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
205
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
205
			User user = userRepository.selectById(userId);
206
            User user = userRepository.selectById(userId);
206
			Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
207
            Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
207
					.collect(Collectors.toSet());
208
                    .collect(Collectors.toSet());
208
			LoginDetails newFofoDetails = new LoginDetails();
209
            LoginDetails newFofoDetails = new LoginDetails();
209
			newFofoDetails.setFofoId(fofoId);
210
            newFofoDetails.setFofoId(fofoId);
210
			newFofoDetails.setRoleIds(roleIds);
211
            newFofoDetails.setRoleIds(roleIds);
211
			newFofoDetails.setEmailId(user.getEmailId());
212
            newFofoDetails.setEmailId(user.getEmailId());
212
			model.addAttribute("response1", true);
213
            model.addAttribute("response1", true);
213
			this.addCookiesToResponse(newFofoDetails, request, response);
214
            this.addCookiesToResponse(newFofoDetails, request, response);
214
		} else {
215
        } else {
215
			throw new ProfitMandiBusinessException("", "", "");
216
            throw new ProfitMandiBusinessException("", "", "");
216
		}
217
        }
217
		return "response";
218
        return "response";
218
	}
219
    }
219
	
220
 
220
	@RequestMapping(value = "/login-as-partner-readonly", method = RequestMethod.GET)
221
    @RequestMapping(value = "/login-as-partner-readonly", method = RequestMethod.GET)
221
	public String readonlyLogin(HttpServletRequest request, Model model, HttpServletResponse response,
222
    public String readonlyLogin(HttpServletRequest request, Model model, HttpServletResponse response,
222
			@RequestParam int fofoId) throws Exception {
223
                                @RequestParam int fofoId) throws Exception {
223
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
224
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
224
		if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
225
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
225
			int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
226
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
226
			User user = userRepository.selectById(userId);
227
            User user = userRepository.selectById(userId);
227
			Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
228
            Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
228
					.collect(Collectors.toSet());
229
                    .collect(Collectors.toSet());
229
			LoginDetails newFofoDetails = new LoginDetails();
230
            LoginDetails newFofoDetails = new LoginDetails();
230
			newFofoDetails.setFofoId(fofoId);
231
            newFofoDetails.setFofoId(fofoId);
231
			newFofoDetails.setRoleIds(roleIds);
232
            newFofoDetails.setRoleIds(roleIds);
232
			newFofoDetails.setEmailId(user.getEmailId());
233
            newFofoDetails.setEmailId(user.getEmailId());
233
			newFofoDetails.setReadOnly(true);
234
            newFofoDetails.setReadOnly(true);
234
			model.addAttribute("response1", true);
235
            model.addAttribute("response1", true);
235
			this.addCookiesToResponse(newFofoDetails, request, response);
236
            this.addCookiesToResponse(newFofoDetails, request, response);
236
		} else {
237
        } else {
237
			throw new ProfitMandiBusinessException("", "", "");
238
            throw new ProfitMandiBusinessException("", "", "");
238
		}
239
        }
239
		return "response";
240
        return "response";
240
	}
241
    }
241
 
242
 
242
	@RequestMapping(value = "/login", method = RequestMethod.POST)
243
    @RequestMapping(value = "/login", method = RequestMethod.POST)
243
	public String login(HttpServletRequest request, HttpServletResponse response,
244
    public String login(HttpServletRequest request, HttpServletResponse response,
244
			@RequestParam(name = ProfitMandiConstants.TOKEN) String token,
245
                        @RequestParam(name = ProfitMandiConstants.TOKEN) String token,
245
			@RequestParam(name = ProfitMandiConstants.EMAIL_ID_OR_MOBILE_NUMBER, defaultValue = "") String emailIdOrMobileNumber,
246
                        @RequestParam(name = ProfitMandiConstants.EMAIL_ID_OR_MOBILE_NUMBER, defaultValue = "") String emailIdOrMobileNumber,
246
			@RequestParam(name = "password", defaultValue = "") String password, Model model) throws Exception {
247
                        @RequestParam(name = "password", defaultValue = "") String password, Model model) throws Exception {
247
 
248
 
248
		LoginDetails fofoDetails = new LoginDetails();
249
        LoginDetails fofoDetails = new LoginDetails();
249
		Set<Integer> roleIds = new HashSet<>();
250
        Set<Integer> roleIds = new HashSet<>();
250
		fofoDetails.setRoleIds(roleIds);
251
        fofoDetails.setRoleIds(roleIds);
251
		String emailId = null;
252
        String emailId = null;
252
		String name = null;
253
        String name = null;
253
		try {
254
        try {
254
			// if role is retailer then FOFO_ID is retailerId else it is userid as normal
255
            // if role is retailer then FOFO_ID is retailerId else it is userid as normal
255
			// user's wont have retailer id.
256
            // user's wont have retailer id.
256
			if (token == "") {
257
            if (StringUtils.isNotEmpty(token)) {
257
				if (authService.authenticate(emailIdOrMobileNumber, password)) {
258
                if (authService.authenticate(emailIdOrMobileNumber, password)) {
258
					AuthUser authUser = authRepository.selectByEmailOrMobile(emailIdOrMobileNumber);
259
                    AuthUser authUser = authRepository.selectByEmailOrMobile(emailIdOrMobileNumber);
259
					if (authUser == null) {
260
                    if (authUser == null) {
260
						throw new ProfitMandiBusinessException("Authentication", "Email or Mobile",
261
                        throw new ProfitMandiBusinessException("Authentication", "Email or Mobile",
261
								"Invalid Email Or Mobile");
262
                                "Invalid Email Or Mobile");
262
					}
263
                    }
263
					emailId = authUser.getEmailId();
264
                    emailId = authUser.getEmailId();
264
					name = authUser.getFirstName() + " " + authUser.getLastName();
265
                    name = authUser.getFirstName() + " " + authUser.getLastName();
265
					authUser.setLastLoginTimestamp(LocalDateTime.now());
266
                    authUser.setLastLoginTimestamp(LocalDateTime.now());
266
					authRepository.persist(authUser);
267
                }
267
				}
268
 
268
 
269
            } else {
269
			} else {
270
                try {
270
				try {
271
                    emailId = googleTokenUtil.getEmailId(token);
271
					emailId = googleTokenUtil.getEmailId(token);
272
                } catch (Exception e) {
272
				} catch (Exception e) {
273
                    // in case we cannot connect to google server.
273
					// in case we cannot connect to google server.
274
                    emailId = emailIdOrMobileNumber;
274
					emailId = emailIdOrMobileNumber;
275
                }
275
				}
276
            }
276
			}
277
            fofoDetails.setEmailId(emailId);
277
			fofoDetails.setEmailId(emailId);
278
            fofoDetails.setFofoId(-1);
278
			fofoDetails.setFofoId(-1);
279
            // fofoDetails.setFofo(false);
279
			// fofoDetails.setFofo(false);
280
            User user = null;
280
			User user = null;
281
            try {
281
			try {
282
                user = userRepository.selectByEmailId(emailId);
282
				user = userRepository.selectByEmailId(emailId);
283
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
283
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
284
                LOGGER.error("User not found with given emailId [{}]", emailId);
284
				LOGGER.error("User not found with given emailId [{}]", emailId);
285
            }
285
			}
286
            if (user == null) {
286
			if (user == null) {
287
                try {
287
				try {
288
                    user = userRepository.selectBySecondryEmailId(emailId);
288
					user = userRepository.selectBySecondryEmailId(emailId);
289
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
289
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
290
                    LOGGER.error("User not found with given emailId", profitMandiBusinessException);
290
					LOGGER.error("User not found with given emailId", profitMandiBusinessException);
291
                    model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
291
					model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
292
                            request.getContextPath() + "/login", "Email"));
292
							request.getContextPath() + "/login", "Email"));
293
                    return "response";
293
					return "response";
294
                }
294
				}
295
            }
295
			}
296
            if (user != null) {
296
			if (user != null) {
297
                fofoDetails.setFofoId(user.getId());
297
				fofoDetails.setFofoId(user.getId());
298
                try {
298
				try {
299
                    List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
299
					List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
300
                    for (int index = 0; index < userRoles.size(); index++) {
300
					for (int index = 0; index < userRoles.size(); index++) {
301
                        roleIds.add(userRoles.get(index).getRoleId());
301
						roleIds.add(userRoles.get(index).getRoleId());
302
                    }
302
					}
303
                    List<Role> roles = roleRepository.selectByIds(roleIds);
303
					List<Role> roles = roleRepository.selectByIds(roleIds);
304
                    for (Role role : roles) {
304
					for (Role role : roles) {
305
                        if (role.getName().equals(RoleType.RETAILER.toString())) {
305
						if (role.getName().equals(RoleType.RETAILER.toString())) {
306
                            UserAccount userAccounts = userAccountRepository.selectByUserIdType(user.getId(),
306
							UserAccount userAccounts = userAccountRepository.selectByUserIdType(user.getId(),
307
                                    AccountType.saholic);
307
									AccountType.saholic);
308
                            Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
308
							Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
309
                            fofoDetails.setFofoId(retailer.getId());
309
							fofoDetails.setFofoId(retailer.getId());
310
                            // fofoDetails.setFofo(retailer.isFofo());
310
							// fofoDetails.setFofo(retailer.isFofo());
311
                        }
311
						}
312
                    }
312
					}
313
                } catch (ProfitMandiBusinessException pmbe) {
313
				} catch (ProfitMandiBusinessException pmbe) {
314
                    LOGGER.error("Data Inconsistent", pmbe);
314
					LOGGER.error("Data Inconsistent", pmbe);
315
                }
315
				}
316
            }
316
			}
317
            String redirectUrl = null;
317
			String redirectUrl = null;
318
 
318
 
319
            Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
319
			Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
320
            Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
320
			Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
321
 
321
 
322
            if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
322
			if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
323
                redirectUrl = "/dashboard";
323
				redirectUrl = "/dashboard";
324
                if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
324
				if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
325
 
325
 
326
                }
326
				}
327
            } else {
327
			} else {
328
                redirectUrl = "/login";
328
				redirectUrl = "/login";
329
            }
329
			}
330
 
330
 
331
            if (redirectUrl.equals("/dashboard")) {
331
			if (redirectUrl.equals("/dashboard")) {
332
                user.setLoginTimestamp(LocalDateTime.now());
332
				user.setLoginTimestamp(LocalDateTime.now());
333
                this.addCookiesToResponse(fofoDetails, request, response);
333
				this.addCookiesToResponse(fofoDetails, request, response);
334
                LOGGER.info("Requested token email_id is valid, user login to system, shoud be redirect to {}",
334
				LOGGER.info("Requested token email_id is valid, user login to system, shoud be redirect to {}",
335
                        redirectUrl);
335
						redirectUrl);
336
                model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
336
				model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
337
                        request.getContextPath() + redirectUrl, name));
337
						request.getContextPath() + redirectUrl, name));
338
            } else {
338
			} else {
339
                LOGGER.error("Requested token email_id is not valid, please try to login");
339
				LOGGER.error("Requested token email_id is not valid, please try to login");
340
                /**
340
				/**
341
                 * TODO:Amit This redirect should be handle.
341
				 * TODO:Amit This redirect should be handle.
342
                 */
342
				 */
343
                throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId(),
343
				throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId(),
344
                        "RTLR_1000");
344
						"RTLR_1000");
345
            }
345
			}
346
            return "response";
346
			return "response";
347
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
347
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
348
            LOGGER.error("Error : ", profitMandiBusinessException);
348
			LOGGER.error("Error : ", profitMandiBusinessException);
349
            model.addAttribute("response1",
349
			model.addAttribute("response1",
350
                    mvcResponseSender.createResponseString(profitMandiBusinessException.getCode(), false, "/error"));
350
					mvcResponseSender.createResponseString(profitMandiBusinessException.getCode(), false, "/error"));
351
            return "response";
351
			return "response";
352
        } catch (Exception e) {
352
		} catch (Exception e) {
353
            e.printStackTrace();
353
			e.printStackTrace();
354
            model.addAttribute("response1",
354
			model.addAttribute("response1",
355
                    mvcResponseSender.createResponseString(
355
					mvcResponseSender.createResponseString(
356
                            "You are not authorised! " + "Please contact the team if you feel this is incorrect", false,
356
							"You are not authorised! " + "Please contact the team if you feel this is incorrect", false,
357
                            "/error"));
357
							"/error"));
358
            return "response";
358
			return "response";
359
        }
359
		}
360
    }
360
	}
361
 
361
 
362
    @PostMapping(value = "/forgetPassword")
362
	@PostMapping(value = "/forgetPassword")
363
    public String forgetPasswordPage(
363
	public String forgetPasswordPage(
364
            @RequestParam(name = ProfitMandiConstants.EMAIL_ID, defaultValue = "") String emailId, Model model)
364
			@RequestParam(name = ProfitMandiConstants.EMAIL_ID, defaultValue = "") String emailId, Model model)
365
            throws Exception {
365
			throws Exception {
366
        LOGGER.info(emailId);
366
		LOGGER.info(emailId);
367
        authService.resetPassword(emailId);
367
		authService.resetPassword(emailId);
368
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
368
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
369
        LOGGER.info("completed");
369
		LOGGER.info("completed");
370
        return "response";
370
		return "response";
371
    }
371
	}
372
 
372
 
373
    private void addCookiesToResponse(LoginDetails fofoDetails, HttpServletRequest request,
373
	private void addCookiesToResponse(LoginDetails fofoDetails, HttpServletRequest request,
374
                                      HttpServletResponse response) {
374
			HttpServletResponse response) {
375
        List<String> roleIds = new ArrayList<>();
375
		List<String> roleIds = new ArrayList<>();
376
 
376
 
377
        for (int roleId : fofoDetails.getRoleIds()) {
377
		for (int roleId : fofoDetails.getRoleIds()) {
378
            roleIds.add(String.valueOf(roleId));
378
			roleIds.add(String.valueOf(roleId));
379
        }
379
		}
380
        Cookie cookieRoleIds = new Cookie(ProfitMandiConstants.ROLE_IDS, String.join("-", roleIds));
380
		Cookie cookieRoleIds = new Cookie(ProfitMandiConstants.ROLE_IDS, String.join("-", roleIds));
381
        cookieRoleIds.setDomain(request.getServerName());
381
		cookieRoleIds.setDomain(request.getServerName());
382
        cookieRoleIds.setPath(request.getContextPath());
382
		cookieRoleIds.setPath(request.getContextPath());
383
 
383
 
384
        Cookie cookieFofoId = new Cookie(ProfitMandiConstants.FOFO_ID, String.valueOf(fofoDetails.getFofoId()));
384
		Cookie cookieFofoId = new Cookie(ProfitMandiConstants.FOFO_ID, String.valueOf(fofoDetails.getFofoId()));
385
        cookieFofoId.setDomain(request.getServerName());
385
		cookieFofoId.setDomain(request.getServerName());
386
        cookieFofoId.setPath(request.getContextPath());
386
		cookieFofoId.setPath(request.getContextPath());
387
 
387
 
388
        Cookie cookieEmailId = new Cookie(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId());
388
		Cookie cookieEmailId = new Cookie(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId());
389
        cookieEmailId.setDomain(request.getServerName());
389
		cookieEmailId.setDomain(request.getServerName());
390
        cookieEmailId.setPath(request.getContextPath());
390
		cookieEmailId.setPath(request.getContextPath());
391
 
391
		
392
        Cookie cookieReadOnly = new Cookie(ProfitMandiConstants.READONLY_KEY, fofoDetails.isReadOnly() + "");
392
		Cookie cookieReadOnly = new Cookie(ProfitMandiConstants.READONLY_KEY, fofoDetails.isReadOnly() + "");
393
        cookieReadOnly.setDomain(request.getServerName());
393
		cookieReadOnly.setDomain(request.getServerName());
394
        cookieReadOnly.setPath(request.getContextPath());
394
		cookieReadOnly.setPath(request.getContextPath());
395
 
395
 
396
        response.addCookie(cookieFofoId);
396
		response.addCookie(cookieFofoId);
397
        response.addCookie(cookieEmailId);
397
		response.addCookie(cookieEmailId);
398
        response.addCookie(cookieRoleIds);
398
		response.addCookie(cookieRoleIds);
399
        response.addCookie(cookieReadOnly);
399
		response.addCookie(cookieReadOnly);
400
    }
400
	}
401
 
401
 
402
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
402
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
403
    public String logout(HttpServletRequest request, @ModelAttribute("model") ModelMap model,
403
	public String logout(HttpServletRequest request, @ModelAttribute("model") ModelMap model,
404
                         HttpServletResponse response) throws Exception {
404
			HttpServletResponse response) throws Exception {
405
        try {
405
		try {
406
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
406
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
407
            User user = null;
407
			User user = null;
408
            try {
408
			try {
409
                user = userRepository.selectByEmailId(loginDetails.getEmailId());
409
				user = userRepository.selectByEmailId(loginDetails.getEmailId());
410
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
410
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
411
                LOGGER.error("User not found with given emailId", profitMandiBusinessException);
411
				LOGGER.error("User not found with given emailId", profitMandiBusinessException);
412
            }
412
			}
413
            if (user == null) {
413
			if (user == null) {
414
                user = userRepository.selectBySecondryEmailId(loginDetails.getEmailId());
414
				user = userRepository.selectBySecondryEmailId(loginDetails.getEmailId());
415
            }
415
			}
416
            user.setLogoutTimestamp(LocalDateTime.now());
416
			user.setLogoutTimestamp(LocalDateTime.now());
417
            userRepository.persist(user);
417
			userRepository.persist(user);
418
            cookiesProcessor.removeCookies(request, response);
418
			cookiesProcessor.removeCookies(request, response);
419
            LOGGER.info("Logout is successfull, should be redirect to /login");
419
			LOGGER.info("Logout is successfull, should be redirect to /login");
420
            return "redirect:/login";
420
			return "redirect:/login";
421
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
421
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
422
            LOGGER.info("Error occured while removing requested cookies, should be redirect to /login");
422
			LOGGER.info("Error occured while removing requested cookies, should be redirect to /login");
423
            return "redirect:/login";
423
			return "redirect:/login";
424
        }
424
		}
425
    }
425
	}
426
 
426
 
427
    @RequestMapping(value = "/partner/location", method = RequestMethod.PUT)
427
	@RequestMapping(value = "/partner/location", method = RequestMethod.PUT)
428
    public String setLocation(HttpServletRequest request, Model model, @RequestBody Location location)
428
	public String setLocation(HttpServletRequest request, Model model, @RequestBody Location location)
429
            throws Exception {
429
			throws Exception {
430
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
430
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
431
        boolean response = true;
431
		boolean response = true;
432
        try {
432
		try {
433
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
433
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
434
            if (fs.getLatitude() == null) {
434
			if (fs.getLatitude() == null) {
435
                fs.setLatitude(location.getLatitude());
435
				fs.setLatitude(location.getLatitude());
436
                fs.setLongitude(location.getLongitude());
436
				fs.setLongitude(location.getLongitude());
437
            }
437
			}
438
            model.addAttribute("response1", response);
438
			model.addAttribute("response1", response);
439
        } catch (Exception e) {
439
		} catch (Exception e) {
440
            LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
440
			LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
441
        }
441
		}
442
        return "response";
442
		return "response";
443
    }
443
	}
-
 
444
}
444
}