Subversion Repositories SmartDukaan

Rev

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