Rev 27256 | Rev 27258 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.web.processor;import java.io.IOException;import java.time.LocalDateTime;import java.util.Arrays;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.http.conn.HttpHostConnectException;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.stereotype.Component;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import com.spice.profitmandi.common.enumuration.SchemeType;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.GoogleLoginRequest;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.common.util.JWTUtil;import com.spice.profitmandi.common.util.Utils;import com.spice.profitmandi.common.web.client.RestClient;import com.spice.profitmandi.dao.entity.auth.AuthUser;import com.spice.profitmandi.dao.entity.dtr.SocialUser;import com.spice.profitmandi.dao.entity.dtr.User;import com.spice.profitmandi.dao.entity.user.Promoter;import com.spice.profitmandi.dao.enumuration.dtr.Gender;import com.spice.profitmandi.dao.enumuration.dtr.SocialType;import com.spice.profitmandi.dao.repository.auth.AuthRepository;import com.spice.profitmandi.dao.repository.cs.CsService;import com.spice.profitmandi.dao.repository.dtr.SocialUserRepository;import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;import com.spice.profitmandi.dao.repository.dtr.UserRepository;import com.spice.profitmandi.dao.repository.dtr.UserRoleRepository;import com.spice.profitmandi.dao.repository.user.PromoterRepository;import com.spice.profitmandi.service.AuthService;import com.spice.profitmandi.service.user.RetailerService;@Componentpublic class GoogleLoginProcessor {private static final String V1_HOST_NAME = "content.googleapis.com";private static final String V1_URI = "/plus/v1/people/me";private static final String V3_HOST_NAME = "www.googleapis.com";private static final String V3_URI = "/oauth2/v3/tokeninfo";private static final Logger LOGGER = LogManager.getLogger(GoogleLoginProcessor.class);private static final int PORT_NUMBER = 443;private final ObjectMapper objectMapper = new ObjectMapper();@Autowiredprivate SocialUserRepository socialUserRepository;@Autowiredprivate UserRepository userRepository;@Autowiredprivate AuthService authService;@Autowiredcom.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;@Autowiredprivate AuthRepository authRepository;@Autowiredprivate UserRoleRepository userRoleRepository;@Autowiredprivate PromoterRepository promoterRepository;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate CsService csService;@Autowiredprivate RestClient restClient;@Autowiredprivate RetailerService retailerService;public Map<String, Object> process(GoogleLoginRequest googleLoginRequest) throws ProfitMandiBusinessException {LOGGER.info("1");Map<String, String> params = new HashMap<>();params.put(ProfitMandiConstants.ACCESS_TOKEN, googleLoginRequest.getToken());Map<String, String> headers = new HashMap<>(1);headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);String responseString = null;try {responseString = restClient.get(SchemeType.HTTPS, V1_HOST_NAME, PORT_NUMBER, V1_URI, params, headers);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to remote host");}try {JsonNode rootNode = objectMapper.readTree(responseString);SocialUser socialUser = new SocialUser();if (rootNode.has("emails")) {JsonNode emails = rootNode.get("emails");if (emails.isArray()) {Iterator<JsonNode> emailsIterator = emails.elements();if (emailsIterator.hasNext()) {JsonNode email = emailsIterator.next();if (email.has("value")) {/*if (ProfitMandiConstants.BLOCKED_EMAILS.contains(email.get("value").asText())) {throw new ProfitMandiBusinessException("User Account", email.get("value").asText(),"User is temporarily suspended.");}*/socialUser.setEmailId(email.get("value").asText());}}}// socialUser.setEmailId(rootNode.get("email").asText());}LOGGER.info("2");if (!socialUserRepository.isExistByEmailId(socialUser.getEmailId())) {if (rootNode.has("displayName")) {socialUser.setName(rootNode.get("displayName").asText());}if (rootNode.has("gender")) {String genderName = rootNode.get("gender").asText();switch (genderName) {case "male": {socialUser.setGender(Gender.MALE);break;}case "female": {socialUser.setGender(Gender.FEMALE);break;}}}socialUser.setCreateTimestamp(LocalDateTime.now());socialUser.setType(SocialType.GOOGLE);socialUser.setUpdateTimestamp(LocalDateTime.now());socialUserRepository.persist(socialUser);}Map<String, Object> responseMap = new HashMap<>(2);LOGGER.info("3");String name = authService.getNameByEmailId(socialUser.getEmailId());LOGGER.info("User Name from getNameByEmailId({}) is {}", socialUser.getEmailId(), name);if (name != null) {User registeredUser = null;AuthUser authUser = authRepository.selectByGmailId(socialUser.getEmailId());if (authRepository.selectByGmailId(socialUser.getEmailId()) != null) {registeredUser = userRepository.selectByEmailId(authUser.getEmailId());} else if (promoterRepository.isExistByEmailId(socialUser.getEmailId())) {Promoter promoter = promoterRepository.selectByEmailId(socialUser.getEmailId());int userId = userAccountRepository.selectUserIdByRetailerId(promoter.getRetailerId());registeredUser = userRepository.selectById(userId);} else if (userRepository.isExistBySecondryEmailId(socialUser.getEmailId())) {registeredUser = userRepository.selectBySecondryEmailId(socialUser.getEmailId());}LOGGER.info("4");List<Integer> roleIds = userRoleRepository.selectRoleIdsByUserId(registeredUser.getId());String[] roleTypes = new String[roleIds.size()];int index = 0;for (int roleId : roleIds) {roleTypes[index++] = String.valueOf(roleId);}int retailerId;try {retailerId = userAccountRepository.selectRetailerIdByUserId(registeredUser.getId());LOGGER.info("173 - Auth User Email {}, Retailer Id - {}", authUser.getName(), retailerId);} catch (Exception e) {Set<Integer> authUserPartnerSet = csService.getAuthUserPartnerIdMapping().get(authUser.getEmailId());if(authUserPartnerSet.size() > 0) {retailerId = authUserPartnerSet.stream().findFirst().get();LOGGER.info("178 - Auth User Email {}, Retailer Id - {}", socialUser.getEmailId(), retailerId);} else {com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectByEmailId(Utils.SYSTEM_PARTNER);retailerId = user.getId();LOGGER.info("Auth User Email {}, Retailer Id - {}", socialUser.getEmailId(), retailerId);}}responseMap.put(ProfitMandiConstants.TOKEN,JWTUtil.create(socialUser.getEmailId(), registeredUser.getId(), retailerId, roleTypes));LOGGER.info("Param value for socialUser.getEmailId(), registeredUser.getId(), retailerId, roleTypes are {}, {}, {} and {}",socialUser.getEmailId(), registeredUser.getId(), retailerId, Arrays.asList(roleTypes));responseMap.put(ProfitMandiConstants.REGISTERED, true);return responseMap;}User user = null;try {user = userRepository.selectByEmailId(socialUser.getEmailId());} catch (ProfitMandiBusinessException profitMandiBusinessException) {}if (user == null) {try {user = userRepository.selectByEmailId(socialUser.getEmailId());} catch (ProfitMandiBusinessException profitMandiBusinessException) {responseMap.put(ProfitMandiConstants.TOKEN, JWTUtil.create(socialUser.getEmailId()));responseMap.put(ProfitMandiConstants.REGISTERED, false);}} else {List<Integer> roleIds = userRoleRepository.selectRoleIdsByUserId(user.getId());int retailerId = userAccountRepository.selectRetailerIdByUserId(user.getId());String[] roleTypes = new String[roleIds.size()];int index = 0;for (int roleId : roleIds) {roleTypes[index++] = String.valueOf(roleId);}responseMap.put(ProfitMandiConstants.TOKEN, JWTUtil.create(user.getId(), retailerId, roleTypes));responseMap.put(ProfitMandiConstants.REGISTERED, true);}return responseMap;} catch (JsonProcessingException jsonProcessingException) {// LOGGER.error("Json parse exception of "+json,jsonProcessingException);throw new ProfitMandiBusinessException("", "", "VE_1001");} catch (IOException ioException) {// LOGGER.error("IO Exception occurred while parsing json String");throw new ProfitMandiBusinessException("", "", "VE_1001");}}public Map<String, Object> process(String token) throws ProfitMandiBusinessException {Map<String, String> params = new HashMap<>();params.put(ProfitMandiConstants.ID_TOKEN, token);Map<String, String> headers = new HashMap<>();headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);String responseString = null;try {responseString = restClient.get(SchemeType.HTTPS, V3_HOST_NAME, PORT_NUMBER, V3_URI, params, headers);} catch (HttpHostConnectException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {JsonNode rootNode = objectMapper.readTree(responseString);String email = rootNode.get("email").asText();String name = authService.getNameByEmailId(email);Map<String, Object> responseMap = new HashMap<>(2);LOGGER.info("User Name from getNameByEmailId({}) is {}", email, name);if (name != null) {User registeredUser = null;AuthUser authUser = authRepository.selectByGmailId(email);if (authRepository.selectByGmailId(email) != null) {registeredUser = userRepository.selectByEmailId(authUser.getEmailId());} else if (promoterRepository.isExistByEmailId(email)) {Promoter promoter = promoterRepository.selectByEmailId(email);int userId = userAccountRepository.selectUserIdByRetailerId(promoter.getRetailerId());registeredUser = userRepository.selectById(userId);} else if (userRepository.isExistBySecondryEmailId(email)) {registeredUser = userRepository.selectBySecondryEmailId(email);}LOGGER.info("4");List<Integer> roleIds = userRoleRepository.selectRoleIdsByUserId(registeredUser.getId());String[] roleTypes = new String[roleIds.size()];int index = 0;for (int roleId : roleIds) {roleTypes[index++] = String.valueOf(roleId);}int retailerId;try {Set<Integer> authUserPartnerSet = csService.getAuthUserPartnerIdMapping().get(authUser.getEmailId());if(authUserPartnerSet.size() > 0) {retailerId = authUserPartnerSet.stream().findFirst().get();} catch (Exception e) {com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectByEmailId(Utils.SYSTEM_PARTNER);retailerId = user.getId();}responseMap.put(ProfitMandiConstants.TOKEN,JWTUtil.create(email, registeredUser.getId(), retailerId, roleTypes));LOGGER.info("Param value for email, registeredUser.getId(), retailerId, roleTypes are {}, {}, {} and {}",email, registeredUser.getId(), retailerId, Arrays.asList(roleTypes));responseMap.put(ProfitMandiConstants.REGISTERED, true);return responseMap;}User user = null;try {user = userRepository.selectByEmailId(email);} catch (ProfitMandiBusinessException profitMandiBusinessException) {}if (user == null) {try {user = userRepository.selectByEmailId(email);} catch (ProfitMandiBusinessException profitMandiBusinessException) {responseMap.put(ProfitMandiConstants.TOKEN, JWTUtil.create(email));responseMap.put(ProfitMandiConstants.REGISTERED, false);}} else {List<Integer> roleIds = userRoleRepository.selectRoleIdsByUserId(user.getId());int retailerId = userAccountRepository.selectRetailerIdByUserId(user.getId());String[] roleTypes = new String[roleIds.size()];int index = 0;for (int roleId : roleIds) {roleTypes[index++] = String.valueOf(roleId);}responseMap.put(ProfitMandiConstants.TOKEN, JWTUtil.create(user.getId(), retailerId, roleTypes));responseMap.put(ProfitMandiConstants.REGISTERED, true);}return responseMap;} catch (JsonProcessingException jsonProcessingException) {throw new ProfitMandiBusinessException("", "", "VE_1001");} catch (IOException ioException) {throw new ProfitMandiBusinessException("", "", "VE_1001");}}public Map<String, Object> processStore(String storeCode) throws ProfitMandiBusinessException {Map<String, Object> responseMap = new HashMap<>();storeCode = storeCode.toUpperCase();int retailerId = retailerService.getStoreCodeRetailerMap().get(storeCode);int userId = userAccountRepository.selectUserIdByRetailerId(retailerId);List<Integer> roleIds = userRoleRepository.selectRoleIdsByUserId(userId);String[] roleTypes = new String[roleIds.size()];int index = 0;for (int roleId : roleIds) {roleTypes[index++] = String.valueOf(roleId);}responseMap.put(ProfitMandiConstants.TOKEN, JWTUtil.create(userId, retailerId, roleTypes));responseMap.put(ProfitMandiConstants.REGISTERED, true);return responseMap;}}