Subversion Repositories SmartDukaan

Rev

Rev 37924 | 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 com.google.gson.Gson;
4
import com.google.gson.reflect.TypeToken;
21561 ashik.ali 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
24016 amit.gupta 6
import com.spice.profitmandi.common.model.Location;
21561 ashik.ali 7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
25011 amit.gupta 8
import com.spice.profitmandi.common.model.ProfitMandiResponse;
25008 amit.gupta 9
import com.spice.profitmandi.common.web.client.RestClient;
24383 amit.gupta 10
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30299 amit.gupta 11
import com.spice.profitmandi.dao.entity.dtr.*;
24016 amit.gupta 12
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
25303 amit.gupta 13
import com.spice.profitmandi.dao.entity.user.Device;
22111 ashik.ali 14
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
15
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
24383 amit.gupta 16
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25303 amit.gupta 17
import com.spice.profitmandi.dao.repository.catalog.DeviceRepository;
37780 amit 18
import com.spice.profitmandi.dao.repository.cs.DemoPartnerAccessService;
30299 amit.gupta 19
import com.spice.profitmandi.dao.repository.dtr.*;
24383 amit.gupta 20
import com.spice.profitmandi.service.AuthService;
24976 amit.gupta 21
import com.spice.profitmandi.service.authentication.RoleManager;
22
import com.spice.profitmandi.service.user.RetailerService;
34785 vikas.jang 23
import com.spice.profitmandi.service.user.UserService;
22139 amit.gupta 24
import com.spice.profitmandi.web.model.LoginDetails;
22069 ashik.ali 25
import com.spice.profitmandi.web.util.CookiesProcessor;
22111 ashik.ali 26
import com.spice.profitmandi.web.util.GoogleTokenUtil;
21574 ashik.ali 27
import com.spice.profitmandi.web.util.MVCResponseSender;
32570 amit.gupta 28
import org.apache.commons.lang.StringUtils;
30299 amit.gupta 29
import org.apache.http.NameValuePair;
30
import org.apache.http.client.utils.URLEncodedUtils;
31
import org.apache.http.message.BasicNameValuePair;
32
import org.apache.logging.log4j.LogManager;
33
import org.apache.logging.log4j.Logger;
34
import org.springframework.beans.factory.annotation.Autowired;
35
import org.springframework.beans.factory.annotation.Value;
36
import org.springframework.stereotype.Controller;
37
import org.springframework.ui.Model;
38
import org.springframework.ui.ModelMap;
39
import org.springframework.web.bind.annotation.*;
21561 ashik.ali 40
 
30299 amit.gupta 41
import javax.servlet.http.Cookie;
42
import javax.servlet.http.HttpServletRequest;
43
import javax.servlet.http.HttpServletResponse;
35458 amit 44
import org.springframework.transaction.annotation.Transactional;
30299 amit.gupta 45
import java.lang.reflect.Type;
46
import java.time.LocalDateTime;
47
import java.util.*;
48
import java.util.stream.Collectors;
49
 
