Subversion Repositories SmartDukaan

Rev

Rev 21643 | Rev 21708 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.time.LocalDateTime;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.spice.profitmandi.common.ResponseCodeHolder;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.UserInfo;
import com.spice.profitmandi.common.util.JWTUtil;
import com.spice.profitmandi.dao.entity.Permission;
import com.spice.profitmandi.dao.entity.Retailer;
import com.spice.profitmandi.dao.entity.Role;
import com.spice.profitmandi.dao.entity.User;
import com.spice.profitmandi.dao.entity.UserRole;
import com.spice.profitmandi.dao.enumuration.RoleType;
import com.spice.profitmandi.dao.model.UserCart;
import com.spice.profitmandi.dao.repository.PermissionRepository;
import com.spice.profitmandi.dao.repository.RetailerRepository;
import com.spice.profitmandi.dao.repository.RoleRepository;
import com.spice.profitmandi.dao.repository.UserAccountRepository;
import com.spice.profitmandi.dao.repository.UserRepository;
import com.spice.profitmandi.dao.repository.UserRoleRepository;
import com.spice.profitmandi.dao.util.UserToRetailerMigrationUtil;
import com.spice.profitmandi.web.enumuration.UserStatus;
import com.spice.profitmandi.web.model.ProfitMandiResponse;
import com.spice.profitmandi.web.model.ResponseStatus;
import com.spice.profitmandi.web.processor.GoogleLoginProcessor;
import com.spice.profitmandi.web.req.UserAddRoleRequest;
import com.spice.profitmandi.web.req.UserRequest;
import com.spice.profitmandi.web.util.ResponseSender;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

/**
 * @author ashikali
 *
 */
@Controller
@Transactional
public class UserController {

        @Autowired
        ResponseSender<?> responseSender;

        private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

        @Value("${admin.token}")
        private String validAdminToken;

        @Autowired
        UserRepository userRepository;

        @Autowired
        RetailerRepository retailerRepository;

        @Autowired
        RoleRepository roleRepository;

        @Autowired
        UserRoleRepository userRoleRepository;

        @Autowired
        UserAccountRepository userAccountRepository;

        @Autowired
        PermissionRepository permissionRepository;

        @Autowired
        GoogleLoginProcessor googleLoginProcessor;
        
        @Autowired
        UserToRetailerMigrationUtil userToRetailerMigrationUtil;

