Subversion Repositories SmartDukaan

Rev

Rev 32574 | Rev 34300 | 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
        }
166
        model.addAttribute("appUrl", appUrl);
167
        return "mobileapp";
168
    }
25243 amit.gupta 169
 
32570 amit.gupta 170
    private String getAndroidId(String emailId) throws Exception {
171
        User user = userRepository.selectByEmailId(emailId);
172
        List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(Arrays.asList(user.getId()),
173
                LocalDateTime.now().minusYears(2), LocalDateTime.now());
174
        if (devices.size() > 0) {
175
            Device device = devices.get(0);
176
            return device.getAndroidId();
177
        } else {
178
            return "";
179
        }
180
    }
24976 amit.gupta 181
 
32570 amit.gupta 182
    private String getToken(String emailId) throws Exception {
183
        List<NameValuePair> nameValuePairs = new ArrayList<>();
184
        nameValuePairs.add(new BasicNameValuePair("adminToken", this.adminToken));
185
        nameValuePairs.add(new BasicNameValuePair("emailId", emailId));
186
        String queryString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
187
        String response = restClient.post(this.appTokenUrl + queryString,
188
                new HashMap<>(), new HashMap<>());
189
        Type t = new TypeToken<ProfitMandiResponse<Map<String, Object>>>() {
190
        }.getType();
191
        ProfitMandiResponse<Map<String, Object>> apiResponse = new Gson().fromJson(response, t);
192
        if (apiResponse.getStatusCode().equals("200")) {
193
            return (new StringBuilder((String) apiResponse.getResponse().get("token")).reverse().toString());
194
        } else {
195
            throw new Exception("Unauthorised access");
196
        }
24383 amit.gupta 197
 
32570 amit.gupta 198
    }
24383 amit.gupta 199
 
32570 amit.gupta 200
    @RequestMapping(value = "/login-as-partner", method = RequestMethod.GET)
201
    public String adminLogin(HttpServletRequest request, Model model, HttpServletResponse response,
202
                             @RequestParam int fofoId) throws Exception {
203
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
204
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
205
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
206
            User user = userRepository.selectById(userId);
207
            Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
208
                    .collect(Collectors.toSet());
209
            LoginDetails newFofoDetails = new LoginDetails();
210
            newFofoDetails.setFofoId(fofoId);
211
            newFofoDetails.setRoleIds(roleIds);
212
            newFofoDetails.setEmailId(user.getEmailId());
213
            model.addAttribute("response1", true);
214
            this.addCookiesToResponse(newFofoDetails, request, response);
215
        } else {
216
            throw new ProfitMandiBusinessException("", "", "");
217
        }
218
        return "response";
219
    }
24016 amit.gupta 220
 
32570 amit.gupta 221
    @RequestMapping(value = "/login-as-partner-readonly", method = RequestMethod.GET)
222
    public String readonlyLogin(HttpServletRequest request, Model model, HttpServletResponse response,
223
                                @RequestParam int fofoId) throws Exception {
224
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
225
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
226
            int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
227
            User user = userRepository.selectById(userId);
228
            Set<Integer> roleIds = userRoleRepository.selectByUserId(userId).stream().map(x -> x.getRoleId())
229
                    .collect(Collectors.toSet());
230
            LoginDetails newFofoDetails = new LoginDetails();
231
            newFofoDetails.setFofoId(fofoId);
232
            newFofoDetails.setRoleIds(roleIds);
233
            newFofoDetails.setEmailId(user.getEmailId());
234
            newFofoDetails.setReadOnly(true);
235
            model.addAttribute("response1", true);
236
            this.addCookiesToResponse(newFofoDetails, request, response);
237
        } else {
238
            throw new ProfitMandiBusinessException("", "", "");
239
        }
240
        return "response";
241
    }
24016 amit.gupta 242
 
32570 amit.gupta 243
    @RequestMapping(value = "/login", method = RequestMethod.POST)