21555 kshitij.so 50
@Controller
35458 amit 51
@Transactional(rollbackFor = Throwable.class)
21555 kshitij.so 52
public class LoginController {
53
 
32570 amit.gupta 54
    private static final Logger LOGGER = LogManager.getLogger(LoginController.class);
24016 amit.gupta 55
 
32570 amit.gupta 56
    @Autowired
57
    private GoogleTokenUtil googleTokenUtil;
24016 amit.gupta 58
 
32570 amit.gupta 59
    @Autowired
60
    private RoleManager roleManager;
26449 amit.gupta 61
 
32570 amit.gupta 62
    @Autowired
63
    private DeviceRepository deviceRepository;
24984 amit.gupta 64
 
32570 amit.gupta 65
    @Autowired
66
    private RetailerRepository retailerRepository;
24016 amit.gupta 67
 
32570 amit.gupta 68
    @Autowired
69
    private RetailerService retailerService;
24984 amit.gupta 70
 
32570 amit.gupta 71
    @Autowired
72
    private UserRepository userRepository;
24016 amit.gupta 73
 
32570 amit.gupta 74
    @Autowired
75
    private UserAccountRepository userAccountRepository;
24016 amit.gupta 76
 
32570 amit.gupta 77
    @Autowired
78
    private UserRoleRepository userRoleRepository;
24016 amit.gupta 79
 
32570 amit.gupta 80
    @Autowired
81
    private RoleRepository roleRepository;
24016 amit.gupta 82
 
32570 amit.gupta 83
    @Autowired
84
    private FofoStoreRepository fofoStoreRepository;
24016 amit.gupta 85
 
32570 amit.gupta 86
    @Autowired
87
    private MVCResponseSender mvcResponseSender;
25243 amit.gupta 88
 
32570 amit.gupta 89
    @Autowired
90
    private RestClient restClient;
24016 amit.gupta 91
 
32570 amit.gupta 92
    @Autowired
93
    private CookiesProcessor cookiesProcessor;
22079 amit.gupta 94
 
32570 amit.gupta 95
    @Value("${google.api.key}")
96
    private String googleApiKey;
24016 amit.gupta 97
 
32570 amit.gupta 98
    @Value("${app.token.url}")
99
    private String appTokenUrl;
24383 amit.gupta 100
 
32570 amit.gupta 101
    @Value("${angular.app.url}")
102
    private String appUrl;
24383 amit.gupta 103
 
36369 vikas 104
    @Value("${react.app.url}")
105
    private String reactAppUrl;
106
 
32570 amit.gupta 107
    @Value("${admin.token}")
108
    private String adminToken;
24016 amit.gupta 109
 
32570 amit.gupta 110
    @Autowired
111
    private AuthService authService;
26449 amit.gupta 112
 
32570 amit.gupta 113
    @Autowired
34785 vikas.jang 114
    private UserService userService;
115
 
116
    @Autowired
32570 amit.gupta 117
    private AuthRepository authRepository;
24016 amit.gupta 118
 
37780 amit 119
    @Autowired
120
    private DemoPartnerAccessService demoPartnerAccessService;
121
 
32570 amit.gupta 122
    @RequestMapping(value = "/login", method = RequestMethod.GET)
123
    public String loginPage(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
124
        LOGGER.info("Context Path is {}", request.getContextPath());
125
        try {
126
            LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
127
            LOGGER.info("Request session is already exist, should be redirect to as per roles assigned");
128
            String redirectUrl = null;
25243 amit.gupta 129
 
32570 amit.gupta 130
            Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
131
            Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
132
            Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
133
            if (fofoDetails.getRoleIds().contains(roleFofoAdmin.getId())) {
134
                redirectUrl = "/dashboard";
135
            } else if (fofoDetails.getRoleIds().contains(roleRetailer.getId())
136
                    && fofoDetails.getRoleIds().contains(roleFofo.getId())) {
137
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoDetails.getFofoId());
138
                if (!fofoStore.isActive()) {
139
                    cookiesProcessor.removeCookies(request, response);
140
                    throw new ProfitMandiBusinessException("", "", "");
141
                }
142
                redirectUrl = "/dashboard";
24016 amit.gupta 143
 
32570 amit.gupta 144
            } else {
145
                redirectUrl = "/login";
146
            }
147
            return "redirect:" + redirectUrl;
148
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
149
            model.addAttribute("googleApiKey", googleApiKey);
150
            model.addAttribute("appContextPath", request.getContextPath());
151
            return "login";
152
        }
153
    }
25303 amit.gupta 154
 
32570 amit.gupta 155
    @RequestMapping(value = "/", method = RequestMethod.GET)
156
    public String home() {
157
        return "redirect:/login";
158
    }
25243 amit.gupta 159
 
32570 amit.gupta 160
    @RequestMapping(value = "/mobileapp", method = RequestMethod.GET)
36369 vikas 161
    public String mobileApp(HttpServletRequest request, Model model, @RequestParam(defaultValue = "") String emailId, @RequestParam(defaultValue = "") String appType)
