Subversion Repositories SmartDukaan

Rev

Rev 21448 | Rev 21483 | 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.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.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.repository.PermissionRepository;
import com.spice.profitmandi.dao.repository.RoleRepository;
import com.spice.profitmandi.dao.repository.UserRepository;
import com.spice.profitmandi.dao.repository.UserRoleRepository;
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
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
        RoleRepository roleRepository;

        @Autowired
        UserRoleRepository userRoleRepository;

        @Autowired
        PermissionRepository permissionRepository;

        @Autowired
        GoogleLoginProcessor googleLoginProcessor;

        @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<>();
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
                if (userInfo.getEmail() == null) {
                        User user = userRepository.selectById(userInfo.getUserId());
                        responseMap.put(ProfitMandiConstants.EMAIL_ID, user.getEmailId());
                        responseMap.put(ProfitMandiConstants.USER_ID, user.getId());
                        // if user is retailer
                        if (user.getRoles().stream().anyMatch(new Predicate<Role>() {
                                @Override
                                public boolean test(Role t) {
                                        return t.getType().equals(RoleType.RETAILER);
                                }
                        })) {
                                // TODO: This should be from retailer Table
                                // if retailer is activated and migrated is 0 then verified
                                // retailer
                                // if retailer is not activated and and migrated is 0 then not
                                // verified retailer
                                // if retailer is activated and migrated is 1 then retailer is
                                // retailer.
                                if (user.isActivated()) {
                                        responseMap.put(ProfitMandiConstants.USER_STATUS, UserStatus.VERIFIED_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)
        public ResponseEntity<?> createUser(HttpServletRequest request, @RequestBody UserRequest userRequest) {
                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);

                try {
                        user.setCreateTimestamp(LocalDateTime.now());
                        user.setUpdateTimestamp(LocalDateTime.now());
                        userRepository.persist(user);
                        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) {
                LOGGER.info("requested url : " + request.getRequestURL().toString());
                return responseSender.ok(userRepository.selectAll());
        }

        @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);
                }
        }

        @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);

        }
}