244
    public String login(HttpServletRequest request, HttpServletResponse response,
245
                        @RequestParam(name = ProfitMandiConstants.TOKEN) String token,
246
                        @RequestParam(name = ProfitMandiConstants.EMAIL_ID_OR_MOBILE_NUMBER, defaultValue = "") String emailIdOrMobileNumber,
247
                        @RequestParam(name = "password", defaultValue = "") String password, Model model) throws Exception {
25275 amit.gupta 248
 
32570 amit.gupta 249
        LoginDetails fofoDetails = new LoginDetails();
250
        Set<Integer> roleIds = new HashSet<>();
251
        fofoDetails.setRoleIds(roleIds);
252
        String emailId = null;
253
        String name = null;
254
        try {
255
            // if role is retailer then FOFO_ID is retailerId else it is userid as normal
256
            // user's wont have retailer id.
32571 amit.gupta 257
            if (StringUtils.isEmpty(token)) {
32570 amit.gupta 258
                if (authService.authenticate(emailIdOrMobileNumber, password)) {
259
                    AuthUser authUser = authRepository.selectByEmailOrMobile(emailIdOrMobileNumber);
260
                    if (authUser == null) {
261
                        throw new ProfitMandiBusinessException("Authentication", "Email or Mobile",
262
                                "Invalid Email Or Mobile");
263
                    }
264
                    emailId = authUser.getEmailId();
265
                    name = authUser.getFirstName() + " " + authUser.getLastName();
266
                    authUser.setLastLoginTimestamp(LocalDateTime.now());
267
                }
24016 amit.gupta 268
 
32570 amit.gupta 269
            } else {
270
                try {
271
                    emailId = googleTokenUtil.getEmailId(token);
272
                } catch (Exception e) {
273
                    // in case we cannot connect to google server.
274
                    emailId = emailIdOrMobileNumber;
275
                }
276
            }
277
            fofoDetails.setEmailId(emailId);
278
            fofoDetails.setFofoId(-1);
279
            // fofoDetails.setFofo(false);
280
            User user = null;
281
            try {
282
                user = userRepository.selectByEmailId(emailId);
283
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
284
                LOGGER.error("User not found with given emailId [{}]", emailId);
285
            }
286
            if (user == null) {
287
                try {
288
                    user = userRepository.selectBySecondryEmailId(emailId);
289
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
290
                    LOGGER.error("User not found with given emailId", profitMandiBusinessException);
291
                    model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
292
                            request.getContextPath() + "/login", "Email"));
293
                    return "response";
294
                }
295
            }
296
            if (user != null) {
297
                fofoDetails.setFofoId(user.getId());
298
                try {
299
                    List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
300
                    for (int index = 0; index < userRoles.size(); index++) {
301
                        roleIds.add(userRoles.get(index).getRoleId());
302
                    }
303
                    List<Role> roles = roleRepository.selectByIds(roleIds);
304
                    for (Role role : roles) {
305
                        if (role.getName().equals(RoleType.RETAILER.toString())) {
306
                            UserAccount userAccounts = userAccountRepository.selectByUserIdType(user.getId(),
307
                                    AccountType.saholic);
308
                            Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
309
                            fofoDetails.setFofoId(retailer.getId());
310
                            // fofoDetails.setFofo(retailer.isFofo());
311
                        }
312
                    }
313
                } catch (ProfitMandiBusinessException pmbe) {
314
                    LOGGER.error("Data Inconsistent", pmbe);
315
                }
316
            }
317
            String redirectUrl = null;
24976 amit.gupta 318
 
32570 amit.gupta 319
            Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
320
            Role roleFofoAdmin = roleRepository.selectByName(RoleType.FOFO_ADMIN.toString());
24016 amit.gupta 321
 
32570 amit.gupta 322
            if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
323
                redirectUrl = "/dashboard";
324
                if (fofoDetails.getRoleIds().contains(roleFofo.getId())) {
24016 amit.gupta 325
 
32570 amit.gupta 326
                }
327
            } else {
328
                redirectUrl = "/login";
329
            }
24016 amit.gupta 330
 
32570 amit.gupta 331
            if (redirectUrl.equals("/dashboard")) {
332
                user.setLoginTimestamp(LocalDateTime.now());
333
                this.addCookiesToResponse(fofoDetails, request, response);
334
                LOGGER.info("Requested token email_id is valid, user login to system, shoud be redirect to {}",
335
                        redirectUrl);
336
                model.addAttribute("response1", mvcResponseSender.createResponseString("RTLR_OK_1002", true,
337
                        request.getContextPath() + redirectUrl, name));
338
            } else {
339
                LOGGER.error("Requested token email_id is not valid, please try to login");
340
                /**
341
                 * TODO:Amit This redirect should be handle.
342
                 */
343
                throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId(),
344
                        "RTLR_1000");
345
            }
346
            return "response";