32570 amit.gupta 162
            throws Exception {
163
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
164
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
32574 amit.gupta 165
            if (StringUtils.isEmpty(emailId)) {
32570 amit.gupta 166
                AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
167
                model.addAttribute("authToken", getToken(authUser.getGmailId()));
168
            } else {
37780 amit 169
                validateSalesPartnerAccess(fofoDetails.getEmailId(), emailId);
32570 amit.gupta 170
                model.addAttribute("authToken", getToken(emailId));
171
                model.addAttribute("androidId", getAndroidId(emailId));
172
            }
173
        } else {
174
            emailId = fofoDetails.getEmailId();
175
            model.addAttribute("authToken", getToken(emailId));
176
            model.addAttribute("androidId", getAndroidId(emailId));
177
        }
34300 ranu 178
        model.addAttribute("internal", true);
37924 vikas 179
        // Unlike "internal" (always true), "staff" marks sessions opened by internal users, incl. on a partner's behalf.
180
        model.addAttribute("staff", roleManager.isAdmin(fofoDetails.getRoleIds()));
36370 vikas 181
        if (appType.equals("react")) {
182
            model.addAttribute("appUrl", reactAppUrl);
183
        } else {
36369 vikas 184
            model.addAttribute("appUrl", appUrl);
185
        }
32570 amit.gupta 186
        return "mobileapp";
187
    }
25243 amit.gupta 188
 
37780 amit 189
    // Sales position holders may only take a partner's app token for their position or demo partners.
190
    private void validateSalesPartnerAccess(String callerEmail, String partnerEmail) throws Exception {
191
        AuthUser authUser = authRepository.selectByEmailOrMobile(callerEmail);
192
        if (authUser == null || !demoPartnerAccessService.isSalesUser(authUser.getId())) {
193
            return;
194
        }
195
        User partnerUser = userRepository.selectByEmailId(partnerEmail);
196
        int fofoId = userAccountRepository.selectRetailerIdByUserId(partnerUser.getId());
197
        if (!demoPartnerAccessService.isAllowed(authUser.getId(), fofoId)) {
198
            throw new ProfitMandiBusinessException("emailId", partnerEmail, "Partner is not mapped to you by position or demo access");
199
        }
200
    }
201
 
32570 amit.gupta 202
    private String getAndroidId(String emailId) throws Exception {
203
        User user = userRepository.selectByEmailId(emailId);
204
        List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(Arrays.asList(user.getId()),
205
                LocalDateTime.now().minusYears(2), LocalDateTime.now());
206
        if (devices.size() > 0) {
207
            Device device = devices.get(0);
208
            return device.getAndroidId();
209
        } else {
210
            return "";
211
        }
212
    }
24976 amit.gupta 213
 
32570 amit.gupta 214
    private String getToken(String emailId) throws Exception {
215
        List<NameValuePair> nameValuePairs = new ArrayList<>();
216
        nameValuePairs.add(new BasicNameValuePair("adminToken", this.adminToken));
217
        nameValuePairs.add(new BasicNameValuePair("emailId", emailId));
218
        String queryString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
219
        String response = restClient.post(this.appTokenUrl + queryString,
220
                new HashMap<>(), new HashMap<>());
221
        Type t = new TypeToken<ProfitMandiResponse<Map<String, Object>>>() {
222
        }.getType();
223
        ProfitMandiResponse<Map<String, Object>> apiResponse = new Gson().fromJson(response, t);
224
        if (apiResponse.getStatusCode().equals("200")) {
225
            return (new StringBuilder((String) apiResponse.getResponse().get("token")).reverse().toString());
226
        } else {
227
            throw new Exception("Unauthorised access");
228
        }
24383 amit.gupta 229
 
32570 amit.gupta 230
    }
24383 amit.gupta 231
 
32570 amit.gupta 232
    @RequestMapping(value = "/login-as-partner", method = RequestMethod.GET)