        @SuppressWarnings("unchecked")
        @RequestMapping(value = ProfitMandiConstants.URL_USER_GOOGLE_LOGIN, method = RequestMethod.POST)
        public ResponseEntity<?> googleLogin(HttpServletRequest request) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                final Map<String, Object> googleLoginMap = (Map<String, Object>) request
                                .getAttribute(ProfitMandiConstants.GOOGLE_LOGIN_MAP);
                request.removeAttribute(ProfitMandiConstants.GOOGLE_LOGIN_MAP);
                try {
                        return responseSender.ok(googleLoginProcessor.process(googleLoginMap));
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_TOKEN_IS_EXPIRED, method = RequestMethod.GET)
        public ResponseEntity<?> tokenIsExpired(HttpServletRequest request, @RequestParam(name = "token") String token) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                try {
                        return responseSender.ok(JWTUtil.isExpired(token));

                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_TOKEN_INFO, method = RequestMethod.GET)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> tokenInfo(HttpServletRequest request) throws Throwable {
                Map<String, Object> responseMap = new HashMap<>();
                UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
                User user = null;
                if(userInfo.getUserId()>-1){
                        user = userRepository.selectById(userInfo.getUserId());
                } else {
                        try {
                                user = userRepository.selectByEmailId(userInfo.getEmail());
                        } catch (ProfitMandiBusinessException e1) {
                                LOGGER.info("Uneregistered user", userInfo.getEmail());
                        }
                }
                if (user != null) {
                        responseMap.put(ProfitMandiConstants.EMAIL_ID, user.getEmailId());
                        responseMap.put(ProfitMandiConstants.USER_ID, user.getId());
                        
                        Set<Role> roles = user.getRoles();
                        //generate new token if roles size is different
                        if(userInfo.getRoleNames() == null || roles.size() != userInfo.getRoleNames().size()) {
                                String[] roleTypes = new String[roles.size()];
                                int index = 0;
                                for (Role role : roles) {
                                        roleTypes[index++] = role.getType().toString();
                                }
                                String newToken = JWTUtil.create(user.getId(), roleTypes);
                                responseMap.put("newAuthToken", newToken);
                        }
                        
                        // if user is retailer
                        if (user.getRoles().stream().anyMatch(new Predicate<Role>() {
                                @Override
                                public boolean test(Role t) {
                                        return t.getType().equals(RoleType.RETAILER);
                                }
                        })) {
                                UserCart uc  = userAccountRepository.getUserCart(userInfo.getUserId());
                                Retailer retailer  = retailerRepository.selectById(uc.getUserId());
                                // if retailer is activated 1 then verified retailer
                                // else if migrated is 1 then old retailer
                                // else retailer is not verifed
                                if (retailer.isActive()) {
                                        responseMap.put(ProfitMandiConstants.USER_STATUS, UserStatus.VERIFIED_RETAILER.getValue());
                                } else if (retailer.isMigrated()){
                                        responseMap.put(ProfitMandiConstants.USER_STATUS, UserStatus.RETAILER.getValue());
                                } else {
                                        responseMap.put(ProfitMandiConstants.USER_STATUS, UserStatus.NOT_VERIFIED_RETAILER.getValue());
                                }
                        } else if (user.getRoles().stream().anyMatch(new Predicate<Role>() {
                                @Override
                                public boolean test(Role t) {
                                        return t.getType().equals(RoleType.USER);
                                }
                        })) {
                                responseMap.put(ProfitMandiConstants.USER_STATUS, UserStatus.REGISTERED.getValue());
                        }
                } else {
                        responseMap.put(ProfitMandiConstants.USER_STATUS, UserStatus.NOT_REGISTERED.getValue());
                        responseMap.put(ProfitMandiConstants.EMAIL_ID, userInfo.getEmail());
                }
        
                return responseSender.ok(responseMap);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER, method = RequestMethod.POST)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> createUser(HttpServletRequest request, @RequestBody UserRequest userRequest) throws Throwable{
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                User user = new User();
                user.setFirstName(userRequest.getFirstName());
                user.setLastName(userRequest.getLastName());
                user.setCity(userRequest.getCity());
                user.setPinCode(Integer.valueOf(userRequest.getPinCode()));
                user.setEmailId(userRequest.getEmailId());
                user.setUsername("");
                user.setPassword("");
                user.setMobile_verified(false);
                user.setReferral_url("");
                user.setGroup_id(1);
                user.setStatus(0);
                user.setActivated(false);
                user.setCreateTimestamp(LocalDateTime.now());
                user.setUpdateTimestamp(LocalDateTime.now());
                try{
                        userRepository.persist(user);

                        UserRole userRole = new UserRole();
                        userRole.setRoleId(RoleType.USER.getValue());
                        userRole.setUserId(user.getId());
                        userRoleRepository.persist(userRole);
                        return responseSender.ok(ResponseCodeHolder.getMessage("USR_OK_1000"));
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_ALL, method = RequestMethod.GET)
        public ResponseEntity<?> getAll(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.PAGE_NUMBER) int pageNumber, @RequestParam(name = ProfitMandiConstants.PAGE_SIZE) int pageSize) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                return responseSender.ok(userRepository.selectAll(pageNumber, pageSize));
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_ID, method = RequestMethod.GET)
        public ResponseEntity<?> getById(HttpServletRequest request, @RequestParam(name = "id") int id) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                try {
                        return responseSender.ok(userRepository.selectById(id));
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_MOBILE_NUMBER, method = RequestMethod.GET)
        public ResponseEntity<?> getByMobileNumber(HttpServletRequest request,
                        @RequestParam(name = "mobileNumber") String mobileNumber) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                try {
                        return responseSender.ok(userRepository.selectByMobileNumber(mobileNumber));
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        /*@ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        @RequestMapping(value = ProfitMandiConstants.URL_USER_ACTIVATE, method = RequestMethod.POST)
        public ResponseEntity<?> activateUser(HttpServletRequest request,
                        @RequestParam(name = "activationCode") String activationCode) {
                Map<String, Object> response = new HashMap<>();
                boolean activated = false;
                
                int userId = (int)request.getAttribute("userId");
                UserCart uc  = userAccountRepository.getUserCart(userId);
                Client client  = new TransactionClient().getClient();
                if (client.registerRsa(uc.getUserId(),activationCode)){
                        activated = true;
                }
                else{
                        
                }
                return responseSender.ok(null);
        }*/
        
        @RequestMapping(value = ProfitMandiConstants.URL_USER_IS_EXIST_MOBILE_NUMBER, method = RequestMethod.GET)
        public ResponseEntity<?> isMobileNumberExist(HttpServletRequest request,
                        @RequestParam(name = "mobileNumber") String mobileNumber) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                return responseSender.ok(userRepository.isExistByMobileNumber(mobileNumber));
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_EMAIL_ID, method = RequestMethod.GET)
        public ResponseEntity<?> getByEmailId(HttpServletRequest request, @RequestParam(name = "emailId") String emailId) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                try {
                        return responseSender.ok(userRepository.selectByEmailId(emailId));
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_ROLE_ADD, method = RequestMethod.POST)
        public ResponseEntity<?> addRole(HttpServletRequest request, @RequestBody UserAddRoleRequest userAddRoleRequest) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                try {
                        User user = userRepository.selectById(userAddRoleRequest.getUserId());

                        Role role = null;
                        try {
                                role = roleRepository.selectByNameAndType(userAddRoleRequest.getRole().getName(),
                                                userAddRoleRequest.getRole().getType());
                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                role = new Role();
                                role.setName(userAddRoleRequest.getRole().getName());
                                role.setType(userAddRoleRequest.getRole().getType());
                                roleRepository.persist(role);
                        }
                        Permission permission = new Permission();
                        permission.setType(userAddRoleRequest.getRole().getPermissionType());
                        permission.setRoleId(role.getId());
                        permissionRepository.persist(permission);
                        UserRole userRole = new UserRole();
                        userRole.setRoleId(role.getId());
                        userRole.setUserId(user.getId());
                        userRoleRepository.persist(userRole);
                        return responseSender.ok("");
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_ROLE_REMOVE, method = RequestMethod.DELETE)
        public ResponseEntity<?> removeRole(HttpServletRequest request, @RequestParam(name = "roleId") int roleId,
                        @RequestParam(name = "userId") int userId) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                try {
                        roleRepository.selectById(roleId);
                        userRepository.selectById(userId);
                        userRoleRepository.deleteByUserAndRoleId(userId, roleId);
                        permissionRepository.deleteByRoleId(roleId);
                        return responseSender.ok("");
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("ProfitMandi error: ", profitMandiBusinessException);
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }

        @RequestMapping(value = ProfitMandiConstants.URL_USER_ROLE_ALL, method = RequestMethod.GET)
        public ResponseEntity<?> getAllRoles(HttpServletRequest request, @RequestParam(name = "id") int id) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                return responseSender.ok(userRoleRepository.selectRolesByUserId(id));
        }

        @RequestMapping(value = ProfitMandiConstants.URL_ADMIN_TOKEN, method = RequestMethod.POST)
        public ResponseEntity<?> getAdminToken(HttpServletRequest request,
                        @RequestParam(name = "adminToken") String adminToken, @RequestParam(name = "emailId") String emailId) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                if (!adminToken.equals(validAdminToken)) {
                        final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
                                        request.getRequestURL().toString(), HttpStatus.FORBIDDEN.toString(), HttpStatus.FORBIDDEN,
                                        ResponseStatus.FAILURE, null);
                        return new ResponseEntity<>(profitMandiResponse, HttpStatus.FORBIDDEN);
                }

                Map<String, Object> responseMap = new HashMap<>(2);
                try {
                        User user = userRepository.selectByEmailId(emailId);
                        Set<Role> roles = user.getRoles();
                        String[] roleTypes = new String[roles.size()];
                        int index = 0;
                        for (Role role : roles) {
                                roleTypes[index++] = role.getType().toString();
                        }
                        responseMap.put(ProfitMandiConstants.TOKEN, JWTUtil.create(user.getId(), roleTypes));
                        responseMap.put(ProfitMandiConstants.REGISTERED, true);
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        responseMap.put(ProfitMandiConstants.TOKEN, JWTUtil.create(emailId));
                        responseMap.put(ProfitMandiConstants.REGISTERED, false);
                }
                return responseSender.ok(responseMap);

        }
        
        @RequestMapping(value = ProfitMandiConstants.URL_ADMIN_MIGRATE, method = RequestMethod.GET)
        public ResponseEntity<?> migrate(HttpServletRequest request) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                userToRetailerMigrationUtil.migrate();
                return responseSender.ok(ResponseCodeHolder.getMessage("OK_1000"));
        }
}