347
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
348
            LOGGER.error("Error : ", profitMandiBusinessException);
349
            model.addAttribute("response1",
350
                    mvcResponseSender.createResponseString(profitMandiBusinessException.getCode(), false, "/error"));
351
            return "response";
352
        } catch (Exception e) {
353
            e.printStackTrace();
354
            model.addAttribute("response1",
355
                    mvcResponseSender.createResponseString(
356
                            "You are not authorised! " + "Please contact the team if you feel this is incorrect", false,
357
                            "/error"));
358
            return "response";
359
        }
360
    }
24016 amit.gupta 361
 
32570 amit.gupta 362
    @PostMapping(value = "/forgetPassword")
363
    public String forgetPasswordPage(
364
            @RequestParam(name = ProfitMandiConstants.EMAIL_ID, defaultValue = "") String emailId, Model model)
365
            throws Exception {
366
        LOGGER.info(emailId);
367
        authService.resetPassword(emailId);
368
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
369
        LOGGER.info("completed");
370
        return "response";
371
    }
24984 amit.gupta 372
 
32570 amit.gupta 373
    private void addCookiesToResponse(LoginDetails fofoDetails, HttpServletRequest request,
374
                                      HttpServletResponse response) {
375
        List<String> roleIds = new ArrayList<>();
24016 amit.gupta 376
 
32570 amit.gupta 377
        for (int roleId : fofoDetails.getRoleIds()) {
378
            roleIds.add(String.valueOf(roleId));
379
        }
380
        Cookie cookieRoleIds = new Cookie(ProfitMandiConstants.ROLE_IDS, String.join("-", roleIds));
381
        cookieRoleIds.setDomain(request.getServerName());
382
        cookieRoleIds.setPath(request.getContextPath());
24016 amit.gupta 383
 
32570 amit.gupta 384
        Cookie cookieFofoId = new Cookie(ProfitMandiConstants.FOFO_ID, String.valueOf(fofoDetails.getFofoId()));
385
        cookieFofoId.setDomain(request.getServerName());
386
        cookieFofoId.setPath(request.getContextPath());
387
 
388
        Cookie cookieEmailId = new Cookie(ProfitMandiConstants.EMAIL_ID, fofoDetails.getEmailId());
389
        cookieEmailId.setDomain(request.getServerName());
390
        cookieEmailId.setPath(request.getContextPath());
391
 
392
        Cookie cookieReadOnly = new Cookie(ProfitMandiConstants.READONLY_KEY, fofoDetails.isReadOnly() + "");
393
        cookieReadOnly.setDomain(request.getServerName());
394
        cookieReadOnly.setPath(request.getContextPath());
395
 
396
        response.addCookie(cookieFofoId);
397
        response.addCookie(cookieEmailId);
398
        response.addCookie(cookieRoleIds);
399
        response.addCookie(cookieReadOnly);
400
    }
401
 
402
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
403
    public String logout(HttpServletRequest request, @ModelAttribute("model") ModelMap model,
404
                         HttpServletResponse response) throws Exception {
405
        try {
406
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
407
            User user = null;
408
            try {
409
                user = userRepository.selectByEmailId(loginDetails.getEmailId());
410
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
411
                LOGGER.error("User not found with given emailId", profitMandiBusinessException);
412
            }
413
            if (user == null) {
414
                user = userRepository.selectBySecondryEmailId(loginDetails.getEmailId());
415
            }
416
            user.setLogoutTimestamp(LocalDateTime.now());
417
            cookiesProcessor.removeCookies(request, response);
418
            LOGGER.info("Logout is successfull, should be redirect to /login");
419
            return "redirect:/login";
420
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
421
            LOGGER.info("Error occured while removing requested cookies, should be redirect to /login");
422
            return "redirect:/login";
423
        }
424
    }
425
 
426
    @RequestMapping(value = "/partner/location", method = RequestMethod.PUT)
427
    public String setLocation(HttpServletRequest request, Model model, @RequestBody Location location)
428
            throws Exception {
429
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
430
        boolean response = true;
431
        try {
432
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
433
            if (fs.getLatitude() == null) {
434
                fs.setLatitude(location.getLatitude());
435
                fs.setLongitude(location.getLongitude());
436
            }
437
            model.addAttribute("response1", response);
438
        } catch (Exception e) {
439
            LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
440
        }
441
        return "response";
442
    }
21555 kshitij.so 443
}