233
    public String adminLogin(HttpServletRequest request, Model model, HttpServletResponse response,
234
                             @RequestParam int fofoId) throws Exception {
235
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
236
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
237
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
238
            User user = userRepository.selectById(userId);
239
            Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
240
                    .collect(Collectors.toSet());
241
            LoginDetails newFofoDetails = new LoginDetails();
242
            newFofoDetails.setFofoId(fofoId);
243
            newFofoDetails.setRoleIds(roleIds);
244
            newFofoDetails.setEmailId(user.getEmailId());
245
            model.addAttribute("response1", true);
246
            this.addCookiesToResponse(newFofoDetails, request, response);
247
        } else {
248
            throw new ProfitMandiBusinessException("", "", "");
249
        }
250
        return "response";
251
    }
24016 amit.gupta 252
 
32570 amit.gupta 253
    @RequestMapping(value = "/login-as-partner-readonly", method = RequestMethod.GET)
254
    public String readonlyLogin(HttpServletRequest request, Model model, HttpServletResponse response,
255
                                @RequestParam int fofoId) throws Exception {
256
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
257
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
37780 amit 258
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
259
            if (authUser == null || !demoPartnerAccessService.isAllowed(authUser.getId(), fofoId)) {
260
                throw new ProfitMandiBusinessException("fofoId", fofoId, "Partner is not mapped to you by position or demo access");
261
            }
32570 amit.gupta 262
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
263
            User user = userRepository.selectById(userId);
264
            Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
265
                    .collect(Collectors.toSet());
266
            LoginDetails newFofoDetails = new LoginDetails();
267
            newFofoDetails.setFofoId(fofoId);
268
            newFofoDetails.setRoleIds(roleIds);
269
            newFofoDetails.setEmailId(user.getEmailId());
270
            newFofoDetails.setReadOnly(true);
271
            model.addAttribute("response1", true);
272
            this.addCookiesToResponse(newFofoDetails, request, response);
273
        } else {
274
            throw new ProfitMandiBusinessException("", "", "");
275
        }
276
        return "response";
277
    }
24016 amit.gupta 278
 
32570 amit.gupta 279
    @RequestMapping(value = "/login", method = RequestMethod.POST)
280
    public String login(HttpServletRequest request, HttpServletResponse response,
281
                        @RequestParam(name = ProfitMandiConstants.TOKEN) String token,
282
                        @RequestParam(name = ProfitMandiConstants.EMAIL_ID_OR_MOBILE_NUMBER, defaultValue = "") String emailIdOrMobileNumber,
283
                        @RequestParam(name = "password", defaultValue = "") String password, Model model) throws Exception {
25275 amit.gupta 284
 
32570 amit.gupta 285
        LoginDetails fofoDetails = new LoginDetails();
286
        Set<Integer> roleIds = new HashSet<>();
287
        fofoDetails.setRoleIds(roleIds);
288
        String emailId = null;
289
        String name = null;
34785 vikas.jang 290
        User user = null;
32570 amit.gupta 291
        try {
292
            // if role is retailer then FOFO_ID is retailerId else it is userid as normal
293
            // user's wont have retailer id.
32571 amit.gupta 294
            if (StringUtils.isEmpty(token)) {
32570 amit.gupta 295
                if (authService.authenticate(emailIdOrMobileNumber, password)) {
296
                    AuthUser authUser = authRepository.selectByEmailOrMobile(emailIdOrMobileNumber);
297
                    if (authUser == null) {
34785 vikas.jang 298
                        throw new ProfitMandiBusinessException("Authentication", "Email or Mobile", "Invalid Email Or Mobile");
32570 amit.gupta 299
                    }
300
                    emailId = authUser.getEmailId();
37991 vikas 301
                    name = authUser.getFullName();
32570 amit.gupta 302
                    authUser.setLastLoginTimestamp(LocalDateTime.now());
34785 vikas.jang 303
                } else {
304
                    // TODO: Add login with email and password
305
                    user = userService.authenticate(emailIdOrMobileNumber, password);
306
                    if (user != null) {
307
                        emailId = user.getEmailId();
308
                    } else {
309
                        LOGGER.error("User not found with given emailIdOrMobileNumber [{}]", emailIdOrMobileNumber);
310
                        model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
311
                                request.getContextPath() + "/login", "Email"));
312
                        return "response";
313
                    }
32570 amit.gupta 314
                }
315
            } else {
37913 amit 316
                emailId = googleTokenUtil.getEmailId(token);
32570 amit.gupta 317
            }
318
            fofoDetails.setEmailId(emailId);
319
            fofoDetails.setFofoId(-1);
34785 vikas.jang 320
 
32570 amit.gupta 321
            if (user == null) {
322
                try {
34785 vikas.jang 323
                    user = userRepository.selectByEmailId(emailId);
32570 amit.gupta 324
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
34785 vikas.jang 325
                    LOGGER.error("User not found with given emailId [{}]", emailId);
326
                    try {
327
                        user = userRepository.selectBySecondryEmailId(emailId);
328
                    } catch (ProfitMandiBusinessException exception) {
329
                        LOGGER.error("User not found with given emailId", exception);
330
                        model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
331
                                request.getContextPath() + "/login", "Email"));
332
                        return "response";
333
                    }
32570 amit.gupta 334
                }
335
            }
34785 vikas.jang 336
 
32570 amit.gupta 337
            if (user != null) {
338
                fofoDetails.setFofoId(user.getId());
339
                try {
340
                    List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
34785 vikas.jang 341
                    for (UserRole userRole : userRoles) {
342
                        roleIds.add(userRole.getRoleId());
32570 amit.gupta 343
                    }
344
                    List<Role> roles = roleRepository.selectByIds(roleIds);
345
                    for (Role role : roles) {
346
                        if (role.getName().equals(RoleType.RETAILER.toString())) {
34785 vikas.jang 347
                            UserAccount userAccounts = userAccountRepository.selectByUserIdType(user.getId(), AccountType.saholic);
32570 amit.gupta 348
                            Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
349
                            fofoDetails.setFofoId(retailer.getId());
350
                        }
351
                    }
352
                } catch (ProfitMandiBusinessException pmbe) {
353
                    LOGGER.error("Data Inconsistent", pmbe);
354
                }
355
            }
356
            String redirectUrl = null;
24976 amit.gupta 357
 
32570 amit.gupta 358
            Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
359
            Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
24016 amit.gupta 360
 
32570 amit.gupta 361
            if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
362
                redirectUrl = "/dashboard";
363
            } else {
364
                redirectUrl = "/login";
365
            }
24016 amit.gupta 366
 
32570 amit.gupta 367
            if (redirectUrl.equals("/dashboard")) {
368
                user.setLoginTimestamp(LocalDateTime.now());
369
                this.addCookiesToResponse(fofoDetails, request, response);
34785 vikas.jang 370
                LOGGER.info("Requested token email_id is valid, user login to system, shoud be redirect to {}", redirectUrl);
32570 amit.gupta 371
                model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
372
                        request.getContextPath() + redirectUrl, name));
373
            } else {
374
                LOGGER.error("Requested token email_id is not valid, please try to login");
375
                /**
376
                 * TODO:Amit This redirect should be handle.
377
                 */
34785 vikas.jang 378
                throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId(), "RTLR_1000");
32570 amit.gupta 379
            }
380
            return "response";
381
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
37728 amit 382
            LOGGER.warn("Error : ", profitMandiBusinessException);
32570 amit.gupta 383
            model.addAttribute("response1",
384
                    mvcResponseSender.createResponseString(profitMandiBusinessException.getCode(), false, "/error"));
385
            return "response";
386
        } catch (Exception e) {
387
            e.printStackTrace();
388
            model.addAttribute("response1",
389
                    mvcResponseSender.createResponseString(
390
                            "You are not authorised! " + "Please contact the team if you feel this is incorrect", false,
391
                            "/error"));
392
            return "response";
393
        }
394
    }
24016 amit.gupta 395
 
32570 amit.gupta 396
    @PostMapping(value = "/forgetPassword")
34785 vikas.jang 397
    public String forgetPasswordPage(@RequestParam(name = ProfitMandiConstants.EMAIL_ID, defaultValue = "") String emailId, Model model) throws Exception {
398
        try {
399
            LOGGER.info("Forgetting password of: [{}]",emailId);
400
            authService.resetPassword(emailId);
401
        } catch (Exception exception){
402
            try {
403
                userService.resetPassword(emailId);
404
            } catch (Exception e){
34815 vikas 405
                LOGGER.info("Forgetting password of: [{}] - {}",emailId, e);
34785 vikas.jang 406
                throw new ProfitMandiBusinessException("Password Reset Email", emailId, "Could not send password reset mail. Password Could not be reset");
407
            }
408
        }
32570 amit.gupta 409
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
410
        LOGGER.info("completed");
411
        return "response";
412
    }
24984 amit.gupta 413
 
34785 vikas.jang 414
    private void addCookiesToResponse(LoginDetails fofoDetails, HttpServletRequest request, HttpServletResponse response) {
32570 amit.gupta 415
        List<String> roleIds = new ArrayList<>();
24016 amit.gupta 416
 
32570 amit.gupta 417
        for (int roleId : fofoDetails.getRoleIds()) {
418
            roleIds.add(String.valueOf(roleId));
419
        }
420
        Cookie cookieRoleIds = new Cookie(ProfitMandiConstants.ROLE_IDS, String.join("-", roleIds));
421
        cookieRoleIds.setDomain(request.getServerName());
422
        cookieRoleIds.setPath(request.getContextPath());
24016 amit.gupta 423
 
32570 amit.gupta 424
        Cookie cookieFofoId = new Cookie(ProfitMandiConstants.FOFO_ID, String.valueOf(fofoDetails.getFofoId()));
425
        cookieFofoId.setDomain(request.getServerName());
426
        cookieFofoId.setPath(request.getContextPath());
427
 
428
        Cookie cookieEmailId = new Cookie(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId());
429
        cookieEmailId.setDomain(request.getServerName());
430
        cookieEmailId.setPath(request.getContextPath());
431
 
432
        Cookie cookieReadOnly = new Cookie(ProfitMandiConstants.READONLY_KEY, fofoDetails.isReadOnly() + "");
433
        cookieReadOnly.setDomain(request.getServerName());
434
        cookieReadOnly.setPath(request.getContextPath());
435
 
436
        response.addCookie(cookieFofoId);
437
        response.addCookie(cookieEmailId);
438
        response.addCookie(cookieRoleIds);
439
        response.addCookie(cookieReadOnly);
440
    }
441
 
442
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
443
    public String logout(HttpServletRequest request, @ModelAttribute("model") ModelMap model,
444
                         HttpServletResponse response) throws Exception {
445
        try {
446
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
447
            User user = null;
448
            try {
449
                user = userRepository.selectByEmailId(loginDetails.getEmailId());
450
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
37728 amit 451
                LOGGER.warn("User not found with given emailId", profitMandiBusinessException);
32570 amit.gupta 452
            }
453
            if (user == null) {
454
                user = userRepository.selectBySecondryEmailId(loginDetails.getEmailId());
455
            }
456
            user.setLogoutTimestamp(LocalDateTime.now());
457
            cookiesProcessor.removeCookies(request, response);
458
            LOGGER.info("Logout is successfull, should be redirect to /login");
459
            return "redirect:/login";
460
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
461
            LOGGER.info("Error occured while removing requested cookies, should be redirect to /login");
462
            return "redirect:/login";
463
        }
464
    }
465
 
466
    @RequestMapping(value = "/partner/location", method = RequestMethod.PUT)
467
    public String setLocation(HttpServletRequest request, Model model, @RequestBody Location location)
468
            throws Exception {
469
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
470
        boolean response = true;
471
        try {
472
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
473
            if (fs.getLatitude() == null) {
474
                fs.setLatitude(location.getLatitude());
475
                fs.setLongitude(location.getLongitude());
476
            }
477
            model.addAttribute("response1", response);
478
        } catch (Exception e) {
479
            LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
480
        }
481
        return "response";
482
    }
21555 kshitij.so 483
}