diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..c33ac49cc5416170bff23d322024a53ab26e2e91 --- /dev/null +++ b/pom.xml @@ -0,0 +1,235 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>com.tarento</groupId> + <artifactId>user</artifactId> + <version>0.0.1-SNAPSHOT</version> + <packaging>jar</packaging> + + <name>User Service</name> + <description>Demo project for Spring Boot</description> + + <parent> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-parent</artifactId> + <version>1.5.3.RELEASE</version> + <relativePath /> <!-- lookup parent from repository --> + </parent> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> + <java.version>1.8</java.version> + <cxf.version>3.0.1</cxf.version> + + <base>frolvlad/alpine-oraclejdk8:slim</base> + <tomcat.port>9081</tomcat.port> + <tomcat.ip>127.0.0.1</tomcat.ip> + <file>readme</file> + <powermock.version>2.0.0</powermock.version> + + </properties> + + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-actuator</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-jpa</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-security</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + </dependency> + + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-devtools</artifactId> + <scope>runtime</scope> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <scope>runtime</scope> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <scope>test</scope> + </dependency> + <!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4 --> + + <!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 --> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <version>1.7.1</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito</artifactId> + <version>1.7.1</version> + <scope>test</scope> + </dependency> + + + <dependency> + <groupId>org.springframework.security</groupId> + <artifactId>spring-security-jwt</artifactId> + <version>1.0.7.RELEASE</version> + </dependency> + <!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 --> + <dependency> + <groupId>org.springframework.security.oauth</groupId> + <artifactId>spring-security-oauth2</artifactId> + <version>2.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + <version>2.8.6</version> + </dependency> + <dependency> + <groupId>org.flywaydb</groupId> + <artifactId>flyway-core</artifactId> + <version>4.1.0</version> + </dependency> + <dependency> + <groupId>org.postgresql</groupId> + <artifactId>postgresql</artifactId> + <version>9.4.1212</version> + <scope>runtime</scope> + </dependency> + <dependency> + <groupId>javax.ws.rs</groupId> + <artifactId>jsr311-api</artifactId> + <version>1.1.1</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-rt-frontend-jaxws</artifactId> + <version>${cxf.version}</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-rt-transports-http</artifactId> + <version>${cxf.version}</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-rt-frontend-jaxrs</artifactId> + <version>${cxf.version}</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-tools-java2ws</artifactId> + <version>${cxf.version}</version> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.2.4</version> + </dependency> + <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + <version>3.4</version> + </dependency> + <dependency> + <groupId>mysql</groupId> + <artifactId>mysql-connector-java</artifactId> + <version>5.1.47</version> + </dependency> + <dependency> + <groupId>io.jsonwebtoken</groupId> + <artifactId>jjwt</artifactId> + <version>0.6.0</version> + </dependency> + <dependency> + <groupId>commons-dbcp</groupId> + <artifactId>commons-dbcp</artifactId> + </dependency> + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + <version>2.3</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <optional>true</optional> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + <version>3.7</version> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + <configuration> + <executable>true</executable> + <addResources>true</addResources> + </configuration> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>io.fabric8</groupId> + <artifactId>docker-maven-plugin</artifactId> + <extensions>true</extensions> + + <configuration> + <images> + <image> + <name>springboot-jwt</name> + <alias>springboot-jwt</alias> + <build> + <filter>@</filter> + <dockerFileDir>${project.basedir}/src/main/docker</dockerFileDir> + <assembly> + <descriptorRef>artifact</descriptorRef> + </assembly> + </build> + <run> + <namingStrategy>alias</namingStrategy> + <ports> + <port>${tomcat.port}:8080</port> + </ports> + <wait> + <http> + <url>http://${tomcat.ip}:${tomcat.port}/health</url> + </http> + <time>90000</time> + </wait> + </run> + </image> + </images> + </configuration> + + </plugin> + </plugins> + </build> + +</project> diff --git a/src/main/java/com/tarento/retail/Application.java b/src/main/java/com/tarento/retail/Application.java new file mode 100644 index 0000000000000000000000000000000000000000..98797da333498a5be50f11101c92c154750e72ea --- /dev/null +++ b/src/main/java/com/tarento/retail/Application.java @@ -0,0 +1,38 @@ +package com.tarento.retail; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import com.tarento.retail.util.Constants; + + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurerAdapter() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**").allowedMethods(Constants.GET, Constants.POST,Constants.PUT, Constants.DELETE, Constants.OPTIONS).allowedOrigins("*") + .allowedHeaders("*"); + } + }; + } + + @Bean + public TokenStore tokenStore() { + return new InMemoryTokenStore(); + } + +} diff --git a/src/main/java/com/tarento/retail/Test.java b/src/main/java/com/tarento/retail/Test.java new file mode 100644 index 0000000000000000000000000000000000000000..292efc2404a7e402335d20b936506b22ba0bba40 --- /dev/null +++ b/src/main/java/com/tarento/retail/Test.java @@ -0,0 +1,21 @@ +package com.tarento.retail; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + + +public class Test { + + + + public static void main(String[] args) { + // TODO Auto-generated method stub + String pass= "admin@123"; + BCryptPasswordEncoder encoder =new BCryptPasswordEncoder(); + String val =encoder.encode(pass); + + System.out.println(val); + + } + +} diff --git a/src/main/java/com/tarento/retail/config/CORSFilter.java b/src/main/java/com/tarento/retail/config/CORSFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..6a30d541dafd356fface661e5afccc5d69b9af1b --- /dev/null +++ b/src/main/java/com/tarento/retail/config/CORSFilter.java @@ -0,0 +1,32 @@ +package com.tarento.retail.config; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; + + +public class CORSFilter implements Filter { + + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { + System.out.println("Filtering on..........................................................."); + HttpServletResponse response = (HttpServletResponse) res; + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Credentials", "true"); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers"); + + chain.doFilter(req, res); + } + + public void init(FilterConfig filterConfig) {} + + public void destroy() {} + +} \ No newline at end of file diff --git a/src/main/java/com/tarento/retail/config/JwtAuthenticationEntryPoint.java b/src/main/java/com/tarento/retail/config/JwtAuthenticationEntryPoint.java new file mode 100644 index 0000000000000000000000000000000000000000..0d6390e7dd301758c9909a52827cdaac3f4170a9 --- /dev/null +++ b/src/main/java/com/tarento/retail/config/JwtAuthenticationEntryPoint.java @@ -0,0 +1,26 @@ +package com.tarento.retail.config; + +import java.io.IOException; +import java.io.Serializable; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +@Component +public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + public void commence(javax.servlet.http.HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { + httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/tarento/retail/config/JwtAuthenticationFilter.java b/src/main/java/com/tarento/retail/config/JwtAuthenticationFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..7af840aa7a6353be12fcfd4d03029127a30e0502 --- /dev/null +++ b/src/main/java/com/tarento/retail/config/JwtAuthenticationFilter.java @@ -0,0 +1,67 @@ +package com.tarento.retail.config; + +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.SignatureException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import static com.tarento.retail.util.Constants.HEADER_STRING; +import static com.tarento.retail.util.Constants.TOKEN_PREFIX; + +import java.io.IOException; +import java.util.Arrays; + +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private JwtTokenUtil jwtTokenUtil; + + @Override + protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { + String header = req.getHeader(HEADER_STRING); + logger.info("Method : " + req.getMethod()); + String username = null; + String authToken = null; + if (header != null && header.startsWith(TOKEN_PREFIX)) { + authToken = header.replace(TOKEN_PREFIX,""); + try { + username = jwtTokenUtil.getUsernameFromToken(authToken); + } catch (IllegalArgumentException e) { + logger.error("an error occured during getting username from token", e); + } catch (ExpiredJwtException e) { + logger.warn("the token is expired and not valid anymore", e); + } catch(SignatureException e){ + logger.error("Authentication Failed. Username or Password not valid."); + } + } else { + logger.warn("couldn't find bearer string, will ignore the header"); + } + if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { + + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + + if (authToken != null && jwtTokenUtil.validateToken(authToken, userDetails)) { + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"))); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req)); + logger.info("authenticated user " + username + ", setting security context"); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + } + + chain.doFilter(req, res); + } +} \ No newline at end of file diff --git a/src/main/java/com/tarento/retail/config/JwtTokenUtil.java b/src/main/java/com/tarento/retail/config/JwtTokenUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..d85210ce726e1c7f902b273199b7fa16ceef05f7 --- /dev/null +++ b/src/main/java/com/tarento/retail/config/JwtTokenUtil.java @@ -0,0 +1,82 @@ +package com.tarento.retail.config; + +import static com.tarento.retail.util.Constants.ACCESS_TOKEN_VALIDITY_SECONDS; +import static com.tarento.retail.util.Constants.JWT_GRANTED_AUTHORITY; +import static com.tarento.retail.util.Constants.JWT_ISSUER; +import static com.tarento.retail.util.Constants.SIGNING_KEY; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Date; +import java.util.function.Function; + +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import com.tarento.retail.model.User; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +@Component +public class JwtTokenUtil implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + public static final String CLAIMS_KEY = "scopes"; + + public String getUsernameFromToken(String token) { + return getClaimFromToken(token, Claims::getSubject); + } + + public Date getExpirationDateFromToken(String token) { + return getClaimFromToken(token, Claims::getExpiration); + } + + public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { + final Claims claims = getAllClaimsFromToken(token); + return claimsResolver.apply(claims); + } + + private Claims getAllClaimsFromToken(String token) { + return Jwts.parser() + .setSigningKey(SIGNING_KEY) + .parseClaimsJws(token) + .getBody(); + } + + private Boolean isTokenExpired(String token) { + final Date expiration = getExpirationDateFromToken(token); + return expiration.before(new Date()); + } + + public String generateToken(User user) { + return doGenerateToken(user.getUsername()); + } + + private String doGenerateToken(String subject) { + + Claims claims = Jwts.claims().setSubject(subject); + claims.put(CLAIMS_KEY, Arrays.asList(new SimpleGrantedAuthority(JWT_GRANTED_AUTHORITY))); + + return Jwts.builder() + .setClaims(claims) + .setIssuer(JWT_ISSUER) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALIDITY_SECONDS*1000)) + .signWith(SignatureAlgorithm.HS256, SIGNING_KEY) + .compact(); + } + + public Boolean validateToken(String token, UserDetails userDetails) { + final String username = getUsernameFromToken(token); + return ( + username.equals(userDetails.getUsername()) + && !isTokenExpired(token)); + } + +} diff --git a/src/main/java/com/tarento/retail/config/WebSecurityConfig.java b/src/main/java/com/tarento/retail/config/WebSecurityConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..eaab3e1748c276713821033dd466c182018f88ff --- /dev/null +++ b/src/main/java/com/tarento/retail/config/WebSecurityConfig.java @@ -0,0 +1,68 @@ +package com.tarento.retail.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +import javax.annotation.Resource; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Resource(name = "userService") + private UserDetailsService userDetailsService; + + @Autowired + private JwtAuthenticationEntryPoint unauthorizedHandler; + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Autowired + public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(encoder()); + } + + @Bean + public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception { + return new JwtAuthenticationFilter(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors().and().csrf().disable().authorizeRequests() + .antMatchers("/login", "/signup", "/user/role/mapping/delete", "/user/org/getCountryList", + "/user/getCountryList", "/token/validate", "/user/role/mapping", "/user/tokenValidate", + "/user/createOrUpdateCountry", "/user/createOrUpdate", "/user", "/user/getAllUser", + "/user/add/role", "/user/roles/{orgId}", "/user/user/{id}", "/images", "/user/actions/_get", + "/getUserDetails", "/getNumberOfUsers", "/upload", "/user/deleteCountry", "/user/deleteRole", + "/user/deleteUser", "/user/getMapActionToRole", "/user/getUnmapActionToRole", + "/user/mapActionToRole", "/user/unmapActionToRole", "/user/getUsersByMasterRole", + "/user/mapUserMasterRoleCountryOrg", "/user/getMasterRoleByOrgDomain","/user/domainRole","/user/getUsersByRole","/user/addOrgDomainRoles") + .permitAll().anyRequest().authenticated().and().exceptionHandling() + .authenticationEntryPoint(unauthorizedHandler).and().sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS); + http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); + } + + @Bean + public BCryptPasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/src/main/java/com/tarento/retail/controller/AuthenticationController.java b/src/main/java/com/tarento/retail/controller/AuthenticationController.java new file mode 100644 index 0000000000000000000000000000000000000000..c236a85fa6fdc895c8caa0d0b3879609225278be --- /dev/null +++ b/src/main/java/com/tarento/retail/controller/AuthenticationController.java @@ -0,0 +1,116 @@ +package com.tarento.retail.controller; + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.tarento.retail.config.JwtTokenUtil; +import com.tarento.retail.dao.impl.UserDaoImpl; +import com.tarento.retail.dto.UserDto; +import com.tarento.retail.model.LoginDto; +import com.tarento.retail.model.LoginUser; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.model.UserAuthentication; +import com.tarento.retail.service.UserService; +import com.tarento.retail.util.Constants; +import com.tarento.retail.util.PathRoutes; +import com.tarento.retail.util.ResponseGenerator; + +@RestController +public class AuthenticationController { + + public static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationController.class); + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private JwtTokenUtil jwtTokenUtil; + + @Autowired + private UserService userService; + + @Autowired + private UserDetailsService userDetailsService; + + @RequestMapping(value = PathRoutes.AuthenticationRoutes.AUTH_LOGIN_POST, method = RequestMethod.POST) + public String register(@RequestBody LoginUser loginUser) throws JsonProcessingException { + User user = null; + LOGGER.info(" Starting the Authentication Check on LOGIN "); + if (loginUser.getUsername() != null && loginUser.getPassword() != null)// && loginUser.getPhoneNo() == null) + { + final Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword())); + SecurityContextHolder.getContext().setAuthentication(authentication); + user = userService.findOne(loginUser.getUsername()); + LOGGER.info("Fetched a User for the Username "); + } else if (loginUser.getUsername() == null && loginUser.getPassword() == null + && loginUser.getPhoneNo() != null) { + user = userService.findMobile(loginUser.getPhoneNo()); + } else + return ResponseGenerator.failureResponse("Request Parameter mismatched"); + + if (user != null) { + final String token = jwtTokenUtil.generateToken(user); + UserAuthentication userAuthentication = new UserAuthentication(); + + userAuthentication.setUserId(user.getId()); + userAuthentication.setAuthToken(token); + userAuthentication = userService.save(userAuthentication); + LOGGER.info("Saving the User Authentication on Auth Records Log"); + List<Role> userRoles = userService.findAllRolesByUser(user.getId(), user.getOrgId()); + LOGGER.info("Fetched Roles Assigned for the User"); + LoginDto loginDto = new LoginDto(); + loginDto.setUserAvatarUrl(user.getAvatarUrl()); + loginDto.setAuthToken(token); + loginDto.setUsername(user.getUsername()); + loginDto.setUserId(user.getId()); + loginDto.setOrgId(user.getOrgId()); + loginDto.setCountryCode(user.getCountryCode()); + loginDto.setRoles(userRoles); + return ResponseGenerator.successResponse(loginDto); + } + return ResponseGenerator.failureResponse("Invalid credentials. Please retry"); + } + + @RequestMapping(value = PathRoutes.AuthenticationRoutes.AUTH_TOKEN_VALIDATE_POST, method = RequestMethod.POST) + public Object validateToken(@RequestBody LoginDto token, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) { + String username = ""; + String authTokenInfo = null; + if (token != null && StringUtils.isNotBlank(token.getAuthToken())) { + authTokenInfo = token.getAuthToken(); + username = jwtTokenUtil.getUsernameFromToken(token.getAuthToken()); + } else if (StringUtils.isNotBlank(authToken)) { + authTokenInfo = authToken; + username = jwtTokenUtil.getUsernameFromToken(authToken); + } + if(StringUtils.isNotBlank(username)) { + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + if (jwtTokenUtil.validateToken(authTokenInfo, userDetails)) { + UserDto userDto = userService.findUserRolesActions(username); + LOGGER.info(userDto.toString()); + return userDto; + } + } + + return null; + } + +} diff --git a/src/main/java/com/tarento/retail/controller/RoleActionController.java b/src/main/java/com/tarento/retail/controller/RoleActionController.java new file mode 100644 index 0000000000000000000000000000000000000000..c20485e1c137d956bff6f7830bdc11a6abe81c0c --- /dev/null +++ b/src/main/java/com/tarento/retail/controller/RoleActionController.java @@ -0,0 +1,252 @@ +package com.tarento.retail.controller; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.AuthenticationException; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.CreateOrgResponse; +import com.tarento.retail.dto.RoleActionDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.service.RoleActionService; +import com.tarento.retail.util.Constants; +import com.tarento.retail.util.CustomException; +import com.tarento.retail.util.CustomResponse; +import com.tarento.retail.util.PathRoutes; +import com.tarento.retail.util.ResponseGenerator; +import com.tarento.retail.util.ResponseMessages; +import com.tarento.retail.util.Sql.RoleAction; + +@RestController +@RequestMapping(PathRoutes.USER_ACTIONS_URL) +public class RoleActionController { + + @Autowired + private RoleActionService roleActionService; + + @RequestMapping(value = PathRoutes.RoleActionRoutes.LIST_ROLES_GET, method = RequestMethod.GET) + public List<Role> listRoles(@PathVariable(value = "orgId") Long orgCode) { + return roleActionService.getAllRoles(orgCode); + } + + @RequestMapping(value = PathRoutes.RoleActionRoutes.GET_DEFAULT_ROLES_BY_DOMAIN, method = RequestMethod.GET) + public Object listRolesByDomain(@RequestParam(value = "orgDomain") String orgDomain) + throws JsonProcessingException { + try { + return ResponseGenerator.successResponse(roleActionService.getAllRolesByDomain(orgDomain)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ORG_DOMAIN_CODE_UNAVAILABLE); + } + + @RequestMapping(value = PathRoutes.RoleActionRoutes.ADD_ROLE_POST, method = RequestMethod.POST) + public String saveRole(@RequestBody Role role, BindingResult result) + throws AuthenticationException, JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + + if (role != null) { + if (StringUtils.isBlank(role.getName())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_NAME_UNAVAILABLE); + } + } else { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_DETAILS_UNAVAILABLE); + } + + Role savedRole = roleActionService.saveRole(role); + if (savedRole != null) { + List<Role> savedRoles = new ArrayList<>(); + savedRoles.add(savedRole); + return ResponseGenerator.successResponse(savedRoles); + } else { + return ResponseGenerator.failureResponse(HttpStatus.SERVICE_UNAVAILABLE.toString()); + } + } + + @RequestMapping(value = PathRoutes.RoleActionRoutes.ROLE_BY_ID_GET, method = RequestMethod.GET) + public String getOne(@PathVariable(value = "id") Long id) throws JsonProcessingException { + return ResponseGenerator.successResponse(roleActionService.findById(id)); + } + + @RequestMapping(value = PathRoutes.RoleActionRoutes.UPDATE_ROLE_POST, method = RequestMethod.PUT) + public String update(@RequestBody Role role, BindingResult result) + throws AuthenticationException, JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + + if (role != null) { + if (role.getId() == null) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + if (StringUtils.isBlank(role.getName())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_NAME_UNAVAILABLE); + } + if (role.getId() <= 0) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_INVALID); + } + } else { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_DETAILS_UNAVAILABLE); + } + + Role savedRole = roleActionService.updateRole(role); + if (savedRole != null) { + List<Object> savedRoles = new ArrayList<>(); + savedRoles.add(savedRole); + return ResponseGenerator.successResponse(savedRoles); + } else { + return ResponseGenerator.failureResponse(HttpStatus.SERVICE_UNAVAILABLE.toString()); + } + } + + // This API is not in use and needs to be rewritten ..... ! + + @RequestMapping(value = PathRoutes.RoleActionRoutes.NEW_ACTION_POST, method = RequestMethod.POST) + public ResponseEntity<?> saveAction(@RequestBody Action action, BindingResult result) + throws AuthenticationException { + if (result.hasErrors()) { + return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); + } + + List<CustomException> validationExceptions = new ArrayList<>(); + if (action != null) { + if (StringUtils.isBlank("")) { + CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, + ResponseMessages.ErrorMessages.FEATURE_NAME_UNAVAILABLE, ResponseMessages.UNAVAILABLE, null); + validationExceptions.add(exception); + } + if (StringUtils.isBlank("")) { + CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, + ResponseMessages.ErrorMessages.FEATURE_CODE_UNAVAILABLE, ResponseMessages.UNAVAILABLE, null); + validationExceptions.add(exception); + } + // if(StringUtils.isBlank(action.getUrl())) { + // CustomException exception = new + // CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, + // ResponseMessages.ErrorMessages.FEATURE_URL_UNAVAILABLE, + // ResponseMessages.UNAVAILABLE, null); + // validationExceptions.add(exception); + // } + } else { + CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, + ResponseMessages.ErrorMessages.FEATURE_DETAILS_UNAVAILABLE, ResponseMessages.UNAVAILABLE, null); + validationExceptions.add(exception); + } + + if (!validationExceptions.isEmpty()) { + return new ResponseEntity<>(validationExceptions, HttpStatus.BAD_REQUEST); + } + Action savedAction = roleActionService.saveAction(action); + if (savedAction != null) { + List<Object> savedActions = new ArrayList<>(); + savedActions.add(savedAction); + return new ResponseEntity<>(new CustomResponse(HttpStatus.OK.toString(), + ResponseMessages.SuccessMessages.ACTION_ADDED, savedActions), HttpStatus.OK); + } else { + CustomException exception = new CustomException(ResponseMessages.ErrorMessages.CUSTOM_ERROR_ID, + ResponseMessages.ErrorMessages.FEATURE_DETAILS_NOTSAVED, ResponseMessages.INTERNAL_ERROR, null); + validationExceptions.add(exception); + return new ResponseEntity<>(validationExceptions, HttpStatus.SERVICE_UNAVAILABLE); + } + } + + // DELETE Role API by orgId and country ID + @RequestMapping(value = PathRoutes.RoleActionRoutes.DELETE_ROLE_POST, method = RequestMethod.POST) + public Object deleteRole(@RequestBody Role role, @RequestHeader(value = Constants.AUTH_HEADER) String authToken, + BindingResult result) throws JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + if (role != null) { + if (StringUtils.isBlank(role.getId().toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + } + return ResponseGenerator.successResponse(roleActionService.deleteRole(role)); + } + + // GET MAPPED ACTION LIST + @RequestMapping(value = PathRoutes.RoleActionRoutes.GET_MAP_ACTION_LIST, method = RequestMethod.GET) + public Object getMappedActionToRole(@RequestParam(value = "role_id", required = false) Long role_id, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + if (StringUtils.isBlank(role_id.toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + return ResponseGenerator.successResponse(roleActionService.getMappedActionToRole(role_id)); + } + + // GET UNMAPPED ACTION LIST + @RequestMapping(value = PathRoutes.RoleActionRoutes.GET_UNMAP_ACTION_LIST, method = RequestMethod.GET) + public Object getUnmappedActionToRole(@RequestParam(value = "role_id", required = false) Long role_id, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + if (StringUtils.isBlank(role_id.toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + return ResponseGenerator.successResponse(roleActionService.getUnmappedActionToRole(role_id)); + } + + // Map Action to Role + @RequestMapping(value = PathRoutes.RoleActionRoutes.MAP_ACTION_TO_ROLE, method = RequestMethod.POST) + public Object mapActionToRole(@RequestBody RoleActionDto role, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + if (StringUtils.isBlank(role.getRoleId().toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + return ResponseGenerator.successResponse(roleActionService.mapActionToRole(role)); + } + + // Unmap Action From Role + @RequestMapping(value = PathRoutes.RoleActionRoutes.UNMAP_ACTION_TO_ROLE, method = RequestMethod.POST) + public Object unmapActionToRole(@RequestBody RoleActionDto role, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + if (StringUtils.isBlank(role.getRoleId().toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + return ResponseGenerator.successResponse(roleActionService.unmapActionFromRole(role)); + } + + // GET USER LIST By ROLE_ID AND ORG_ID + @RequestMapping(value = PathRoutes.RoleActionRoutes.GET_USER_BY_ROLE_POST, method = RequestMethod.POST) + public Object getUsersByRoleIdAndOrgId(@RequestBody Role role, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + if (StringUtils.isBlank(role.getId().toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + if (StringUtils.isBlank(role.getOrgId().toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ORG_ID_UNAVAILABLE); + } + return ResponseGenerator.successResponse(roleActionService.getUsersByRoleId(role)); + } + + // Role Creation from Org Domain + @RequestMapping(value = PathRoutes.RoleActionRoutes.ADD_ORG_DOMAIN_ROLES, method = RequestMethod.POST) + public Object createRolesFromDomainRoleList(@RequestBody CreateOrgResponse res) throws JsonProcessingException { + + if (StringUtils.isBlank(res.getId().toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ORG_ID_UNAVAILABLE); + } + if (StringUtils.isBlank(res.getOrgDomain().toString())) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ORG_DOMAIN_CODE_UNAVAILABLE); + } + return ResponseGenerator.successResponse(roleActionService.addRolesFromOrgDomain(res)); + } + +} \ No newline at end of file diff --git a/src/main/java/com/tarento/retail/controller/UserController.java b/src/main/java/com/tarento/retail/controller/UserController.java new file mode 100644 index 0000000000000000000000000000000000000000..afb27b3337b4fc0512b78591935ed7342736791f --- /dev/null +++ b/src/main/java/com/tarento/retail/controller/UserController.java @@ -0,0 +1,513 @@ +package com.tarento.retail.controller; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.util.StreamUtils; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.tarento.retail.config.JwtTokenUtil; +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.UserCountryDto; +import com.tarento.retail.dto.UserDto; +import com.tarento.retail.dto.UserMasterRoleCountryOrgDto; +import com.tarento.retail.dto.UserMasterRoleDto; +import com.tarento.retail.dto.UserRoleDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Country; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.model.UserDeviceToken; +import com.tarento.retail.model.UserProfile; +import com.tarento.retail.model.contract.OTPValidationRequest; +import com.tarento.retail.model.contract.OrderConfirmationRequest; +import com.tarento.retail.model.contract.RoleActionRequest; +import com.tarento.retail.model.enums.EmploymentType; +import com.tarento.retail.service.UserService; +import com.tarento.retail.util.Constants; +import com.tarento.retail.util.PathRoutes; +import com.tarento.retail.util.ResponseGenerator; +import com.tarento.retail.util.ResponseMessages; + +@RestController +@RequestMapping(PathRoutes.USER_ACTIONS_URL) +public class UserController { + + @Autowired + private UserService userService; + + @Autowired + private JwtTokenUtil jwtTokenUtil; + + @Autowired + private UserDetailsService userDetailsService; + + public static final org.slf4j.Logger logger = LoggerFactory.getLogger(UserController.class); + + @PostMapping(PathRoutes.UserRoutes.USER_ACTIONS_POST) + public String getActions(@RequestBody RoleActionRequest roleActionRequest) throws JsonProcessingException { + List<Action> actions = userService.findAllActionsByRoleID(roleActionRequest.getRoleRequest().getRoles()); + return ResponseGenerator.successResponse(actions); + } + + @RequestMapping(value = PathRoutes.UserRoutes.COUNTRY_LIST_GET, method = RequestMethod.GET) + public String getUserCountryList(@RequestParam(value = "userId", required = false) Long userId, + ServletWebRequest request) throws JsonProcessingException { + if (userId != null) + return ResponseGenerator.successResponse(userService.getCountryListForUser(userId)); + else + return ResponseGenerator.successResponse(userService.getCountryList()); + } + + @RequestMapping(value = PathRoutes.UserRoutes.ORG_COUNTRY_LIST_GET, method = RequestMethod.GET) + public String getOrgCountryList(@RequestParam(value = "orgId", required = false) Long orgId, + ServletWebRequest request) throws JsonProcessingException { + if (orgId != null) + return ResponseGenerator.successResponse(userService.getCountryListForOrg(orgId)); + else + return ResponseGenerator.failureResponse("OrgId is empty"); + + } + + @RequestMapping(value = PathRoutes.UserRoutes.USER_COUNTRY_MAPPING_POST, method = RequestMethod.POST) + public String mapUserToCountry(@RequestBody UserCountryDto userCountry, BindingResult result) + throws JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + + if (userCountry != null && userCountry.getCountries() != null) { + if (userCountry.getCountries().isEmpty()) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.COUNTRY_ID_UNAVAILABLE); + } + if (userCountry.getUserId() == null) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.USER_ID_UNAVAILABLE); + } + } else { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.COUNTRY_DETAILS_UNAVAILABLE); + } + + Boolean mappingStatus = userService.mapUserToCountry(userCountry); + if (mappingStatus) { + return ResponseGenerator.successResponse(ResponseMessages.SuccessMessages.USER_COUNTRY_MAPPED); + } else { + return ResponseGenerator.failureResponse(HttpStatus.SERVICE_UNAVAILABLE.toString()); + } + } + + @RequestMapping(value = PathRoutes.UserRoutes.EMPLOYMENT_TYPES_GET, method = RequestMethod.GET) + public String getEmploymentTypeEnum() throws JsonProcessingException { + final List<Country> modelList = new ArrayList<>(); + for (final EmploymentType key : EmploymentType.values()) { + Country data = new Country(); + data.setKey(key.name()); + modelList.add(data); + } + return ResponseGenerator.successResponse(modelList); + } + + @RequestMapping(value = PathRoutes.UserRoutes.NUMBER_OF_USERS_GET, method = RequestMethod.GET) + public String getNumberOfUsers(@RequestParam(value = "role", required = false) Long role, + @RequestParam(value = "active", required = false) Boolean active) throws JsonProcessingException { + return ResponseGenerator.successResponse(userService.getNumberOfUsers(role, active)); + } + + @RequestMapping(value = PathRoutes.UserRoutes.NUMBER_OF_ROLES_GET, method = RequestMethod.GET) + public String getNumberOfRoles() throws JsonProcessingException { + return ResponseGenerator.successResponse(userService.getNumberOfRoles()); + } + + @RequestMapping(value = PathRoutes.UserRoutes.USER_BY_ID_GET, method = RequestMethod.GET) + public String getOne(@RequestParam(value = "id", required = true) Long id, + @RequestParam(value = "orgId", required = true) Long orgId) throws JsonProcessingException { + return ResponseGenerator.successResponse(userService.findById(id, orgId)); + } + + @RequestMapping(value = PathRoutes.UserRoutes.CREATE_UPDATE_USER_POST, method = RequestMethod.POST) + public String saveUser(@RequestBody UserProfile profile, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + + User user = userService.findOne(username); + + if (profile != null) { + if (StringUtils.isNotBlank(profile.getEmailId())) { + profile.setUsername(profile.getEmailId()); + } else { + ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.EMAIL_MANDATORY); + } + Long userId = userService.checkUserNameExists(profile.getEmailId(), profile.getPhoneNo()); + if (profile.getId() != null && profile.getId() > 0) { + if (userId.equals(profile.getId())) { + return ResponseGenerator.successResponse(userService.updateUserProfile(profile)); + } else { + return ResponseGenerator + .failureResponse(ResponseMessages.ErrorMessages.EMAIL_PHONE_ALREADY_EXISTS); + } + } else { + if (userId != null && userId > 0) { + return ResponseGenerator + .failureResponse(ResponseMessages.ErrorMessages.EMAIL_PHONE_ALREADY_EXISTS); + } + } + profile.setCreatedBy(user.getId()); + profile.setUpdatedBy(user.getId()); + profile = userService.saveUserProfile(profile); + UserCountryDto userCountryDto = new UserCountryDto(); + userCountryDto.setUserId(profile.getId()); + List<Country> country = new ArrayList<>(); + Country c = new Country(); + c.setId(profile.getCountryId()); + country.add(c); + userCountryDto.setCountries(country); + return ResponseGenerator.successResponse(userService.mapUserToCountry(userCountryDto)); + } + } + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + + @RequestMapping(value = PathRoutes.UserRoutes.USER_DEVICE_TOKEN_POST, method = RequestMethod.POST) + public String updateDeviceToken(@RequestBody UserDeviceToken deviceToken, + @RequestHeader(value = "x-user-info", required = false) String xUserInfo) throws JsonProcessingException { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + User thisUser = gson.fromJson(xUserInfo, User.class); + if (userService.checkUserTokenExists(thisUser.getId(), deviceToken.getDeviceToken())) { + return ResponseGenerator.successResponse("Success"); + } + Long authTokenRef = userService.fetchAuthTokenReference(thisUser.getAuthToken()); + Boolean updateStatus = userService.updateUserDeviceToken(thisUser.getId(), deviceToken.getDeviceToken(), + authTokenRef); + if (updateStatus) + return ResponseGenerator.successResponse("Success"); + + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + + @RequestMapping(value = PathRoutes.UserRoutes.LIST_USER_GET, method = RequestMethod.GET) + public String listUser(@RequestParam(value = "pageNumber", required = false) Integer pageNumber, + @RequestParam(value = "numberOfRecords", required = false) Integer numberOfRecords, + @RequestParam(value = "keyword", required = false) String keyword, + @RequestParam(value = "active", required = false) Boolean active, + @RequestParam(value = "roles", required = false) List<Long> roles, + @RequestParam(value = "countryCode", required = false) String countryCode, + @RequestParam(value = "orgId", required = true) Long orgId) throws JsonProcessingException { + return ResponseGenerator.successResponse( + userService.findAll(pageNumber, numberOfRecords, active, keyword, roles, countryCode, orgId)); + } + + @RequestMapping(value = PathRoutes.UserRoutes.REMOVE_ROLE_MAPPING, method = RequestMethod.POST) + public String deleteUserToRole(@RequestBody UserRoleDto userRole, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken, BindingResult result) + throws JsonProcessingException { + + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + + User user = userService.findOne(username); + if (userRole != null && userRole.getRoles() != null) { + if (userRole.getRoles().isEmpty()) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + } + if (userRole.getUserId() == null) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.USER_ID_UNAVAILABLE); + } + } else { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_DETAILS_UNAVAILABLE); + } + + Boolean mappingStatus = userService.deleteUserToRole(userRole); + if (mappingStatus) { + return ResponseGenerator.successResponse(ResponseMessages.SuccessMessages.REMOVE_USER_ROLE_MAPPED); + } else { + return ResponseGenerator.failureResponse(HttpStatus.SERVICE_UNAVAILABLE.toString()); + } + } + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.UNAUTHORIZED_ROLE_MAPPING_PERMISSION); + + } + + @RequestMapping(value = PathRoutes.UserRoutes.USER_ROLE_MAPPING_POST, method = RequestMethod.POST) + public String mapUserToRole(@RequestBody UserRoleDto userRole, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken, BindingResult result) + throws JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + + User user = userService.findOne(username); + + if (userRole != null && userRole.getRoles() != null) { + // if (userRole.getRoles().isEmpty()) { + // return + // ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_ID_UNAVAILABLE); + // } + if (userRole.getUserId() == null) { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.USER_ID_UNAVAILABLE); + } + } else { + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.ROLE_DETAILS_UNAVAILABLE); + } + + Boolean mappingStatus = userService.mapUserToRole(userRole); + if (mappingStatus) { + return ResponseGenerator.successResponse(ResponseMessages.SuccessMessages.USER_ROLE_MAPPED); + } else { + return ResponseGenerator.failureResponse(HttpStatus.SERVICE_UNAVAILABLE.toString()); + } + } + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.UNAUTHORIZED_ROLE_MAPPING_PERMISSION); + + } + + @RequestMapping(value = PathRoutes.UserRoutes.USER_DETAILS_GET, method = RequestMethod.GET) + public String getUserDetails(@RequestParam(value = "userIdList") List<Long> userIdList) + throws JsonProcessingException { + List<UserProfile> profileList = new ArrayList<>(); + if (userIdList != null && !userIdList.isEmpty()) { + profileList = userService.findListOfUsers(userIdList); + } + return ResponseGenerator.successResponse(profileList); + } + + @PostMapping(PathRoutes.UserRoutes.SINGLE_FILE_UPLOAD_POST) + public String singleFileUpload(@RequestParam("file") MultipartFile file, + @RequestParam(value = "userId", required = true) long userId) throws IOException { + return ResponseGenerator.successResponse(userService.uploadFile(file, userId)); + } + + @RequestMapping(value = PathRoutes.UserRoutes.IMAGE_GET, method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity<byte[]> getImage(@RequestParam String url) throws IOException { + File file = new File(Constants.UPLOADED_FOLDER + url); + InputStream targetStream = new FileInputStream(file); + byte[] bytes = StreamUtils.copyToByteArray(targetStream); + return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(bytes); + } + + @RequestMapping(value = PathRoutes.UserRoutes.LOGOUT_GET, method = RequestMethod.GET) + public String invalidateToken(@RequestHeader(value = Constants.AUTH_HEADER) String authToken) + throws JsonProcessingException { + Boolean status = false; + if (authToken != null) { + authToken = authToken.replace("Bearer ", ""); + status = userService.invalidateToken(authToken); + } + if (status) + return ResponseGenerator.successResponse(ResponseMessages.SuccessMessages.LOGOUT_SUCCESS); + return ResponseGenerator.failureResponse(ResponseMessages.ErrorMessages.LOGOUT_FAILED); + } + + /* + * -----------------------------------------------------STUBS--------------- + * ----------------------------------------------------- + */ + /* + * ------------------------------- Once the B17 Integration is added, these + * stubs will be removed ------------------------------- + */ + + @RequestMapping(value = "orderConfirmation", method = RequestMethod.POST) + public String orderConfirmation(@RequestBody OrderConfirmationRequest orderConfirmation) + throws JsonProcessingException { + return ResponseGenerator.successResponse("Success"); + } + + @RequestMapping(value = "otpvalidation", method = RequestMethod.POST) + public String otpValidation(@RequestBody OTPValidationRequest otpValidation) throws JsonProcessingException { + String otp = otpValidation.getOtp(); + if (otpValidation.isBypassFlag()) { + return ResponseGenerator.successResponse("Success"); + } + if (otp.equals("54321") || otp.equals("8088") || otp.equals("465842") || otp.equals("95000") + || otp.equals("96971")) { + return ResponseGenerator.successResponse("Success"); + } + return ResponseGenerator.failureResponse("Failed"); + } + + @RequestMapping(value = "getDeviceTokenForUserIds", method = RequestMethod.GET) + public List<UserDeviceToken> getUsersForAStore( + @RequestParam(value = "userIds", required = false) List<Long> userIdList) throws JsonProcessingException { + if (userIdList != null) { + List<UserDeviceToken> tokenList = userService.getDeviceTokenForUsers(userIdList); + if (tokenList != null) { + return tokenList; + } + return null; + } + return null; + } + + @RequestMapping(value = PathRoutes.UserRoutes.CREATE_UPDATE_COUNTRY, method = RequestMethod.POST) + public String createOrUpdateCountry(@RequestBody CountryDto country) throws JsonProcessingException { + if (country.getId() != null) { + return ResponseGenerator.successResponse(userService.updateCountry(country)); + } + // Check if country already exist + if (userService.checkCountryAlreadyExists(country.getCode(), country.getOrgId())) { + ResponseGenerator.failureResponse("Country With Same Code Exists"); + } + return ResponseGenerator.successResponse(userService.createCountry(country)); + } + + @RequestMapping(value = PathRoutes.AuthenticationRoutes.AUTH_TOKEN_VALIDATE_GET, method = RequestMethod.GET) + public Object validateUserToken(@RequestHeader(value = Constants.AUTH_HEADER) String authToken) + throws JsonProcessingException { + String username = ""; + String authTokenInfo = null; + if (StringUtils.isNotBlank(authToken)) { + authTokenInfo = authToken; + Boolean userTokenAvailable = userService.findUserByToken(authTokenInfo); + if (userTokenAvailable) + username = jwtTokenUtil.getUsernameFromToken(authTokenInfo); + } + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + + if (jwtTokenUtil.validateToken(authTokenInfo, userDetails)) { + UserDto userDto = new UserDto(); + User user = userService.findOne(username); + userDto.setId(user.getId()); + userDto.setUserName(user.getUsername()); + userDto.setEmailId(user.getEmailId()); + userDto.setRoles(userService.findAllRolesByUser(user.getId(), user.getOrgId())); + userDto.setActions(userService.findAllActionsByUser(user.getId(), user.getOrgId())); + userDto.setOrgId(user.getOrgId()); + userDto.setTimeZone(user.getTimeZone()); +// System.out.println("--------time zone------"+userDto.getTimeZone()); + return ResponseGenerator.successResponse(userDto); + } + return ResponseGenerator.failureResponse("Invalid Token"); + } + + // DELETE country by orgId and country ID + @RequestMapping(value = PathRoutes.UserRoutes.DELETE_COUNTRY, method = RequestMethod.POST) + public Object deleteCountryForOrg(@RequestBody CountryDto countryDto, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken, BindingResult result) + throws JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + User user = userService.findOne(username); + return ResponseGenerator.successResponse(userService.deleteCountryForOrg(countryDto)); + } + return ResponseGenerator.failureResponse("Invalid Token"); + } + + // DELETE user + @RequestMapping(value = PathRoutes.UserRoutes.DELETE_USER, method = RequestMethod.POST) + public Object deleteUser(@RequestBody UserDto userDto, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken, BindingResult result) + throws JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + User user = userService.findOne(username); + return ResponseGenerator.successResponse(userService.deleteUser(userDto)); + } + return ResponseGenerator.failureResponse("Invalid Token"); + } + + // User List based on ROLE and Org Domain + @RequestMapping(value = PathRoutes.UserRoutes.GET_USERS_BY_MASTER_ROLE, method = RequestMethod.GET) + public Object getUsersBasedOnManagerRole(@RequestParam(value = "role", required = true) String roleCode, + @RequestParam(value = "orgId", required = true) long orgId, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + User user = userService.findOne(username); + return ResponseGenerator.successResponse(userService.getUsersByMasterRole(roleCode, orgId)); + } + return ResponseGenerator.failureResponse("Invalid Token"); + } + + // Map user to country by master role id + @RequestMapping(value = PathRoutes.UserRoutes.MAP_USER_MASTER_ROLE_COUNTRY_ORG, method = RequestMethod.POST) + public Object mapUserMasterRoleCountryOrg(@RequestBody UserMasterRoleCountryOrgDto userMasterRoleCountryOrgDto, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken, BindingResult result) + throws JsonProcessingException { + if (result.hasErrors()) { + return ResponseGenerator.failureResponse(HttpStatus.UNPROCESSABLE_ENTITY.toString()); + } + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + User user = userService.findOne(username); + return ResponseGenerator + .successResponse(userService.mapUserMasterRoleCountryOrg(userMasterRoleCountryOrgDto)); + } + return ResponseGenerator.failureResponse("Invalid Token"); + } + + // GET MASTER ROLE + @RequestMapping(value = PathRoutes.RoleActionRoutes.GET_MASTER_ROLE_BY_ORG_DOMAIN, method = RequestMethod.GET) + public Object getMasterRoleBasedOnOrgDomain(@RequestParam Long org_domain_id, + @RequestHeader(value = Constants.AUTH_HEADER) String authToken) throws JsonProcessingException { + Boolean userTokenAvailable = userService.findUserByToken(authToken); + String username = ""; + + if (userTokenAvailable) { + username = jwtTokenUtil.getUsernameFromToken(authToken); + User user = userService.findOne(username); + return ResponseGenerator.successResponse(userService.getMasterRoleByOrgDomainId(org_domain_id)); + } + return ResponseGenerator.failureResponse("Invalid Token"); + } + +} diff --git a/src/main/java/com/tarento/retail/dao/RoleDao.java b/src/main/java/com/tarento/retail/dao/RoleDao.java new file mode 100644 index 0000000000000000000000000000000000000000..e186195ce17d4f5a6fb1d9a03dac6827ed37ff03 --- /dev/null +++ b/src/main/java/com/tarento/retail/dao/RoleDao.java @@ -0,0 +1,109 @@ +package com.tarento.retail.dao; + +import java.util.List; + +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.DomainRoleDto; +import com.tarento.retail.dto.RoleActionDto; +import com.tarento.retail.dto.RoleActionListDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.ActionRole; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.util.Sql.RoleAction; + +public interface RoleDao { + + /** + * Based on the ID passed, this method responds with a Role specific to the ID + * + * @param id + * @return + */ + public Role findOne(Long id); + + /** + * This method hits the DB and fetches all the available active roles + * + * @param fetchData + * @return + */ + public Boolean updateOrgRole(Long roleId, Long orgId); + + public List<Role> getAllRoles(Long orgCode); + + /** + * Based on the Role ID passed, this method responds with all the actions + * available for the specific role + * + * @param roleId + * @return + */ + public List<Action> findAllActionsByRole(Long roleId); + + /** + * This method is used to find a single action based on the Action ID which has + * been passed as a parameter + * + * @param id + * @return + */ + public Action findOneAction(Long id); + + /** + * This method is used to save the Role Details in the Database + * + * @param role + * @return + */ + public Role saveRole(Role role); + + /** + * This method is used to update the Role Details based on the Role ID passed in + * the Role Object + * + * @param role + * @return + */ + public Role updateRole(Role role); + + /** + * This method is used to save the Feature Details in the Database + * + * @param feature + * @return + */ + public Action saveAction(Action action); + + /** + * This method supplies the ID to Database and fetches the Role for the ID and + * returns the Role Object + * + * @param id + * @return + */ + public Role findById(Long id); + + public Role findById(Long userId, Long orgId); + + public Boolean deleteRole(Role role); + + public List<Action> getMappedActionRole(Long role); + + public List<Action> getUnmappedActionRole(Long role); + + public Boolean mapActionToRole(RoleActionDto roleAction); + + public Boolean mapAllActionsToRole(RoleActionListDto roleActionListDto); + + public Boolean unmapActionFromRole(RoleActionDto roleAction); + + public List<DomainRoleDto> getAllRolesByDomain(String orgDomain); + + public List<String> getDefaultRoles(Long roleId); + + public Boolean deleteOrgRole(Long roleId, Long orgId); + + public List<User> getUsersByRoleId(Role role); + +} diff --git a/src/main/java/com/tarento/retail/dao/UserDao.java b/src/main/java/com/tarento/retail/dao/UserDao.java new file mode 100644 index 0000000000000000000000000000000000000000..0c740f358881d444ca9af62262b729db40849389 --- /dev/null +++ b/src/main/java/com/tarento/retail/dao/UserDao.java @@ -0,0 +1,254 @@ +package com.tarento.retail.dao; + +import java.util.List; + +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.MasterRoleDto; +import com.tarento.retail.dto.UserCountryDto; +import com.tarento.retail.dto.UserDto; +import com.tarento.retail.dto.UserMasterRoleCountryOrgDto; +import com.tarento.retail.dto.UserRoleDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Country; +import com.tarento.retail.model.User; +import com.tarento.retail.model.UserAuthentication; +import com.tarento.retail.model.UserDeviceToken; +import com.tarento.retail.model.UserProfile; +import com.tarento.retail.model.mapper.SqlDataMapper.UserProfileMapper; +import com.tarento.retail.model.mapper.SqlDataMapper.UserRoleActionMapper; +import com.tarento.retail.model.mapper.SqlDataMapper.UserRoleMapper; + +public interface UserDao { + + /** + * This method is used to fetch the User high level Object from the database + * based on the username parameter which is being passed + * + * @param username + * @return + */ + public User findByUsername(String username); + + public User findOnlyUser(String username); + + /** + * This method is used to fetch the UserProfile Detailed object from the + * database based on the User ID which is being passed + * + * @param id + * @return + */ + public UserProfileMapper findOne(Long id, Long orgId); + + /** + * This method is used to fetch the UserProfile Detailed object from the + * database based on the User ID which is being passed + * + * @param id + * @return + */ + public UserProfileMapper findOneUser(Long id); + + public User findMobile(String phoneNo); + + /** + * This method receives the User ID and the List of Roles which are associated + * with the user Save the same to database for further Role Based Access + * + * @param userRole + * @return + */ + public Boolean mapUserToRole(UserRoleDto userRole); + + /** + * The detailed information about the user profile is received and the same gets + * stored into the database against the User ID which is put into the User + * table. + * + * @param profile + * @return + */ + public UserProfile saveUserProfile(UserProfile profile); + + /** + * This method receives the update on the Profile of the User and updates it + * against the data which is already available in the database + * + * @param profile + * @return + */ + public UserProfile updateUserProfile(UserProfile profile); + + /** + * This method receives the User Profile Object with updated Image URL and + * updates the same against the User ID + * + * @param profile + * @return + */ + public UserProfile updateUserProfileImage(UserProfile profile); + + /** + * While adding a new user to the system, this method is called with Email ID + * and Phone Number to verify whether there already exists a user with same + * username as that of the Email ID and Phone Number This method responds with a + * long value of the User ID if exists and returns 0 in the case of negative + * scenario + * + * @param emailId + * @param phoneNo + * @return + */ + public Long checkUserNameExists(String emailId, String phoneNo); + + /** + * On receiving the Role ID, this method fetches the Actions which are mapped to + * that role + * + * @param roleID + * @return + */ + public List<Action> findAllActionsByRoleID(Integer roleID); + + /** + * In order to show the count of Users available in the system, this method is + * invoked The method responds with the count of users available in the system + * + * @return + */ + public Long getNumberOfUsers(Long role, Boolean active); + + /** + * In order to show the count of Roles available in the system, this method is + * invoked The method responds with the count of roles available in the system + * + * @return + */ + public Long getNumberOfRoles(); + + /** + * This is method used to fetch the Country List from the database. The list of + * countries are sent as a response + * + * @return + */ + public List<Country> getCountryList(); + + /** + * This method receives the User ID and fetches the List of Country Objects for + * the User ID from the mapping table on the Database + * + * @param userId + * @return + */ + public List<Country> getCountryListForUser(Long userId); + + /** + * This method receives the List Country Codes and User ID to map the same + * against each other On mapping successfully, the boolean response is sent as a + * part of acknowledgement + * + * @param userCountry + * @return + */ + public Boolean mapUserToCountry(UserCountryDto userCountry); + + /** + * This method receives the JWT Auth Token and invalidates the token from the + * Jwt Token Store and also removes the entry of the Token from the Database + * + * @param authToken + * @return + */ + public Boolean invalidateToken(String authToken); + + /** + * This method receives the Auth Token and finds out whether there is an active + * user for that Authentication Token Auth Token in this method is the JWT Token + * + * @param authToken + * @return + */ + public Boolean findUserByToken(String authToken); + + /** + * This method receives the Auth Token of the FCM and verifies whether the token + * is already registered against any User ID or not. + * + * @param userId + * @param deviceToken + * @return + */ + public Boolean checkUserTokenExists(Long userId, String deviceToken); + + /** + * This method receives the Device Token and the User ID and updates it against + * the record which is already available in the system database + * + * @param userId + * @param deviceToken + * @return + */ + public Boolean updateUserDeviceToken(Long userId, String deviceToken); + + /** + * This method receives the Device Token and the User ID in the object and + * inserts the same in the Database for further processing + * + * @param userId + * @param deviceToken + * @return + */ + public Boolean insertUserDeviceToken(Long userId, String deviceToken, Long authTokenRef); + + /** + * This method receives the List of User IDs and fetches the FCM Device Token + * IDs for the User IDs and wraps it in the object and sends the list of it + * + * @param userIdList + * @return + */ + public List<UserDeviceToken> getDeviceTokenForUserList(List<Long> userIdList); + + public UserAuthentication findOneUserAuthentication(Long id); + + public UserProfileMapper findListOfUsers(List<Long> userIdList); + + public User save(User user); + + public UserAuthentication save(UserAuthentication user); + + public User update(User user); + + public UserProfileMapper findAll(Boolean active, String keyword, List<Long> roles, String countryCode, Long orgId); + + public UserRoleMapper findAllRolesByUser(Long userId, String orgId); + + public Long fetchAuthTokenReference(String authToken); + + public List<Action> findAllActionsByRoleIDs(List<Long> roles); + + public Boolean saveCountry(CountryDto country); + + public Boolean updateCountry(CountryDto country); + + public List<Country> getCountryListForOrg(Long orgId); + + public Boolean checkCountryExistsWithCode(String code, Long orgId); + + public Boolean deleteUserToRole(UserRoleDto userRole); + + public Boolean deleteCountryForOrg(CountryDto country); + + public Boolean deleteUser(UserDto user); + + + Boolean mapUserMasterRoleCountryOrg(UserMasterRoleCountryOrgDto userMasterRoleCountryOrg); + + List<MasterRoleDto> getMasterRoleByOrgDomainId(Long id); + + UserRoleActionMapper findUserRolesActions(String username); + + public List<UserDto> getUsersByMasterRole(String roleCode, Long orgId); + +} diff --git a/src/main/java/com/tarento/retail/dao/impl/RoleDaoImpl.java b/src/main/java/com/tarento/retail/dao/impl/RoleDaoImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f86f72a932a61dfc8d6998e20e11896501989e2c --- /dev/null +++ b/src/main/java/com/tarento/retail/dao/impl/RoleDaoImpl.java @@ -0,0 +1,336 @@ +package com.tarento.retail.dao.impl; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Repository; + +import com.mysql.jdbc.PreparedStatement; +import com.tarento.retail.dao.RoleDao; +import com.tarento.retail.dto.DomainRoleDto; +import com.tarento.retail.dto.RoleActionDto; +import com.tarento.retail.dto.RoleActionListDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.ActionRole; +import com.tarento.retail.model.Country; +import com.tarento.retail.model.OrgDomaiRole; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.model.mapper.SqlDataMapper; +import com.tarento.retail.util.Constants; +import com.tarento.retail.util.Sql; +import com.tarento.retail.util.Sql.Common; +import com.tarento.retail.util.Sql.RoleAction; +import com.tarento.retail.util.Sql.UserQueries; + +@Repository(Constants.ROLE_DAO) +public class RoleDaoImpl implements RoleDao { + + public static final Logger LOGGER = LoggerFactory.getLogger(RoleDaoImpl.class); + + @Autowired + JdbcTemplate jdbcTemplate; + + public Role findOne(Long id) { + Role role = null; + try { + role = jdbcTemplate + .query(RoleAction.SELECT_ROLES_ON_ID, new Object[] { id }, new SqlDataMapper().new RoleMapper()) + .get(0); + } catch (Exception e) { + System.out.print(e.getMessage()); + } + return role; + } + + @Override + public List<Action> findAllActionsByRole(Long roleId) { + List<ActionRole> actionRoles = new ArrayList<ActionRole>(); + try { + actionRoles = jdbcTemplate.query(RoleAction.SELECT_ROLE_ACTIONS_ON_ROLEID, new Object[] { roleId }, + new SqlDataMapper().new ActionRoleMapper()); + } catch (Exception e) { + System.out.print(e.getMessage()); + } + + List<Action> actions = new ArrayList<Action>(); + for (ActionRole actionRole : actionRoles) { + actions.add(findOneAction(actionRole.getActionId())); + } + return actions; + } + + public Action findOneAction(Long id) { + Action action = null; + try { + action = jdbcTemplate + .query(RoleAction.SELECT_ACTIONS_ON_ID, new Object[] { id }, new SqlDataMapper().new ActionMapper()) + .get(0); + } catch (Exception e) { + System.out.print(e.getMessage()); + } + return action; + } + + @Override + public Role saveRole(Role role) { + try { + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(new PreparedStatementCreator() { + public java.sql.PreparedStatement createPreparedStatement(Connection con) throws SQLException { + String[] returnValColumn = new String[] { "id" }; + java.sql.PreparedStatement statement = con.prepareStatement(Sql.RoleAction.SAVE_NEW_ROLE, + returnValColumn); + statement.setString(1, role.getName()); + statement.setString(2, role.getCode()); + statement.setString(3, role.getDescription()); + statement.setBoolean(4, role.isAdmin()); + statement.setLong(5, role.getOrgId()); + return statement; + } + }, keyHolder); + Long id = keyHolder.getKey().longValue(); + role.setId(id); + } catch (Exception ex) { + LOGGER.error("Encountered an exception while saving the Role Details : " + ex); + } + + return role; + } + + @Override + public Role updateRole(Role role) { + int updateRole = 0; + try { + updateRole = jdbcTemplate.update(RoleAction.UPDATE_ROLE, + new Object[] { role.getName(), role.getDescription(), role.getId() }); + } catch (Exception ex) { + LOGGER.error("Encountered an exception while saving the Role Details : " + ex); + } + if (updateRole > 0) { + return role; + } + return null; + } + + // Method needs rework as the logic has changed + @Override + public Action saveAction(Action action) { + /* + * int saveAction = 0; try{ saveAction = + * jdbcTemplate.update(RoleAction.INSERT_ACTION, new + * Object[]{action.getDescription(), action.getModuleCode(), + * action.getModuleName(), action.getUrl()}); } catch (Exception ex){ + * LOGGER.error("Encountered an exception while saving the Feature Details : " + + * ex); } if(saveAction > 0) { return action; } + */ + return null; + } + + @Override + public List<Role> getAllRoles(Long orgCode) { + List<Role> roleList = null; + try { + roleList = jdbcTemplate.query(RoleAction.GET_ALL_ROLES, new Object[] { orgCode }, + new SqlDataMapper().new RoleMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching all roles" + e); + } + return roleList; + } + + @Override + public List<DomainRoleDto> getAllRolesByDomain(String orgDomain) { + List<DomainRoleDto> roleList = null; + try { + roleList = jdbcTemplate.query(RoleAction.GET_ROLE_BY_ORG_DOMAIN, new Object[] { orgDomain }, + new SqlDataMapper().new DomainRoleMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching all roles" + e); + } + return roleList; + } + + @Override + public Role findById(Long id) { + List<Role> roleList = null; + try { + roleList = jdbcTemplate.query(RoleAction.SELECT_ROLES_ON_ID, new Object[] { id }, + new SqlDataMapper().new RoleOrgDomainMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching all roles" + e); + } + if (roleList != null && !roleList.isEmpty()) { + return roleList.get(0); + } + return null; + } + + @Override + public Role findById(Long userId, Long orgId) { + List<Role> roleList = null; + try { + roleList = jdbcTemplate.query(RoleAction.GET_ROLE_BY_USER, new Object[] { userId, orgId }, + new SqlDataMapper().new RoleMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching all roles" + e); + } + if (roleList != null && !roleList.isEmpty()) { + return roleList.get(0); + } + return null; + } + + @Override + public Boolean deleteRole(Role role) { + try { + // jdbcTemplate.update(RoleAction.DELETE_ROLE, new Object[] { role.getId() }); + jdbcTemplate.update(RoleAction.DELETE_ROLE, new Object[] { role.getId() }); + } catch (Exception ex) { + LOGGER.error("Encounter an exception while deleting the role: " + ex); + return Boolean.FALSE; + } + return Boolean.FALSE; + } + + @Override + public List<Action> getMappedActionRole(Long role_id) { + List<Action> action = null; + try { + action = jdbcTemplate.query(RoleAction.GET_MAPPED_ACTION_ROLE_LIST, new Object[] { role_id }, + new SqlDataMapper().new ActionMapper()); + } catch (Exception e) { + LOGGER.error("Encounter an exception while getting the map action list"); + } + return action; + } + + @Override + public List<Action> getUnmappedActionRole(Long role_id) { + List<Action> action = null; + try { + action = jdbcTemplate.query(RoleAction.GET_UNMAPPED_ACTION_ROLE_LIST, new Object[] { role_id }, + new SqlDataMapper().new ActionMapper()); + } catch (Exception e) { + LOGGER.error("Encounter an exception while getting the unmap action list"); + } + return action; + } + + @Override + public Boolean mapActionToRole(RoleActionDto roleAction) { + int updateRole = 0; + try { + updateRole = jdbcTemplate.update(RoleAction.MAP_ACTION_TO_ROLE, + new Object[] { roleAction.getRoleId(), roleAction.getActionId() }); + } catch (Exception e) { + LOGGER.error("Encounter an exception while doing the map action to role"); + } + if (updateRole > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + @Override + public Boolean mapAllActionsToRole(RoleActionListDto roleActionListDto) { + int[] values = null; + try { + values = jdbcTemplate.batchUpdate(RoleAction.MAP_ACTION_TO_ROLE, new BatchPreparedStatementSetter() { + @Override + public void setValues(java.sql.PreparedStatement statement, int i) throws SQLException { + statement.setLong(1, roleActionListDto.getRole_id()); + statement.setLong(2, roleActionListDto.getActionIds().get(i)); + } + + public int getBatchSize() { + return roleActionListDto.getActionIds().size(); + } + }); + } catch (Exception ex) { + LOGGER.error("Exception Occured while mapping Role to Action : " + ex); + } + if (values.length > 0) { + return true; + } + + return Boolean.FALSE; + } + + @Override + public Boolean unmapActionFromRole(RoleActionDto roleAction) { + int updateRole = 0; + try { + updateRole = jdbcTemplate.update(RoleAction.UNMAP_ACTION_TO_ROLE, + new Object[] { roleAction.getActionId(), roleAction.getRoleId() }); + } catch (Exception e) { + LOGGER.error("encounter an exception while doing the unmap action from role"); + } + if (updateRole > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + @Override + public Boolean updateOrgRole(Long roleId, Long orgId) { + int updateRole = 0; + try { + updateRole = jdbcTemplate.update(RoleAction.UPDATE_ROLE_ORG, new Object[] { roleId, orgId }); + } catch (Exception e) { + LOGGER.error("Encounter an exception while doing the map action to role"); + } + if (updateRole > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + @Override + public List<String> getDefaultRoles(Long roleId) { + List<String> ids = null; + try { + ids = jdbcTemplate.query(RoleAction.GET_DEFAULT_ROLES, new Object[] { roleId }, + new SqlDataMapper().new OrgDomainRoleMapper()); + } catch (Exception e) { + LOGGER.error("Encounter an exception while getting the unmap action list"); + } + return ids; + } + + @Override + public Boolean deleteOrgRole(Long roleId, Long orgId) { + int updateRole = 0; + try { + updateRole = jdbcTemplate.update(RoleAction.UNMAP_ORG_ROLE, new Object[] { roleId, orgId }); + } catch (Exception e) { + LOGGER.error("Encounter an exception while doing the map action to role"); + } + if (updateRole > 0) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + @Override + public List<User> getUsersByRoleId(Role role) { + ArrayList<User> users = null; + try { + users = (ArrayList<User>) jdbcTemplate.query(RoleAction.GET_USERS_BY_ROLE_ID, + new Object[] { role.getId(), role.getOrgId() }, new SqlDataMapper().new UserDetailsMapper()); + } catch (Exception e) { + LOGGER.error("Encounter an exception while getting the user list by role id" + e); + } + return users; + } +} diff --git a/src/main/java/com/tarento/retail/dao/impl/UserDaoImpl.java b/src/main/java/com/tarento/retail/dao/impl/UserDaoImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a80535175e302f66124571aa336f7ead9ccbd85f --- /dev/null +++ b/src/main/java/com/tarento/retail/dao/impl/UserDaoImpl.java @@ -0,0 +1,821 @@ +package com.tarento.retail.dao.impl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Repository; + +import com.tarento.retail.dao.RoleDao; +import com.tarento.retail.dao.UserDao; +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.MasterRoleDto; +import com.tarento.retail.dto.UserCountryDto; +import com.tarento.retail.dto.UserDto; +import com.tarento.retail.dto.UserMasterRoleCountryOrgDto; +import com.tarento.retail.dto.UserRoleDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Country; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.model.UserAuthentication; +import com.tarento.retail.model.UserDeviceToken; +import com.tarento.retail.model.UserProfile; +import com.tarento.retail.model.mapper.SqlDataMapper; +import com.tarento.retail.model.mapper.SqlDataMapper.UserProfileMapper; +import com.tarento.retail.model.mapper.SqlDataMapper.UserRoleActionMapper; +import com.tarento.retail.model.mapper.SqlDataMapper.UserRoleMapper; +import com.tarento.retail.util.Constants; +import com.tarento.retail.util.Sql; +import com.tarento.retail.util.Sql.Common; +import com.tarento.retail.util.Sql.UserQueries; + +@Repository(Constants.USER_DAO) + +public class UserDaoImpl implements UserDao { + + public static final Logger LOGGER = LoggerFactory.getLogger(UserDaoImpl.class); + + @Autowired + JdbcTemplate jdbcTemplate; + + @Autowired + RoleDao roleDao; + + @Override + public List<Action> findAllActionsByRoleID(Integer roleID) { + List<Action> actions = new ArrayList<Action>(); + try { + actions = jdbcTemplate.query(UserQueries.GET_USER_ACTIONS, new Object[] { roleID }, + new SqlDataMapper().new ActionMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching all the actions by Role ID " + e); + } + return actions; + } + + @Override + public User findByUsername(String username) { + User user = null; + try { + user = jdbcTemplate.query(UserQueries.SELECT_USER_ON_USERNAME, new Object[] { username, username }, + new SqlDataMapper().new UserMapper()).get(0); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching the User by Username : " + e); + } + return user; + } + + @Override + public UserProfileMapper findOne(Long id, Long orgId) { + UserProfileMapper mapper = new SqlDataMapper().new UserProfileMapper(); + try { + jdbcTemplate.query(UserQueries.USER_PROFILE_FETCH + Common.WHERE_CLAUSE + + UserQueries.USER_ID_EQUAL_CONDITION + UserQueries.AND_CONDITION + UserQueries.USER_ORG_ID, + new Object[] { id, orgId }, mapper); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching the User By ID : " + e); + } + return mapper; + } + + @Override + public UserProfileMapper findOneUser(Long id) { + UserProfileMapper mapper = new SqlDataMapper().new UserProfileMapper(); + try { + jdbcTemplate.query(UserQueries.GET_USER_BY_ID, new Object[] { id }, mapper); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching the User By ID : " + e); + } + return mapper; + } + + @Override + public UserAuthentication findOneUserAuthentication(Long id) { + UserAuthentication user = null; + try { + user = jdbcTemplate.query(UserQueries.GET_USER_AUTH_DETAILS, new Object[] { id }, + new SqlDataMapper().new UserAuthenticationMapper()).get(0); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching the Users Auth Details : " + e); + } + return user; + } + + @Override + public User save(final User user) { + User user1 = new User(); + try { + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(new PreparedStatementCreator() { + public PreparedStatement createPreparedStatement(Connection con) throws SQLException { + String[] returnValColumn = new String[] { "id" }; + PreparedStatement statement = con.prepareStatement(UserQueries.SAVE_USER, returnValColumn); + statement.setString(1, user.getUsername()); + statement.setString(2, user.getPassword()); + statement.setString(3, user.getEmailId()); + statement.setString(4, user.getPhoneNo()); + statement.setBoolean(5, user.getIsActive()); + statement.setBoolean(6, (user.getIsDeleted() != null) ? user.getIsDeleted() : Boolean.FALSE); + statement.setString(7, user.getOrgId()); + statement.setString(8, user.getTimeZone()); + statement.setString(9, user.getAvatarUrl()); + return statement; + } + }, keyHolder); + Long id = keyHolder.getKey().longValue(); + user.setId(id); + } catch (Exception e) { + LOGGER.error("Encountered an exception while saving new user : " + e); + } + return user; + } + + @Override + public UserAuthentication save(final UserAuthentication user) { + UserAuthentication user1 = new UserAuthentication(); + try { + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(new PreparedStatementCreator() { + public PreparedStatement createPreparedStatement(Connection con) throws SQLException { + String[] returnValColumn = new String[] { "id" }; + PreparedStatement statement = con.prepareStatement(UserQueries.SAVE_USER_AUTHENTICATION, + returnValColumn); + statement.setLong(1, user.getUserId()); + statement.setString(2, user.getAuthToken()); + return statement; + } + }, keyHolder); + Long id = keyHolder.getKey().longValue(); + System.out.println(id); + user1 = this.findOneUserAuthentication(id); + + } catch (Exception e) { + LOGGER.error("Encountered an exception while saving User Authentication : " + e); + } + return user1; + } + + @Override + public User update(final User user) { + try { + jdbcTemplate.update(UserQueries.UPDATE_USER, + new Object[] { user.getEmailId(), user.getUsername(), user.getPhoneNo(), user.getIsActive(), + (user.getIsDeleted() != null) ? user.getIsDeleted() : Boolean.FALSE, user.getTimeZone(), + user.getAvatarUrl(), user.getId() }); + } catch (Exception e) { + LOGGER.error("Encountered an error while updating User Object : " + e); + } + return user; + } + + @Override + public UserProfileMapper findAll(Boolean active, String keyword, List<Long> roles, String countryCode, Long orgId) { + List<Object> preparedStatementValues = new ArrayList<>(); + UserProfileMapper mapper = new SqlDataMapper().new UserProfileMapper(); + try { + String queryToExecute = BuildMyQuery(active, keyword, preparedStatementValues, roles, countryCode, orgId); + LOGGER.info("Query to fetch is ::: " + queryToExecute); + LOGGER.info("Prepared Statement Values passed for Query ::: " + preparedStatementValues.toString()); + jdbcTemplate.query(queryToExecute, preparedStatementValues.toArray(), mapper); + + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching the User Profile : " + e); + } + return mapper; + } + + private String BuildMyQuery(Boolean active, String keyword, List preparedStatementValues, List<Long> roles, + String countryCode, Long orgId) { + StringBuilder builder = new StringBuilder(); + StringBuilder keywordBuilder = new StringBuilder(); + if (StringUtils.isNotBlank(keyword)) { + keywordBuilder.append("%" + keyword + "%"); + } + + builder.append(UserQueries.USER_PROFILE_FETCH); + if (active != null || StringUtils.isNotBlank(keyword) || roles != null || StringUtils.isNotBlank(countryCode) + || StringUtils.isNotBlank(orgId.toString())) { + builder.append(Common.WHERE_CLAUSE); + Boolean andRequired = false; + if (active != null) { + if (active) + builder.append(UserQueries.TAIL_CONDITIONS_USER_ACTIVE); + else + builder.append(UserQueries.TAIL_CONDITIONS_USER_INACTIVE); + andRequired = true; + } + + if (StringUtils.isNotBlank(countryCode)) { + if (andRequired) + builder.append(Common.AND_CONDITION); + builder.append(UserQueries.TAIL_CONDITIONS_COUNTRY_EQUALS); + if (countryCode.equals(Constants.CountryList.SWE.toString())) + preparedStatementValues.add(Constants.CountryList.SWE.getName()); + else if (countryCode.equals(Constants.CountryList.FIN.toString())) + preparedStatementValues.add(Constants.CountryList.FIN.getName()); + else if (countryCode.equals(Constants.CountryList.NOR.toString())) + preparedStatementValues.add(Constants.CountryList.NOR.getName()); + else if (countryCode.equals(Constants.CountryList.IND.toString())) + preparedStatementValues.add(Constants.CountryList.IND.getName()); + } + if (StringUtils.isNotBlank(keyword)) { + if (andRequired) + builder.append(Common.AND_CONDITION); + builder.append(Common.OPEN_BRACE + UserQueries.TAIL_CONDITIONS_EMAIL_LIKE + Common.OR_CONDITION + + UserQueries.TAIL_CONDITIONS_FIRSTNAME_LIKE + Common.OR_CONDITION + + UserQueries.TAIL_CONDITIONS_LASTNAME_LIKE + Common.OR_CONDITION + + UserQueries.TAIL_CONDITIONS_COUNTRY_LIKE + Common.CLOSE_BRACE); + preparedStatementValues.add(keywordBuilder.toString()); + preparedStatementValues.add(keywordBuilder.toString()); + preparedStatementValues.add(keywordBuilder.toString()); + preparedStatementValues.add(keywordBuilder.toString()); + andRequired = true; + } + + if (roles != null && !roles.isEmpty()) { + if (andRequired) + builder.append(Common.AND_CONDITION); + builder.append(UserQueries.TAIL_CONDITIONS_USER_ROLEIN + getIdQuery(roles)); + } + // if (StringUtils.isNotBlank(orgId.toString())) { + // if (andRequired) { + // preparedStatementValues.add(orgId); + // builder.append("usrrole.org_id=?"); + // } + // } + + // builder.append(Common.AND_CONDITION).append(UserQueries.USER_ORG_ID); + builder.append(UserQueries.USER_ORG_ID); + preparedStatementValues.add(orgId); + builder.append(UserQueries.ORDER_BY_USER_ID); + // builder.append(UserQueries.USER_ORG_ID); + } + + return builder.toString(); + } + + private static String getIdQuery(final List<Long> idList) { + final StringBuilder query = new StringBuilder("("); + if (idList.size() >= 1) { + query.append(idList.get(0).toString()); + for (int i = 1; i < idList.size(); i++) + query.append(", " + idList.get(i)); + } + return query.append(")").toString(); + } + + @Override + public UserRoleMapper findAllRolesByUser(Long userId, String orgId) { + UserRoleMapper mapper = new SqlDataMapper().new UserRoleMapper(); + try { + jdbcTemplate.query(UserQueries.GET_ROLES_FOR_USER, new Object[] { userId, orgId }, mapper); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching the Roles for a User : " + e); + } + + return mapper; + } + + @Override + public User findMobile(String phoneNo) { + User user = null; + try { + user = jdbcTemplate.query(UserQueries.GET_USER_BY_PHONE, new Object[] { phoneNo }, + new SqlDataMapper().new UserMapper()).get(0); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching User by Mobile Number : " + e); + } + return user; + } + + @Override + public Boolean mapUserToRole(UserRoleDto userRole) { + try { + jdbcTemplate.update(UserQueries.REMOVE_USER_ROLE_MAP, new Object[] { userRole.getUserId() }); + } catch (Exception ex) { + LOGGER.error("Encountered an exception while removing the User Role mapping : " + ex); + } + + int[] values = null; + List<Role> roleList = userRole.getRoles(); + if (roleList.isEmpty()) { + return true; + } + try { + values = jdbcTemplate.batchUpdate(UserQueries.MAP_USER_TO_ROLE, new BatchPreparedStatementSetter() { + @Override + public void setValues(java.sql.PreparedStatement statement, int i) throws SQLException { + Role role = roleList.get(i); + statement.setLong(1, userRole.getUserId()); + statement.setLong(2, role.getId()); + statement.setLong(3, userRole.getOrgId()); + } + + public int getBatchSize() { + return roleList.size(); + } + }); + } catch (Exception ex) { + LOGGER.error("Exception Occured while adding Roles to User : " + ex); + } + if (values.length > 0) { + return true; + } + return false; + } + + @Override + public UserProfile saveUserProfile(UserProfile profile) { + try { + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(new PreparedStatementCreator() { + public PreparedStatement createPreparedStatement(Connection con) throws SQLException { + String[] returnValColumn = new String[] { "id" }; + PreparedStatement statement = con.prepareStatement(UserQueries.INSERT_USER_PROFILE, + returnValColumn); + statement.setLong(1, profile.getId()); + statement.setString(2, profile.getFirstName()); + statement.setString(3, profile.getLastName()); + statement.setInt(4, profile.getAge()); + statement.setString(5, profile.getPhoneNo()); + statement.setString(6, profile.getDob()); + statement.setString(7, profile.getGender()); + statement.setString(8, profile.getAvatarUrl()); + if (profile.getStartDate() != null) { + statement.setDate(9, new java.sql.Date(profile.getStartDate().getTime())); + } else { + statement.setDate(9, new java.sql.Date(new Date().getTime())); + } + if (profile.getEndDate() != null) { + statement.setDate(10, new java.sql.Date(profile.getEndDate().getTime())); + } else { + statement.setDate(10, new java.sql.Date(new Date().getTime())); + } + statement.setString(11, profile.getEmailId()); + statement.setString(12, profile.getCountry()); + if (profile.getRegistrationDate() != null) { + statement.setDate(13, new java.sql.Date(profile.getRegistrationDate().getTime())); + } else { + statement.setDate(13, new java.sql.Date(new Date().getTime())); + } + statement.setLong(14, profile.getCreatedBy()); + statement.setDate(15, new java.sql.Date(new Date().getTime())); + statement.setLong(16, profile.getUpdatedBy()); + statement.setDate(17, new java.sql.Date(new Date().getTime())); + statement.setString(18, profile.getEmploymentType()); + return statement; + } + }, keyHolder); + Long id = keyHolder.getKey().longValue(); + profile.setProfileId(id); + } catch (Exception e) { + LOGGER.error("Encountered an error while creatin User Profile : " + e.getMessage()); + } + return profile; + } + + @Override + public UserProfile updateUserProfileImage(UserProfile profile) { + try { + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(new PreparedStatementCreator() { + public PreparedStatement createPreparedStatement(Connection con) throws SQLException { + String[] returnValColumn = new String[] { "id" }; + PreparedStatement statement = con.prepareStatement(UserQueries.Update_USER_PROFILE_PROFILE_IMAGE, + returnValColumn); + statement.setString(1, profile.getAvatarUrl()); + statement.setLong(2, profile.getId()); + return statement; + } + }, keyHolder); + } catch (Exception e) { + LOGGER.error("Encountered an error while updating User Profile image" + e); + } + return profile; + } + + @Override + public Long checkUserNameExists(String emailId, String phoneNo) { + Long userId = 0L; + try { + userId = jdbcTemplate.queryForObject( + "SELECT id FROM user WHERE username = ? OR email_id = ? OR phone_no = ? or username = ? ", + new Object[] { emailId, emailId, phoneNo, phoneNo }, Long.class); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while finding the UserName Availability : " + e); + } + return userId; + } + + @Override + public UserProfileMapper findListOfUsers(List<Long> userIdList) { + UserProfileMapper mapper = new SqlDataMapper().new UserProfileMapper(); + String query = buildMyQuery(userIdList); + LOGGER.info("Query to execute for fetching the User Profile : " + query); + try { + jdbcTemplate.query(query.toString(), new Object[] {}, mapper); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching the User By ID : " + e); + } + return mapper; + } + + private String buildMyQuery(List<Long> userIdList) { + StringBuilder builder = new StringBuilder( + UserQueries.USER_PROFILE_FETCH + Common.WHERE_CLAUSE + UserQueries.USER_ID_IN_CONDITION); + if (!userIdList.isEmpty()) { + builder.append("("); + for (int i = 0; i < userIdList.size(); i++) { + if (i == 0 && i == userIdList.size() - 1) { + builder.append(userIdList.get(i)); + } else if (i == userIdList.size() - 1) { + builder.append(userIdList.get(i)); + } else { + builder.append(userIdList.get(i) + ","); + } + } + builder.append(")"); + } + return builder.toString(); + } + + @Override + public UserProfile updateUserProfile(UserProfile profile) { + try { + if (profile.getRegistrationDate() != null) { + jdbcTemplate.update(UserQueries.UPDATE_USER_PROFILE, + new Object[] { profile.getFirstName(), profile.getLastName(), profile.getAge(), + profile.getPhoneNo(), profile.getDob(), profile.getGender(), profile.getStartDate(), + profile.getEndDate(), profile.getCountry(), new java.sql.Date(new Date().getTime()), 1L, + profile.getEmploymentType(), new java.sql.Date(profile.getRegistrationDate().getTime()), + profile.getAvatarUrl(), profile.getId() }); + } + } catch (Exception e) { + LOGGER.error("Encountered an error while updating User Profile Object : " + e.getMessage()); + } + return profile; + } + + @Override + public Long getNumberOfUsers(Long role, Boolean active) { + Long numberOfUsers = 0L; + try { + if (role != null) { + numberOfUsers = jdbcTemplate.queryForObject(UserQueries.GET_USER_COUNT_FOR_ROLE, new Object[] { role }, + Long.class); + } else if (active != null) { + numberOfUsers = jdbcTemplate.queryForObject(UserQueries.GET_USER_COUNT_ON_ACTIVE_STATUS, + new Object[] { active }, Long.class); + } else { + numberOfUsers = jdbcTemplate.queryForObject(UserQueries.GET_USER_COUNT, Long.class); + } + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching count of Users : " + e); + } + return numberOfUsers; + } + + @Override + public Long getNumberOfRoles() { + Long numberOfRoles = 0L; + try { + numberOfRoles = jdbcTemplate.queryForObject(UserQueries.GET_ROLE_COUNT, Long.class); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching count of Roles : " + e); + } + return numberOfRoles; + } + + @Override + public List<Country> getCountryList() { + List<Country> countryList = new ArrayList<>(); + try { + countryList = jdbcTemplate.query(Common.GET_COUNTRY_LIST, new SqlDataMapper().new CountryMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching Country List: " + e); + } + return countryList; + } + + @Override + public List<Country> getCountryListForUser(Long userId) { + List<Country> countryList = new ArrayList<>(); + try { + countryList = jdbcTemplate.query(Common.GET_COUNTRY_LIST_FOR_USER, new Object[] { userId }, + new SqlDataMapper().new CountryMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching Country List: " + e); + } + return countryList; + } + + @Override + public Boolean mapUserToCountry(UserCountryDto userCountry) { + try { + jdbcTemplate.update(UserQueries.REMOVE_USER_COUNTRY_MAP, new Object[] { userCountry.getUserId() }); + } catch (Exception ex) { + LOGGER.error("Encountered an exception while removing the User Country mapping : " + ex); + } + + int[] values = null; + try { + values = jdbcTemplate.batchUpdate(UserQueries.MAP_USER_TO_COUNTRY, new BatchPreparedStatementSetter() { + @Override + public void setValues(java.sql.PreparedStatement statement, int i) throws SQLException { + Country country = userCountry.getCountries().get(i); + statement.setLong(1, userCountry.getUserId()); + statement.setLong(2, country.getId()); + statement.setBoolean(3, (country.getIsDefault() != null) ? country.getIsDefault() : Boolean.FALSE); + } + + public int getBatchSize() { + return userCountry.getCountries().size(); + } + }); + } catch (Exception ex) { + LOGGER.error("Exception Occured while adding Countries to User : " + ex); + } + if (values.length > 0) { + return true; + } + return false; + } + + @Override + public Boolean invalidateToken(String authToken) { + try { + jdbcTemplate.update(UserQueries.REMOVE_USER_DEVICE_TOKEN, new Object[] { authToken }); + } catch (Exception e) { + LOGGER.error("Encountered an error while removing user device token: " + e.getMessage()); + return false; + } + + try { + jdbcTemplate.update(UserQueries.INVALIDATE_TOKEN, new Object[] { authToken }); + } catch (Exception e) { + LOGGER.error("Encountered an error while invalidating Auth Token : " + e.getMessage()); + return false; + } + return true; + } + + @Override + public Boolean findUserByToken(String authToken) { + Long countOfUsers = 0L; + try { + countOfUsers = jdbcTemplate.queryForObject(UserQueries.SELECT_USER_BY_TOKEN, new Object[] { authToken }, + Long.class); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching User by auth token: " + e); + } + if (countOfUsers > 0) + return true; + return false; + } + + @Override + public Boolean checkUserTokenExists(Long userId, String deviceToken) { + Long available = 0L; + try { + available = jdbcTemplate.queryForObject(UserQueries.CHECK_USER_DEVICE_TOKEN, + new Object[] { userId, deviceToken }, Long.class); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching User Device by Device token: " + e); + } + if (available > 0) + return true; + return false; + } + + @Override + public Boolean updateUserDeviceToken(Long userId, String deviceToken) { + try { + jdbcTemplate.update(UserQueries.UPDATE_USER_DEVICE_TOKEN, + new Object[] { deviceToken, new Date().getTime(), userId }); + } catch (Exception e) { + LOGGER.error("Encountered an error while updating User Device Token : " + e.getMessage()); + return false; + } + return true; + } + + @Override + public Boolean insertUserDeviceToken(Long userId, String deviceToken, Long authTokenRef) { + try { + jdbcTemplate.update(UserQueries.INSERT_USER_DEVICE_TOKEN, + new Object[] { userId, deviceToken, new Date().getTime(), authTokenRef }); + } catch (Exception e) { + LOGGER.error("Encountered an error while inserting new User Device Token : " + e.getMessage()); + return false; + } + return true; + } + + @Override + public List<UserDeviceToken> getDeviceTokenForUserList(List<Long> userIdList) { + List<UserDeviceToken> tokenList = new ArrayList<>(); + try { + tokenList = jdbcTemplate.query(UserQueries.FETCH_USER_DEVICE_TOKEN + getIdQuery(userIdList) + + UserQueries.USER_DEVICE_ROLE_CONDITION, new SqlDataMapper().new UserDeviceMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching User Device Token Map: " + e); + } + return tokenList; + } + + @Override + public Long fetchAuthTokenReference(String authToken) { + authToken = authToken.split(" ")[1]; + Long authTokenRef = 0L; + try { + authTokenRef = jdbcTemplate.queryForObject(UserQueries.FETCH_AUTH_TOKEN_REF, new Object[] { authToken }, + Long.class); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching User Device by Device token: " + e); + } + return authTokenRef; + } + + public List<Action> findAllActionsByRoleIDs(List<Long> roleIDs) { + String roleId = StringUtils.join(roleIDs, ','); + List<Action> actions = new ArrayList<Action>(); + try { + actions = jdbcTemplate.query(UserQueries.GET_USER_ACTIONS.replace("<roleIds>", roleId), + new SqlDataMapper().new ActionMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching all the actions by Role ID " + e); + } + return actions; + } + + @Override + public Boolean saveCountry(CountryDto country) { + try { + jdbcTemplate.update(UserQueries.ADD_NEW_COUNTRY, new Object[] { country.getCode(), country.getName(), + country.getCurrency(), country.getPhoneCode(), country.getLogoUrl(), country.getOrgId() }); + } catch (Exception ex) { + LOGGER.error("Encountered an exception while adding the country : " + ex); + return false; + } + return true; + } + + @Override + public Boolean updateCountry(CountryDto country) { + try { + jdbcTemplate.update(UserQueries.UPDATE_COUNTRY, new Object[] { country.getCode(), country.getName(), + country.getCurrency(), country.getPhoneCode(), country.getId() }); + } catch (Exception ex) { + LOGGER.error("Encountered an exception while updating the country : " + ex); + return false; + } + return true; + } + + @Override + public List<Country> getCountryListForOrg(Long orgId) { + List<Country> countryList = new ArrayList<>(); + try { + countryList = jdbcTemplate.query(Common.GET_COUNTRY_LIST_FOR_ORG, new Object[] { orgId }, + new SqlDataMapper().new CountryMapper()); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching Country List: " + e); + } + return countryList; + } + + @Override + public Boolean checkCountryExistsWithCode(String code, Long orgId) { + Country country = null; + try { + country = jdbcTemplate.query(UserQueries.GET_COUNTRY_BY_CODE, new Object[] { code, orgId }, + new SqlDataMapper().new CountryMapper()).get(0); + if (country != null && country.getId() != null) { + return true; + } + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching User by Mobile Number : " + e); + } + return false; + } + + @Override + public Boolean deleteUserToRole(UserRoleDto userRole) { + String role = ""; + for (int i = 0; i < userRole.getRoles().size(); i++) { + if (i == 0) { + role = role + userRole.getRoles().get(i).getId(); + } else { + role = role + "," + userRole.getRoles().get(i).getId(); + } + } + try { + jdbcTemplate.update(UserQueries.REMOVE_USER_ROLE_MAP + UserQueries.AND_CONDITION + + Sql.Common.BY_ROLE_ID.replace("<ROLE_ID>", role), new Object[] { userRole.getUserId() }); + } catch (Exception ex) { + LOGGER.error("Encountered an exception while removing the User Role mapping : " + ex); + return Boolean.FALSE; + } + return Boolean.TRUE; + } + + @Override + public Boolean deleteCountryForOrg(CountryDto country) { // my + try { + jdbcTemplate.update(Common.DELETE_COUNTRY_FOR_ORG, new Object[] { country.getId(), country.getOrgId() }); + } catch (Exception ex) { + LOGGER.error("Encounter an exception white deleting the country: " + ex); + return Boolean.FALSE; + } + return Boolean.FALSE; + } + + @Override + public Boolean deleteUser(UserDto user) { + try { + jdbcTemplate.update(Sql.UserQueries.DELETE_COUNTRY_USER, new Object[] { user.getId() }); + jdbcTemplate.update(Sql.UserQueries.DELETE_USER_ROLE, new Object[] { user.getId() }); + jdbcTemplate.update(Sql.UserQueries.DELETE_USER_PROFILE, new Object[] { user.getId() }); + jdbcTemplate.update(Sql.UserQueries.DELETE_USER, new Object[] { user.getId() }); + } catch (Exception ex) { + LOGGER.error("Encounter an exception while deleting the user: " + ex); + return Boolean.FALSE; + } + return Boolean.TRUE; + } + + @Override + public List<UserDto> getUsersByMasterRole(String roleCode, Long orgId) { + List<UserDto> userList = new ArrayList<UserDto>(); + try { + userList = jdbcTemplate.query(UserQueries.GET_USERS_BY_MASTER_ROLE, new Object[] { roleCode, orgId }, + new SqlDataMapper().new UserMasterRoleMapper()); + } catch (Exception ex) { + LOGGER.error("Encounter an exception while getting users which have master role access"); + } + return userList; + } + + @Override + public Boolean mapUserMasterRoleCountryOrg(UserMasterRoleCountryOrgDto userMasterRoleCountryOrg) { + try { + jdbcTemplate.update(Sql.UserQueries.MAP_USER_MASTER_ROLE_COUNTRY_ORG, + new Object[] { userMasterRoleCountryOrg.getMasterRoleId(), userMasterRoleCountryOrg.getCountryId(), + userMasterRoleCountryOrg.getUserId(), userMasterRoleCountryOrg.getOrgId() }); + } catch (Exception ex) { + LOGGER.error("Encounter an exception while mapping the user master_role country org : " + ex); + return Boolean.FALSE; + } + return Boolean.TRUE; + } + + @Override + public List<MasterRoleDto> getMasterRoleByOrgDomainId(Long org_domain_id) { + List<MasterRoleDto> masterRoleList = new ArrayList<MasterRoleDto>(); + + try { + masterRoleList = jdbcTemplate.query(UserQueries.GET_MASTER_ROLE_LIST_BY_ORG_DOMAIN, + new Object[] { org_domain_id }, new SqlDataMapper().new MasterRoleMapper()); + } catch (Exception ex) { + LOGGER.error("Encounter an exception while getting master role list"); + } + return masterRoleList; + } + + @Override + public UserRoleActionMapper findUserRolesActions(String username) { + UserRoleActionMapper mapper = new SqlDataMapper().new UserRoleActionMapper(); + try { + jdbcTemplate.query(UserQueries.GET_USER_ROLE_ACTIONS, + new Object[] { username }, mapper); + } catch (Exception e) { + LOGGER.error("Encountered an exception while fetching the User By UserName : " + e); + } + return mapper; + } + + @Override + public User findOnlyUser(String username) { + User user = null; + try { + user = jdbcTemplate.query(UserQueries.SELECT_ONLY_USER, new Object[] { username, username }, + new SqlDataMapper().new SimpleUserMapper()).get(0); + } catch (Exception e) { + LOGGER.error("Encountered an Exception while fetching the User by Username : " + e); + } + return user; + } +} diff --git a/src/main/java/com/tarento/retail/dto/CountryDto.java b/src/main/java/com/tarento/retail/dto/CountryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..671d7042af9ad285495222cb661682199131ad8c --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/CountryDto.java @@ -0,0 +1,57 @@ +package com.tarento.retail.dto; + +public class CountryDto { + + private Long id; + private String code; + private String name; + private String currency; + private String phoneCode; + private String logoUrl; + private Long orgId; + + + public String getLogoUrl() { + return logoUrl; + } + public void setLogoUrl(String logoUrl) { + this.logoUrl = logoUrl; + } + + public Long getOrgId() { + return orgId; + } + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getCurrency() { + return currency; + } + public void setCurrency(String currency) { + this.currency = currency; + } + public String getPhoneCode() { + return phoneCode; + } + public void setPhoneCode(String phoneCode) { + this.phoneCode = phoneCode; + } +} diff --git a/src/main/java/com/tarento/retail/dto/CreateOrgResponse.java b/src/main/java/com/tarento/retail/dto/CreateOrgResponse.java new file mode 100644 index 0000000000000000000000000000000000000000..12a59e25516719dd0462c86079fd4934b65ded6a --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/CreateOrgResponse.java @@ -0,0 +1,43 @@ +package com.tarento.retail.dto; + +public class CreateOrgResponse { + + private Long id; + private String logoUrl; + private String orgCode; + private String orgPin; + private String orgDomain; + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public String getLogoUrl() { + return logoUrl; + } + public void setLogoUrl(String logoUrl) { + this.logoUrl = logoUrl; + } + public String getOrgCode() { + return orgCode; + } + public void setOrgCode(String orgCode) { + this.orgCode = orgCode; + } + public String getOrgPin() { + return orgPin; + } + public void setOrgPin(String orgPin) { + this.orgPin = orgPin; + } + public String getOrgDomain() { + return orgDomain; + } + public void setOrgDomain(String orgDomain) { + this.orgDomain = orgDomain; + } + + +} diff --git a/src/main/java/com/tarento/retail/dto/DomainRoleDto.java b/src/main/java/com/tarento/retail/dto/DomainRoleDto.java new file mode 100644 index 0000000000000000000000000000000000000000..868de4c746caddca18a8ebd137a2700088c56023 --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/DomainRoleDto.java @@ -0,0 +1,50 @@ +package com.tarento.retail.dto; + +public class DomainRoleDto { + + private String orgDomain; + private String roleName; + private String roleCode; + private String roleDescription; + private boolean isOrgAdmin; + private String actionsIds; + + public String getOrgDomain() { + return orgDomain; + } + public void setOrgDomain(String orgDomain) { + this.orgDomain = orgDomain; + } + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } + public String getRoleCode() { + return roleCode; + } + public void setRoleCode(String roleCode) { + this.roleCode = roleCode; + } + public String getRoleDescription() { + return roleDescription; + } + public void setRoleDescription(String roleDescription) { + this.roleDescription = roleDescription; + } + public boolean isOrgAdmin() { + return isOrgAdmin; + } + public void setOrgAdmin(boolean isOrgAdmin) { + this.isOrgAdmin = isOrgAdmin; + } + public String getActionsIds() { + return actionsIds; + } + public void setActionsIds(String actionsIds) { + this.actionsIds = actionsIds; + } + + +} diff --git a/src/main/java/com/tarento/retail/dto/MasterRoleDto.java b/src/main/java/com/tarento/retail/dto/MasterRoleDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4bb8dcad9f759e65c18ab8109de9db1056a5f48d --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/MasterRoleDto.java @@ -0,0 +1,33 @@ +package com.tarento.retail.dto; + +public class MasterRoleDto { + + private Long id; + private String name; + private String code; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + +} diff --git a/src/main/java/com/tarento/retail/dto/PaginationDto.java b/src/main/java/com/tarento/retail/dto/PaginationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d378c32ea88c803c46e709aebe97c45f8c9e6d1e --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/PaginationDto.java @@ -0,0 +1,29 @@ +package com.tarento.retail.dto; + +/** + * This is a Data Transfer Object which receives the pagination information based on which the + * data is filtered out and sorted to fetch + * @author Darshan Nagesh + * + */ + +public class PaginationDto { + + private int startIndex; + private int countOfRecords; + + public int getStartIndex() { + return startIndex; + } + public void setStartIndex(int startIndex) { + this.startIndex = startIndex; + } + public int getCountOfRecords() { + return countOfRecords; + } + public void setCountOfRecords(int countOfRecords) { + this.countOfRecords = countOfRecords; + } + + +} diff --git a/src/main/java/com/tarento/retail/dto/RoleActionDto.java b/src/main/java/com/tarento/retail/dto/RoleActionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..dc6582bd88890eee09b6bec4af5bdbc906726eca --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/RoleActionDto.java @@ -0,0 +1,33 @@ +package com.tarento.retail.dto; + +public class RoleActionDto { + + private Long roleId; + private Long actionId; + private Long orgId; + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public Long getActionId() { + return actionId; + } + + public void setActionId(Long actionId) { + this.actionId = actionId; + } + + public Long getOrgId() { + return orgId; + } + + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + +} diff --git a/src/main/java/com/tarento/retail/dto/RoleActionListDto.java b/src/main/java/com/tarento/retail/dto/RoleActionListDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c2f0563c10ca9df2ff420ed8533d4b6dd4fb01d0 --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/RoleActionListDto.java @@ -0,0 +1,26 @@ +package com.tarento.retail.dto; + +import java.util.List; + +public class RoleActionListDto { + + private Long role_id; + private List<Long> actionIds; + + public Long getRole_id() { + return role_id; + } + + public void setRole_id(Long role_id) { + this.role_id = role_id; + } + + public List<Long> getActionIds() { + return actionIds; + } + + public void setActionIds(List<Long> actionIds) { + this.actionIds = actionIds; + } + +} diff --git a/src/main/java/com/tarento/retail/dto/UserCountryDto.java b/src/main/java/com/tarento/retail/dto/UserCountryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ea42352693df9e74f345221aa2b3bf56b622e14e --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/UserCountryDto.java @@ -0,0 +1,35 @@ +package com.tarento.retail.dto; + +import java.util.List; + +import com.tarento.retail.model.Country; + +/** + * This Data Transfer Object which receives the User ID and List of Countries which is mapped against each other. + * @author Darshan Nagesh + * + */ + +public class UserCountryDto { + + private Long userId; + private List<Country> countries; + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + public List<Country> getCountries() { + return countries; + } + public void setCountries(List<Country> countries) { + this.countries = countries; + } + + + + + + +} diff --git a/src/main/java/com/tarento/retail/dto/UserDto.java b/src/main/java/com/tarento/retail/dto/UserDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f48974d9555d53cf549076dc90ceaf68fe93855c --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/UserDto.java @@ -0,0 +1,87 @@ +package com.tarento.retail.dto; + +import java.util.List; +import java.util.Set; + +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Role; + +/** + * Data Transfer Object which carries the User Information to the Data Access Layers + * @author Darshan Nagesh + * + */ +public class UserDto { + + + private long id; + + private String userName; + + private String emailId; + + public List<Role> roles; + + public Set<Action> actions; + + public String orgId ; + + public String timeZone; + + public String getTimeZone() { + return timeZone; + } + + public void setTimeZone(String timeZone) { + this.timeZone = timeZone; + } + + + public String getOrgId() { + return orgId; + } + + public void setOrgId(String orgId) { + this.orgId = orgId; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(String emailId) { + this.emailId = emailId; + } + + public List<Role> getRoles() { + return roles; + } + + public void setRoles(List<Role> roles) { + this.roles = roles; + } + + public Set<Action> getActions() { + return actions; + } + + public void setActions(Set<Action> actions) { + this.actions = actions; + } +} diff --git a/src/main/java/com/tarento/retail/dto/UserMasterRoleCountryOrgDto.java b/src/main/java/com/tarento/retail/dto/UserMasterRoleCountryOrgDto.java new file mode 100644 index 0000000000000000000000000000000000000000..452005c954e6b31a334335f20e59fa514654e3c9 --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/UserMasterRoleCountryOrgDto.java @@ -0,0 +1,40 @@ +package com.tarento.retail.dto; + +public class UserMasterRoleCountryOrgDto { + private Long masterRoleId; + private Long userId; + private Long countryId; + private Long orgId; + + public Long getMasterRoleId() { + return masterRoleId; + } + + public void setMasterRoleId(Long masterRoleId) { + this.masterRoleId = masterRoleId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getCountryId() { + return countryId; + } + + public void setCountryId(Long countryId) { + this.countryId = countryId; + } + + public Long getOrgId() { + return orgId; + } + + public void setOrgId(Long orgId) { + this.orgId = orgId; + } +} diff --git a/src/main/java/com/tarento/retail/dto/UserMasterRoleDto.java b/src/main/java/com/tarento/retail/dto/UserMasterRoleDto.java new file mode 100644 index 0000000000000000000000000000000000000000..1462e8bca02e79f024002855541805fea93622a2 --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/UserMasterRoleDto.java @@ -0,0 +1,24 @@ +package com.tarento.retail.dto; + +public class UserMasterRoleDto { + + private Long orgId; + private Long masterRoleId; + + public Long getOrgId() { + return orgId; + } + + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + + public Long getMasterRoleId() { + return masterRoleId; + } + + public void setMasterRoleId(Long masterRoleId) { + this.masterRoleId = masterRoleId; + } + +} diff --git a/src/main/java/com/tarento/retail/dto/UserProfileDto.java b/src/main/java/com/tarento/retail/dto/UserProfileDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2f8fba28489cd8458e59a645f94e146ba73c6ba2 --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/UserProfileDto.java @@ -0,0 +1,174 @@ +package com.tarento.retail.dto; + +import java.util.Date; + +/** + * This Data Transfer Object will carry the information related to the User Profile to update the User Profile Information + * in the API + * @author Darshan Nagesh + * + */ +public class UserProfileDto { + + private Long id; + private Long userId; + private String firstName; + private String lastName; + private int age; + private String emailId; + private String phoneNumber; + private String dob; + private String gender; + private String avatarUrl; + private Date startDate; + private Date endDate; + private Long salary; + private String address; + private Boolean isActive; + private Boolean isDeleted; + private Date registrationDate; + private Date createdDate; + private Long createdBy; + private Date updatedDate; + private Long updatedBy; + private String employmentType; + + public UserProfileDto() {} + public String getEmploymentType() { + return employmentType; + } + public void setEmploymentType(String employmentType) { + this.employmentType = employmentType; + } + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + public int getAge() { + return age; + } + public void setAge(int age) { + this.age = age; + } + public String getEmailId() { + return emailId; + } + public void setEmailId(String emailId) { + this.emailId = emailId; + } + public String getPhoneNumber() { + return phoneNumber; + } + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + public String getDob() { + return dob; + } + public void setDob(String dob) { + this.dob = dob; + } + public String getGender() { + return gender; + } + public void setGender(String gender) { + this.gender = gender; + } + public String getAvatarUrl() { + return avatarUrl; + } + public void setAvatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + } + public Date getStartDate() { + return startDate; + } + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + public Date getEndDate() { + return endDate; + } + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + public Long getSalary() { + return salary; + } + public void setSalary(Long salary) { + this.salary = salary; + } + public String getAddress() { + return address; + } + public void setAddress(String address) { + this.address = address; + } + public Boolean getIsActive() { + return isActive; + } + public void setIsActive(Boolean isActive) { + this.isActive = isActive; + } + public Boolean getIsDeleted() { + return isDeleted; + } + public void setIsDeleted(Boolean isDeleted) { + this.isDeleted = isDeleted; + } + public Date getRegistrationDate() { + return registrationDate; + } + public void setRegistrationDate(Date registrationDate) { + this.registrationDate = registrationDate; + } + public Date getCreatedDate() { + return createdDate; + } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + public Long getCreatedBy() { + return createdBy; + } + public void setCreatedBy(Long createdBy) { + this.createdBy = createdBy; + } + public Date getUpdatedDate() { + return updatedDate; + } + public void setUpdatedDate(Date updatedDate) { + this.updatedDate = updatedDate; + } + public Long getUpdatedBy() { + return updatedBy; + } + public void setUpdatedBy(Long updatedBy) { + this.updatedBy = updatedBy; + } + + + + + +} diff --git a/src/main/java/com/tarento/retail/dto/UserRoleDto.java b/src/main/java/com/tarento/retail/dto/UserRoleDto.java new file mode 100644 index 0000000000000000000000000000000000000000..471602090136520d42e9d5e775211d545faab57c --- /dev/null +++ b/src/main/java/com/tarento/retail/dto/UserRoleDto.java @@ -0,0 +1,37 @@ +package com.tarento.retail.dto; + +import java.util.List; + +import com.tarento.retail.model.Role; + +/** + * Data Transfer Object which carries the User ID and the Roles associated. + * @author Darshan Nagesh + * + */ +public class UserRoleDto { + + private Long userId; + private List<Role> roles; + private Long orgId; + + public Long getOrgId() { + return orgId; + } + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + public List<Role> getRoles() { + return roles; + } + public void setRoles(List<Role> roles) { + this.roles = roles; + } + +} diff --git a/src/main/java/com/tarento/retail/model/Action.java b/src/main/java/com/tarento/retail/model/Action.java new file mode 100644 index 0000000000000000000000000000000000000000..b940433ab0468e08f8312bb988f1680967e8c7a4 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/Action.java @@ -0,0 +1,119 @@ +package com.tarento.retail.model; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@AllArgsConstructor +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Setter +@ToString +public class Action { + + public Long id; + + public String name; + + public String displayName; + + public String url; + + public String queryParams; + + public String serviceCode; + + public int orderNum; + + public String menuGroupCode; + + public String menuGroupName; + + public String colourCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getQueryParams() { + return queryParams; + } + + public void setQueryParams(String queryParams) { + this.queryParams = queryParams; + } + + public String getServiceCode() { + return serviceCode; + } + + public void setServiceCode(String serviceCode) { + this.serviceCode = serviceCode; + } + + public int getOrderNum() { + return orderNum; + } + + public void setOrderNum(int orderNum) { + this.orderNum = orderNum; + } + + public String getMenuGroupCode() { + return menuGroupCode; + } + + public void setMenuGroupCode(String menuGroupCode) { + this.menuGroupCode = menuGroupCode; + } + + public String getMenuGroupName() { + return menuGroupName; + } + + public void setMenuGroupName(String menuGroupName) { + this.menuGroupName = menuGroupName; + } + + public String getColourCode() { + return colourCode; + } + + public void setColourCode(String colourCode) { + this.colourCode = colourCode; + } + + +} diff --git a/src/main/java/com/tarento/retail/model/ActionRole.java b/src/main/java/com/tarento/retail/model/ActionRole.java new file mode 100644 index 0000000000000000000000000000000000000000..6b4ac169877fced5dae6e04be6d6f6cb4cd16b58 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/ActionRole.java @@ -0,0 +1,24 @@ +package com.tarento.retail.model; + +public class ActionRole { + + public long actionId; + + public long roleId; + + public long getActionId() { + return actionId; + } + + public void setActionId(long actionId) { + this.actionId = actionId; + } + + public long getRoleId() { + return roleId; + } + + public void setRoleId(long roleId) { + this.roleId = roleId; + } +} diff --git a/src/main/java/com/tarento/retail/model/Country.java b/src/main/java/com/tarento/retail/model/Country.java new file mode 100644 index 0000000000000000000000000000000000000000..777e6ad4d109a7a6ce7b9bf51b3dd4c3fb9e511e --- /dev/null +++ b/src/main/java/com/tarento/retail/model/Country.java @@ -0,0 +1,79 @@ +package com.tarento.retail.model; + +/** + * + * @author Darshan Nagesh + * + */ + + +public class Country { + private String key; + private Long id; + private String name; + private String code; + private String displayName; + private Boolean isDefault; + private String currency; + private String dailingCode; + private String logoUrl; + + public String getCurrency() { + return currency; + } + public void setCurrency(String currency) { + this.currency = currency; + } + public String getDailingCode() { + return dailingCode; + } + public void setDailingCode(String dailingCode) { + this.dailingCode = dailingCode; + } + public Boolean getIsDefault() { + return isDefault; + } + public void setIsDefault(Boolean isDefault) { + this.isDefault = isDefault; + } + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + public String getDisplayName() { + return displayName; + } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + public String getKey() { + return key; + } + public void setKey(String key) { + this.key = key; + } + public String getLogoUrl() { + return logoUrl; + } + public void setLogoUrl(String logoUrl) { + this.logoUrl = logoUrl; + } + + + +} + diff --git a/src/main/java/com/tarento/retail/model/FetchGenericData.java b/src/main/java/com/tarento/retail/model/FetchGenericData.java new file mode 100644 index 0000000000000000000000000000000000000000..3f8e4d09f8bed704a387e4dfbb0a55fc4d0525a0 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/FetchGenericData.java @@ -0,0 +1,33 @@ +package com.tarento.retail.model; + +/** + * This is a model class which is a generalized model for any kind of fetch. + * All the parameters which is a factor for fetch will be passed through this + * @author Darshan Nagesh + * + */ +public class FetchGenericData { + + private Integer startIndex; + private Integer length; + private Integer pageNumber; + + public Integer getStartIndex() { + return startIndex; + } + public void setStartIndex(Integer startIndex) { + this.startIndex = startIndex; + } + public Integer getLength() { + return length; + } + public void setLength(Integer length) { + this.length = length; + } + public Integer getPageNumber() { + return pageNumber; + } + public void setPageNumber(Integer pageNumber) { + this.pageNumber = pageNumber; + } +} diff --git a/src/main/java/com/tarento/retail/model/LoginDto.java b/src/main/java/com/tarento/retail/model/LoginDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2d0083fec321c9fb68987688d28afb39de93ed02 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/LoginDto.java @@ -0,0 +1,77 @@ +package com.tarento.retail.model; + +import java.util.List; + +public class LoginDto { + + private String authToken; + + private Long userId; + + private String username; + + private String orgId; + + private String countryCode; + + private List<Role> roles; + + private String userAvatarUrl; + + public String getUserAvatarUrl() { + return userAvatarUrl; + } + + public void setUserAvatarUrl(String userAvatarUrl) { + this.userAvatarUrl = userAvatarUrl; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public List<Role> getRoles() { + return roles; + } + + public void setRoles(List<Role> roles) { + this.roles = roles; + } + + public String getCountryCode() { + return countryCode; + } + + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + + public String getOrgId() { + return orgId; + } + + public void setOrgId(String orgId) { + this.orgId = orgId; + } + + public String getAuthToken() { + return authToken; + } + + public void setAuthToken(String authToken) { + this.authToken = authToken; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + +} diff --git a/src/main/java/com/tarento/retail/model/LoginUser.java b/src/main/java/com/tarento/retail/model/LoginUser.java new file mode 100644 index 0000000000000000000000000000000000000000..3045699eeeced6eeaa4d134b55c02c698427f6cd --- /dev/null +++ b/src/main/java/com/tarento/retail/model/LoginUser.java @@ -0,0 +1,33 @@ +package com.tarento.retail.model; + +public class LoginUser { + + private String username; + private String password; + private String phoneNo; + private String organization; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getPhoneNo() { + return phoneNo; + } + + public void setPhoneNo(String phoneNo) { + this.phoneNo = phoneNo; + } +} diff --git a/src/main/java/com/tarento/retail/model/OrgDomaiRole.java b/src/main/java/com/tarento/retail/model/OrgDomaiRole.java new file mode 100644 index 0000000000000000000000000000000000000000..9c5824514bbd11ccaa81c8062473082ddfa854da --- /dev/null +++ b/src/main/java/com/tarento/retail/model/OrgDomaiRole.java @@ -0,0 +1,19 @@ +package com.tarento.retail.model; + +public class OrgDomaiRole { + + private String domain; + private Long roleId; + public String getDomain() { + return domain; + } + public void setDomain(String domain) { + this.domain = domain; + } + public Long getRoleId() { + return roleId; + } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } +} diff --git a/src/main/java/com/tarento/retail/model/Role.java b/src/main/java/com/tarento/retail/model/Role.java new file mode 100644 index 0000000000000000000000000000000000000000..f05de590f6a299e155c4eade3244fa18f83aea8e --- /dev/null +++ b/src/main/java/com/tarento/retail/model/Role.java @@ -0,0 +1,87 @@ +package com.tarento.retail.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Role { + + private Long id; + + private String description; + + private String code; + + private String name; + + private Long orgId; + + private boolean isSuperAdmin; + + @JsonProperty("isAdmin") + private boolean isAdmin; + + private Long createdBy; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public boolean isAdmin() { + return isAdmin; + } + + public void setAdmin(boolean isAdmin) { + this.isAdmin = isAdmin; + } + + public Long getOrgId() { + return orgId; + } + + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + + public Long getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(Long createdBy) { + this.createdBy = createdBy; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isSuperAdmin() { + return isSuperAdmin; + } + + public void setSuperAdmin(boolean isSuperAdmin) { + this.isSuperAdmin = isSuperAdmin; + } +} diff --git a/src/main/java/com/tarento/retail/model/User.java b/src/main/java/com/tarento/retail/model/User.java new file mode 100644 index 0000000000000000000000000000000000000000..16cde571329fb6207dc507ba1622c8049581650d --- /dev/null +++ b/src/main/java/com/tarento/retail/model/User.java @@ -0,0 +1,134 @@ +package com.tarento.retail.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class holds the information about the User's basic authentication along + * with Mail ID. + * + * @author Darshan Nagesh + * + */ +public class User { + + private Long id; + + private String username; + + private String password; + + private String emailId; + + private String phoneNo; + + private String orgId; + + private String countryCode; + + private String timeZone; + + private String avatarUrl; + + public String getAvatarUrl() { + return avatarUrl; + } + + public void setAvatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + } + + public String getTimeZone() { + return timeZone; + } + + public void setTimeZone(String timeZone) { + this.timeZone = timeZone; + } + + public String getCountryCode() { + return countryCode; + } + + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + + private Boolean isActive; + private Boolean isDeleted; + + @JsonProperty("authToken") + private String authToken; + + public String getOrgId() { + return orgId; + } + + public void setOrgId(String orgId) { + this.orgId = orgId; + } + + public String getAuthToken() { + return authToken; + } + + public void setAuthToken(String authToken) { + this.authToken = authToken; + } + + public Boolean getIsActive() { + return isActive; + } + + public void setIsActive(Boolean isActive) { + this.isActive = isActive; + } + + public Boolean getIsDeleted() { + return isDeleted; + } + + public void setIsDeleted(Boolean isDeleted) { + this.isDeleted = isDeleted; + } + + public String getPhoneNo() { + return phoneNo; + } + + public void setPhoneNo(String phoneNo) { + this.phoneNo = phoneNo; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(String emailId) { + this.emailId = emailId; + } + +} diff --git a/src/main/java/com/tarento/retail/model/UserAuthentication.java b/src/main/java/com/tarento/retail/model/UserAuthentication.java new file mode 100644 index 0000000000000000000000000000000000000000..03a12302e140c9a629212997c1a11c93ffa97db9 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/UserAuthentication.java @@ -0,0 +1,34 @@ +package com.tarento.retail.model; + +public class UserAuthentication { + + private long id; + + private long userId; + + private String authToken; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public String getAuthToken() { + return authToken; + } + + public void setAuthToken(String authToken) { + this.authToken = authToken; + } +} diff --git a/src/main/java/com/tarento/retail/model/UserDeviceToken.java b/src/main/java/com/tarento/retail/model/UserDeviceToken.java new file mode 100644 index 0000000000000000000000000000000000000000..b0c907fdc1170adfa518c4ae321b2317aa92519c --- /dev/null +++ b/src/main/java/com/tarento/retail/model/UserDeviceToken.java @@ -0,0 +1,37 @@ +package com.tarento.retail.model; + +/** + * + * @author Darshan Nagesh + * + */ + +public class UserDeviceToken { + + private Long userId; + private String deviceToken; + private String deviceId; + + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + public String getDeviceToken() { + return deviceToken; + } + public void setDeviceToken(String deviceToken) { + this.deviceToken = deviceToken; + } + public String getDeviceId() { + return deviceId; + } + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + + + +} diff --git a/src/main/java/com/tarento/retail/model/UserProfile.java b/src/main/java/com/tarento/retail/model/UserProfile.java new file mode 100644 index 0000000000000000000000000000000000000000..f5062477c60f629bdb6b41061c33265b6656d5b9 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/UserProfile.java @@ -0,0 +1,200 @@ +package com.tarento.retail.model; + +import java.util.Date; +import java.util.List; + +import com.tarento.retail.dto.UserProfileDto; + +/** + * This model contains the User Profile Information for a User + * + * @author Darshan Nagesh + * + */ + +public class UserProfile extends User { + private Long profileId; + private String firstName; + private String lastName; + private int age; + private String dob; + private String gender; + private String avatarUrl; + private Date startDate; + private Date endDate; + private Long salary; + private String country; + private Date registrationDate; + private String employmentType; + private Date createdDate; + private Long createdBy; + private Date updatedDate; + private Long updatedBy; + private List<Role> roles; + private String countryCode; + private Long countryId; + + public Long getCountryId() { + return countryId; + } + + public void setCountryId(Long countryId) { + this.countryId = countryId; + } + + public String getCountryCode() { + return countryCode; + } + + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + + public List<Role> getRoles() { + return roles; + } + + public void setRoles(List<Role> roles) { + this.roles = roles; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public UserProfile() { + } + + public String getEmploymentType() { + return employmentType; + } + + public void setEmploymentType(String employmentType) { + this.employmentType = employmentType; + } + + public Long getProfileId() { + return profileId; + } + + public void setProfileId(Long profileId) { + this.profileId = profileId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getAvatarUrl() { + return avatarUrl; + } + + public void setAvatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } + + public Date getRegistrationDate() { + return registrationDate; + } + + public void setRegistrationDate(Date registrationDate) { + this.registrationDate = registrationDate; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Long getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(Long createdBy) { + this.createdBy = createdBy; + } + + public Date getUpdatedDate() { + return updatedDate; + } + + public void setUpdatedDate(Date updatedDate) { + this.updatedDate = updatedDate; + } + + public Long getUpdatedBy() { + return updatedBy; + } + + public void setUpdatedBy(Long updatedBy) { + this.updatedBy = updatedBy; + } + +} diff --git a/src/main/java/com/tarento/retail/model/UserRole.java b/src/main/java/com/tarento/retail/model/UserRole.java new file mode 100644 index 0000000000000000000000000000000000000000..ce37746a10bd26cd1179418f44af6aca6dee0325 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/UserRole.java @@ -0,0 +1,24 @@ +package com.tarento.retail.model; + +public class UserRole { + + public long userId; + + public long roleId; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public long getRoleId() { + return roleId; + } + + public void setRoleId(long roleId) { + this.roleId = roleId; + } +} diff --git a/src/main/java/com/tarento/retail/model/contract/OTPValidationRequest.java b/src/main/java/com/tarento/retail/model/contract/OTPValidationRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..3ecdc004184b95b6f8db21f731924a1daca7dd35 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/OTPValidationRequest.java @@ -0,0 +1,197 @@ +package com.tarento.retail.model.contract; + +import java.util.Objects; + +import org.springframework.validation.annotation.Validated; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * OTPValidationRequest + */ +@Validated +@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-07-12T05:30:16.631Z") + +public class OTPValidationRequest { + @JsonProperty("orderId") + private String orderId = null; + + @JsonProperty("storeId") + private Long storeId = null; + + @JsonProperty("storeCode") + private String storeCode = null; + + @JsonProperty("otp") + private String otp = null; + + @JsonProperty("textComments") + private String textComments = null; + + @JsonProperty("bypassFlag") + private Boolean bypassFlag = null; + + public OTPValidationRequest orderId(String orderId) { + this.orderId = orderId; + return this; + } + + /** + * Unique identifier representing a specific order. + * @return orderId + **/ + + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public OTPValidationRequest storeId(Long storeId) { + this.storeId = storeId; + return this; + } + + /** + * Unique identifier representing a store record + * @return storeId + **/ + + + public Long getStoreId() { + return storeId; + } + + public void setStoreId(Long storeId) { + this.storeId = storeId; + } + + public OTPValidationRequest storeCode(String storeCode) { + this.storeCode = storeCode; + return this; + } + + /** + * This field carries the Store Code for which the order has been assigned + * @return storeCode + **/ + + + public String getStoreCode() { + return storeCode; + } + + public void setStoreCode(String storeCode) { + this.storeCode = storeCode; + } + + public OTPValidationRequest otp(String otp) { + this.otp = otp; + return this; + } + + /** + * One Time Password which the customer shares with the Store Personnel is passed here + * @return otp + **/ + + + public String getOtp() { + return otp; + } + + public void setOtp(String otp) { + this.otp = otp; + } + + public OTPValidationRequest textComments(String textComments) { + this.textComments = textComments; + return this; + } + + /** + * Comments added by Store Personnel if any has to be recorded + * @return textComments + **/ + + + public String getTextComments() { + return textComments; + } + + public void setTextComments(String textComments) { + this.textComments = textComments; + } + + public OTPValidationRequest bypassFlag(Boolean bypassFlag) { + this.bypassFlag = bypassFlag; + return this; + } + + /** + * Bypass Flag indicates that the OTP Validation has to be bypassed if the Customer has not carried the OTP + * @return bypassFlag + **/ + + + public Boolean isBypassFlag() { + return bypassFlag; + } + + public void setBypassFlag(Boolean bypassFlag) { + this.bypassFlag = bypassFlag; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OTPValidationRequest otPValidationRequest = (OTPValidationRequest) o; + return Objects.equals(this.orderId, otPValidationRequest.orderId) && + Objects.equals(this.storeId, otPValidationRequest.storeId) && + Objects.equals(this.storeCode, otPValidationRequest.storeCode) && + Objects.equals(this.otp, otPValidationRequest.otp) && + Objects.equals(this.textComments, otPValidationRequest.textComments) && + Objects.equals(this.bypassFlag, otPValidationRequest.bypassFlag); + } + + @Override + public int hashCode() { + return Objects.hash(orderId, storeId, storeCode, otp, textComments, bypassFlag); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OTPValidationRequest {\n"); + + sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); + sb.append(" storeId: ").append(toIndentedString(storeId)).append("\n"); + sb.append(" storeCode: ").append(toIndentedString(storeCode)).append("\n"); + sb.append(" otp: ").append(toIndentedString(otp)).append("\n"); + sb.append(" textComments: ").append(toIndentedString(textComments)).append("\n"); + sb.append(" bypassFlag: ").append(toIndentedString(bypassFlag)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/src/main/java/com/tarento/retail/model/contract/OrderConfirmationRequest.java b/src/main/java/com/tarento/retail/model/contract/OrderConfirmationRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..f7bcb1fcb1d6adc6a2dc6c297e0fa3d7f3f43dcf --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/OrderConfirmationRequest.java @@ -0,0 +1,173 @@ +package com.tarento.retail.model.contract; + +import java.util.Objects; + +import org.springframework.validation.annotation.Validated; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * OrderConfirmationRequest + */ +@Validated +@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-07-12T05:30:16.631Z") + +public class OrderConfirmationRequest { + @JsonProperty("orderId") + private String orderId = null; + + @JsonProperty("storeId") + private Long storeId = null; + + @JsonProperty("storeCode") + private String storeCode = null; + + @JsonProperty("textComments") + private String textComments = null; + + @JsonProperty("orderStatus") + private String orderStatus = null; + + public OrderConfirmationRequest orderId(String orderId) { + this.orderId = orderId; + return this; + } + + /** + * Unique identifier representing a specific order. + * @return orderId + **/ + + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public OrderConfirmationRequest storeId(Long storeId) { + this.storeId = storeId; + return this; + } + + /** + * Unique identifier representing a store record + * @return storeId + **/ + + + public Long getStoreId() { + return storeId; + } + + public void setStoreId(Long storeId) { + this.storeId = storeId; + } + + public OrderConfirmationRequest storeCode(String storeCode) { + this.storeCode = storeCode; + return this; + } + + /** + * This field carries the Store Code for which the order has been assigned + * @return storeCode + **/ + + + public String getStoreCode() { + return storeCode; + } + + public void setStoreCode(String storeCode) { + this.storeCode = storeCode; + } + + public OrderConfirmationRequest textComments(String textComments) { + this.textComments = textComments; + return this; + } + + /** + * Comments added by Store Personnel if any has to be recorded + * @return textComments + **/ + + + public String getTextComments() { + return textComments; + } + + public void setTextComments(String textComments) { + this.textComments = textComments; + } + + public OrderConfirmationRequest orderStatus(String orderStatus) { + this.orderStatus = orderStatus; + return this; + } + + /** + * Status of the order which defines at what stage the order has reached as of now + * @return orderStatus + **/ + + + public String getOrderStatus() { + return orderStatus; + } + + public void setOrderStatus(String orderStatus) { + this.orderStatus = orderStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderConfirmationRequest orderConfirmationRequest = (OrderConfirmationRequest) o; + return Objects.equals(this.orderId, orderConfirmationRequest.orderId) && + Objects.equals(this.storeId, orderConfirmationRequest.storeId) && + Objects.equals(this.storeCode, orderConfirmationRequest.storeCode) && + Objects.equals(this.textComments, orderConfirmationRequest.textComments) && + Objects.equals(this.orderStatus, orderConfirmationRequest.orderStatus); + } + + @Override + public int hashCode() { + return Objects.hash(orderId, storeId, storeCode, textComments, orderStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OrderConfirmationRequest {\n"); + + sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); + sb.append(" storeId: ").append(toIndentedString(storeId)).append("\n"); + sb.append(" storeCode: ").append(toIndentedString(storeCode)).append("\n"); + sb.append(" textComments: ").append(toIndentedString(textComments)).append("\n"); + sb.append(" orderStatus: ").append(toIndentedString(orderStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/src/main/java/com/tarento/retail/model/contract/RequestInfo.java b/src/main/java/com/tarento/retail/model/contract/RequestInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..42b2cd0706f4fdc0078976579ae588ad9f90767e --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/RequestInfo.java @@ -0,0 +1,54 @@ +package com.tarento.retail.model.contract; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +/** + * RequestInfo should be used to carry meta information about the requests to the server as described in the fields below. Some of this information will be returned back from the server as part of the ResponseInfo in the response body to ensure correlation + */ +@AllArgsConstructor +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Setter +@ToString +public class RequestInfo { + + private String apiId; + + + private String ver; + + + private Long ts; + + + private String action; + + + private String did; + + + private String key; + + + private String msgId; + + + private String requesterId; + + + private String authToken; + + + private String correlationId; + + + + +} + diff --git a/src/main/java/com/tarento/retail/model/contract/RoleActionRequest.java b/src/main/java/com/tarento/retail/model/contract/RoleActionRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..cdb79f077f93ed4ba619be1c8fe7597b145bd57e --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/RoleActionRequest.java @@ -0,0 +1,50 @@ +/* + * Musti Backend API - User + * All services for User service + * + * OpenAPI spec version: 1.0 + * + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +package com.tarento.retail.model.contract; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Getter; +import lombok.Setter; + +/** + * RoleActionRequest + */ + +@Getter +@Setter +public class RoleActionRequest { + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public RoleRequest getRoleRequest() { + return roleRequest; + } + + public void setRoleRequest(RoleRequest roleRequest) { + this.roleRequest = roleRequest; + } + + @JsonProperty("RequestInfo") + private RequestInfo requestInfo; + + @JsonProperty("RoleRequest") + private RoleRequest roleRequest; + +} diff --git a/src/main/java/com/tarento/retail/model/contract/RoleActionResponseInfo.java b/src/main/java/com/tarento/retail/model/contract/RoleActionResponseInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..09ebb319b7f736b3e0ad700220d9765b9e614315 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/RoleActionResponseInfo.java @@ -0,0 +1,31 @@ +package com.tarento.retail.model.contract; + +import java.util.List; + +import com.tarento.retail.model.Action; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + + + +/** + * ResponseInfo should be used to carry metadata information about the response from the server along with the requested data. + */ +@AllArgsConstructor +@Getter +@NoArgsConstructor +@Setter +public class RoleActionResponseInfo { + + private StatusInfo statusInfo; + + + private List<Action> actions; + + + +} + diff --git a/src/main/java/com/tarento/retail/model/contract/RoleRequest.java b/src/main/java/com/tarento/retail/model/contract/RoleRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..e60b1e5369365a870a28be343d3f5f74c45becac --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/RoleRequest.java @@ -0,0 +1,51 @@ +package com.tarento.retail.model.contract; + +import java.util.ArrayList; +import java.util.List; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +/** + * RoleRequest + */ +@AllArgsConstructor +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Setter +@ToString +public class RoleRequest { + + private Boolean enabled; + + + private List<Integer> roles = new ArrayList<Integer>(); + + +public Boolean getEnabled() { + return enabled; +} + + +public void setEnabled(Boolean enabled) { + this.enabled = enabled; +} + + +public List<Integer> getRoles() { + return roles; +} + + +public void setRoles(List<Integer> roles) { + this.roles = roles; +} + + +} + diff --git a/src/main/java/com/tarento/retail/model/contract/StatusInfo.java b/src/main/java/com/tarento/retail/model/contract/StatusInfo.java new file mode 100644 index 0000000000000000000000000000000000000000..233915d5c85501317c6c201909115dd92a53a913 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/StatusInfo.java @@ -0,0 +1,38 @@ +package com.tarento.retail.model.contract; + + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +/** + * Status Information object will hold the run time status and the live response obtained from the server for the respective API Call. + */ +@AllArgsConstructor +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Setter +@ToString +public class StatusInfo { + + private Integer statusCode; + + + private String statusMessage; + + + private Long errorCode; + + + private String errorMessage; + + + + + +} + diff --git a/src/main/java/com/tarento/retail/model/contract/UserGetRequest.java b/src/main/java/com/tarento/retail/model/contract/UserGetRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..46b4ae1b75cebfe29479c2a0802d3e5877eed854 --- /dev/null +++ b/src/main/java/com/tarento/retail/model/contract/UserGetRequest.java @@ -0,0 +1,25 @@ +package com.tarento.retail.model.contract; + +import java.util.List; + +/** + * + * @author Darshan Nagesh + * + */ + +public class UserGetRequest { + + private List<Long> userIdList; + + public List<Long> getUserIdList() { + return userIdList; + } + + public void setUserIdList(List<Long> userIdList) { + this.userIdList = userIdList; + } + + + +} diff --git a/src/main/java/com/tarento/retail/model/enums/CountryList.java b/src/main/java/com/tarento/retail/model/enums/CountryList.java new file mode 100644 index 0000000000000000000000000000000000000000..7aca9eee3af7d1c3ac43233c92ab503ab7c1750a --- /dev/null +++ b/src/main/java/com/tarento/retail/model/enums/CountryList.java @@ -0,0 +1,67 @@ +package com.tarento.retail.model.enums; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * + * @author Darshan Nagesh + * + */ + +public enum CountryList { + SWEDEN("SWEDEN","Sweden"), FINLAND("FINLAND","Finland"), NORWAY("NORWAY","Norway"); + + private String value; + + @Override + @JsonValue + public String toString() { + return StringUtils.capitalize(name()); + } + + @JsonCreator + public static CountryList fromValue(final String passedValue) { + for (final CountryList obj : CountryList.values()) + if (String.valueOf(obj.value).equals(passedValue.toUpperCase())) + return obj; + return null; + } + + private String abbreviation; + + // Reverse-lookup map for getting a day from an abbreviation + private static final Map<String, CountryList> lookup = new HashMap<String, CountryList>(); + + static { + for (CountryList list : CountryList.values()) { + lookup.put(list.getAbbreviation(), list); + } + } + + private CountryList(String abbreviation, final String value) { + this.abbreviation = abbreviation; + this.value = value; + } + + private CountryList(final String value) { + this.value = value; + } + + public String getAbbreviation() { + return abbreviation; + } + + public String getValue() { + return value; + } + + public static CountryList get(String abbreviation) { + return lookup.get(abbreviation); + } +} diff --git a/src/main/java/com/tarento/retail/model/enums/EmploymentType.java b/src/main/java/com/tarento/retail/model/enums/EmploymentType.java new file mode 100644 index 0000000000000000000000000000000000000000..1b8ef014f5f5b3cd5e1377e6979e14bb8bd2940b --- /dev/null +++ b/src/main/java/com/tarento/retail/model/enums/EmploymentType.java @@ -0,0 +1,36 @@ +package com.tarento.retail.model.enums; + +import org.apache.commons.lang3.StringUtils; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * + * @author Darshan Nagesh + * + */ + +public enum EmploymentType { + PERMANENT("PERMANENT"), CONTRACT("CONTRACT"); + + private String value; + + EmploymentType(final String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return StringUtils.capitalize(name()); + } + + @JsonCreator + public static EmploymentType fromValue(final String passedValue) { + for (final EmploymentType obj : EmploymentType.values()) + if (String.valueOf(obj.value).equals(passedValue.toUpperCase())) + return obj; + return null; + } +} diff --git a/src/main/java/com/tarento/retail/model/mapper/SqlDataMapper.java b/src/main/java/com/tarento/retail/model/mapper/SqlDataMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..203ba8ff32ded6520b45c9bc5c80c24430db2baa --- /dev/null +++ b/src/main/java/com/tarento/retail/model/mapper/SqlDataMapper.java @@ -0,0 +1,364 @@ +package com.tarento.retail.model.mapper; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.RowMapper; + +import com.tarento.retail.dto.DomainRoleDto; +import com.tarento.retail.dto.MasterRoleDto; +import com.tarento.retail.dto.UserDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.ActionRole; +import com.tarento.retail.model.Country; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.model.UserAuthentication; +import com.tarento.retail.model.UserDeviceToken; +import com.tarento.retail.model.UserProfile; + +public class SqlDataMapper { + + public static final Logger LOGGER = LoggerFactory.getLogger(SqlDataMapper.class); + + public class UserMapper implements RowMapper<User> { + public User mapRow(ResultSet rs, int rowNum) throws SQLException { + User user = new User(); + user.setId(rs.getLong("id")); + user.setPassword(rs.getString("password")); + user.setUsername(rs.getString("username")); + user.setEmailId(rs.getString("email_id")); + user.setPhoneNo(rs.getString("phone_no")); + user.setOrgId(rs.getString("org_id")); + user.setCountryCode(rs.getString("code")); + user.setTimeZone(rs.getString("timezone")); + user.setAvatarUrl(rs.getString("avatar_url")); + return user; + } + } + + public class UserDetailsMapper implements RowMapper<User> { + public User mapRow(ResultSet rs, int rowNum) throws SQLException { + User user = new User(); + user.setId(rs.getLong("id")); + user.setUsername(rs.getString("username")); + user.setEmailId(rs.getString("email_id")); + user.setPhoneNo(rs.getString("phone_no")); + user.setOrgId(rs.getString("org_id")); + user.setTimeZone(rs.getString("timezone")); + return user; + } + } + + public class SimpleUserMapper implements RowMapper<User> { + public User mapRow(ResultSet rs, int rowNum) throws SQLException { + User user = new User(); + user.setId(rs.getLong("id")); + user.setPassword(rs.getString("password")); + user.setUsername(rs.getString("username")); + user.setEmailId(rs.getString("email_id")); + user.setPhoneNo(rs.getString("phone_no")); + return user; + } + } + + public class UserDetailMapper implements RowMapper<User> { + public User mapRow(ResultSet rs, int rowNum) throws SQLException { + User user = new User(); + user.setId(rs.getLong("id")); + user.setPassword(rs.getString("password")); + user.setUsername(rs.getString("username")); + user.setEmailId(rs.getString("email_id")); + user.setPhoneNo(rs.getString("phone_no")); + user.setOrgId(rs.getString("org_id")); + user.setCountryCode(rs.getString("code")); + return user; + } + } + + public class OrgDomainRoleMapper implements RowMapper<String> { + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + + return rs.getString("org_domain"); + } + } + + public class UserDeviceMapper implements RowMapper<UserDeviceToken> { + public UserDeviceToken mapRow(ResultSet rs, int rowNum) throws SQLException { + UserDeviceToken token = new UserDeviceToken(); + token.setDeviceToken(rs.getString("device_token")); + token.setUserId(rs.getLong("user_id")); + return token; + } + } + + public class CountryMapper implements RowMapper<Country> { + public Country mapRow(ResultSet rs, int rowNum) throws SQLException { + Country country = new Country(); + country.setId(rs.getLong("id")); + country.setCode(rs.getString("code")); + country.setName(rs.getString("name")); + country.setKey(rs.getString("code")); + country.setCurrency(rs.getString("currency")); + country.setDailingCode(rs.getString("phone_code")); + country.setDisplayName(rs.getString("name")); + country.setLogoUrl(rs.getString("url")); + return country; + } + } + + public class UserProfileMapper implements RowMapper<UserProfile> { + public Map<Long, UserProfile> userMap = new HashMap<>(); + public Map<Long, List<Role>> userRoleMap = new HashMap<>(); + + public UserProfile mapRow(ResultSet rs, int rowNum) throws SQLException { + if (!userMap.containsKey(rs.getLong("id"))) { + UserProfile user = new UserProfile(); + user.setId(rs.getLong("id")); + user.setUsername(rs.getString("username")); + user.setEmailId(rs.getString("email_id")); + user.setPhoneNo(rs.getString("phone_no")); + user.setFirstName(rs.getString("first_name")); + user.setLastName(rs.getString("last_name")); + user.setAge(rs.getInt("age")); + user.setDob(rs.getString("dob")); + user.setGender(rs.getString("gender")); + user.setAvatarUrl(rs.getString("avatar_url")); + user.setStartDate(rs.getDate("work_start_date")); + user.setEndDate(rs.getDate("work_end_date")); + user.setCountry(rs.getString("country")); + user.setIsActive(rs.getBoolean("is_active")); + user.setIsDeleted(rs.getBoolean("is_deleted")); + user.setRegistrationDate(rs.getDate("registration_date")); + user.setCreatedDate(rs.getDate("created_date")); + user.setCreatedBy(rs.getLong("created_by")); + user.setUpdatedDate(rs.getDate("updated_date")); + user.setUpdatedBy(rs.getLong("updated_by")); + user.setEmploymentType(rs.getString("employment_type")); + user.setTimeZone(rs.getString("timezone")); + userMap.put(rs.getLong("id"), user); + } + + if (userRoleMap.containsKey(rs.getLong("id"))) { + List<Role> roleList = userRoleMap.get(rs.getLong("id")); + Role role = new Role(); + role.setId(rs.getLong("role_id")); + role.setName(rs.getString("role_name")); + role.setDescription(rs.getString("description")); + if (StringUtils.isNotBlank(rs.getString("role_name"))) { + roleList.add(role); + } + } else { + List<Role> roleList = new ArrayList<>(); + Role role = new Role(); + role.setId(rs.getLong("role_id")); + role.setName(rs.getString("role_name")); + role.setDescription(rs.getString("description")); + + if (StringUtils.isNotBlank(rs.getString("role_name"))) { + roleList.add(role); + } + userRoleMap.put(rs.getLong("id"), roleList); + } + + return null; + } + } + + public class UserRoleActionMapper implements RowMapper<UserProfile> { + public Map<Long, UserDto> userMap = new HashMap<>(); + public Map<Long, Map<Long, Role>> userRoleMap = new HashMap<>(); + public Map<Long, Map<Long, Action>> roleActionMap = new HashMap<>(); + + public UserProfile mapRow(ResultSet rs, int rowNum) throws SQLException { + if(!userMap.containsKey(rs.getLong("userId"))) { + userMap.put(rs.getLong("userId"), createUser(rs)); + + Map<Long, Role> roleMap = new HashMap<>(); + roleMap.put(rs.getLong("roleId"), createRole(rs)); + userRoleMap.put(rs.getLong("userId"), roleMap); + + Map<Long, Action> actionMap = new HashMap<>(); + actionMap.put(rs.getLong("actionId"), createAction(rs)); + roleActionMap.put(rs.getLong("roleId"), actionMap); + } else { + Map<Long, Role> roleMap = userRoleMap.get(rs.getLong("userId")); + if(!roleMap.containsKey(rs.getLong("roleId"))) { + roleMap.put(rs.getLong("roleId"), createRole(rs)); + + Map<Long, Action> actionMap = new HashMap<>(); + actionMap.put(rs.getLong("actionId"), createAction(rs)); + roleActionMap.put(rs.getLong("roleId"), actionMap); + } else { + Map<Long, Action> actionMap = roleActionMap.get(rs.getLong("roleId")); + actionMap.put(rs.getLong("actionId"), createAction(rs)); + } + } + return null; + } + + private Action createAction(ResultSet rs) { + Action action = new Action(); + try { + action.setId(rs.getLong("actionId")); + action.setName(rs.getString("actionName")); + action.setUrl(rs.getString("actionUrl")); + } catch (Exception e) { + LOGGER.info("Encountered an Exception while creating Action : " + e.getMessage()); + } + return action; + } + + private UserDto createUser(ResultSet rs) { + UserDto userDto = new UserDto(); + try { + userDto.setId(rs.getLong("userId")); + userDto.setUserName(rs.getString("username")); + userDto.setEmailId(rs.getString("userEmailId")); + userDto.setOrgId(String.valueOf(rs.getLong("userOrgId"))); + } catch (Exception e) { + LOGGER.info("Encountered an Exception while creating User : " + e.getMessage()); + } + return userDto; + } + + private Role createRole(ResultSet rs) { + Role role = new Role(); + try { + role.setId(rs.getLong("roleId")); + role.setName(rs.getString("roleName")); + role.setCode(rs.getString("roleCode")); + role.setDescription(rs.getString("roleDescription")); + role.setAdmin(rs.getBoolean("isOrgAdmin")); + role.setSuperAdmin(rs.getBoolean("isSuperAdmin")); + role.setOrgId(rs.getLong("roleOrgId")); + } catch (Exception e) { + LOGGER.info("Encountered an Exception while creating Role : " + e.getMessage()); + } + return role; + } + } + + public class UserAuthenticationMapper implements RowMapper<UserAuthentication> { + public UserAuthentication mapRow(ResultSet rs, int rowNum) throws SQLException { + UserAuthentication userAuthentication = new UserAuthentication(); + userAuthentication.setId(rs.getLong("id")); + userAuthentication.setUserId(rs.getLong("user_id")); + userAuthentication.setAuthToken(rs.getString("auth_token")); + return userAuthentication; + } + } + + public class UserRoleMapper implements RowMapper<Role> { + public Map<Long, Role> roleMap = new HashMap<>(); + + public Role mapRow(ResultSet rs, int rowNum) throws SQLException { + if (!roleMap.containsKey(rs.getLong("role_id"))) { + Role role = new Role(); + role.setId(rs.getLong("role_id")); + role.setName(rs.getString("role_name")); + role.setDescription(rs.getString("description")); + role.setOrgId(rs.getLong("org_id")); + role.setSuperAdmin(rs.getBoolean("is_super_admin")); + roleMap.put(rs.getLong("role_id"), role); + } + return null; + } + } + + public class UserMasterRoleMapper implements RowMapper<UserDto> { + @Override + public UserDto mapRow(ResultSet rs, int rowNum) throws SQLException { + UserDto user = new UserDto(); + + user.setUserName(rs.getString("username")); + user.setId(rs.getLong("id")); + return user; + } + } + + public class MasterRoleMapper implements RowMapper<MasterRoleDto> { + @Override + public MasterRoleDto mapRow(ResultSet rs, int rowNum) throws SQLException { + MasterRoleDto masterRoleDto = new MasterRoleDto(); + masterRoleDto.setId(rs.getLong("id")); + masterRoleDto.setName(rs.getString("name")); + masterRoleDto.setCode(rs.getString("code")); + return masterRoleDto; + } + } + + public class ActionMapper implements RowMapper<Action> { + public Action mapRow(ResultSet rs, int rowNum) throws SQLException { + Action action = new Action(); + action.setId(rs.getLong("id")); + action.setDisplayName(rs.getString("display_name")); + action.setName(rs.getString("name")); + action.setServiceCode(rs.getString("service_code")); + action.setUrl(rs.getString("url")); + return action; + } + } + + public class RoleMapper implements RowMapper<Role> { + public Role mapRow(ResultSet rs, int rowNum) throws SQLException { + Role role = new Role(); + role.setId(rs.getLong("id")); + role.setCode(rs.getString("code")); + role.setDescription(rs.getString("description")); + role.setName(rs.getString("role_name")); + role.setOrgId(rs.getLong("org_id")); + return role; + } + } + + public class RoleOrgDomainMapper implements RowMapper<Role> { + public Role mapRow(ResultSet rs, int rowNum) throws SQLException { + Role role = new Role(); + role.setId(rs.getLong("id")); + role.setDescription(rs.getString("description")); + role.setName(rs.getString("role_name")); + role.setCode(rs.getString("code")); + return role; + } + } + + public class DomainRoleMapper implements RowMapper<DomainRoleDto> { + public DomainRoleDto mapRow(ResultSet rs, int rowNum) throws SQLException { + DomainRoleDto role = new DomainRoleDto(); + role.setOrgDomain(rs.getString("org_domain")); + role.setRoleName(rs.getString("role_name")); + role.setRoleCode(rs.getString("role_code")); + role.setRoleDescription(rs.getString("role_description")); + role.setOrgAdmin(rs.getBoolean("is_org_admin")); + role.setActionsIds(rs.getString("action_ids")); + return role; + } + } + /* + * public class ActionMapper implements RowMapper<Action> { public Action + * mapRow(ResultSet rs, int rowNum) throws SQLException { Action action = new + * Action(); action.setId(rs.getLong("id")); + * action.setDescription(rs.getString("description")); + * action.setModuleCode(rs.getString("module_code")); + * action.setModuleName(rs.getString("module_name")); + * action.setUrl(rs.getString("url")); return action; } } + */ + + public class ActionRoleMapper implements RowMapper<ActionRole> { + public ActionRole mapRow(ResultSet rs, int rowNum) throws SQLException { + ActionRole actionRole = new ActionRole(); + actionRole.setActionId(rs.getLong("action_id")); + actionRole.setRoleId(rs.getLong("role_id")); + return actionRole; + } + } + +} diff --git a/src/main/java/com/tarento/retail/service/RoleActionService.java b/src/main/java/com/tarento/retail/service/RoleActionService.java new file mode 100644 index 0000000000000000000000000000000000000000..73684d175f45d223ad8094d171805aed5bdea098 --- /dev/null +++ b/src/main/java/com/tarento/retail/service/RoleActionService.java @@ -0,0 +1,85 @@ +package com.tarento.retail.service; + +import java.util.List; + +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.CreateOrgResponse; +import com.tarento.retail.dto.DomainRoleDto; +import com.tarento.retail.dto.RoleActionDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; + +/** + * This interface handles the service layer of business operation logic + * implementation for all the Role and its Action related transactions + * + * @author Darshan Nagesh + * + */ +public interface RoleActionService { + + /** + * This method receives the request with details related to a new role and + * passes on to the DAO layer to save in DB + * + * @param role + * @return + */ + Role saveRole(Role role); + + /** + * This method receives the request with details related to a new role and + * passes on to the DAO layer to update the role information in DB + * + * @param role + * @return + */ + Role updateRole(Role role); + + /** + * This method fetches all the Roles available in the system + * + * @param fetchData + * @return + */ + List<Role> getAllRoles(Long orgCode); + + List<DomainRoleDto> getAllRolesByDomain(String orgDomain); + /** + * As a part of Role Action Mapping, this API method will add a new feature and + * its URL Details to the existing list of API URLS This can be later used to + * map to a role to achieve RBAC + * + * @param feature + * @return + */ + Action saveAction(Action action); + + /** + * This method receives the ID from Controller to pass on the same to DAO to + * fetch the Role Object from Database This returns the Role Object for the + * respective Role ID + * + * @param id + * @return + */ + Role findById(Long id); + + boolean checkRoleAccess(Long userId, Long orgId); + + Boolean deleteRole(Role role); + + List<Action> getMappedActionToRole(Long role); + + List<Action> getUnmappedActionToRole(Long role); + + Boolean mapActionToRole(RoleActionDto roleActionDto); + + Boolean unmapActionFromRole(RoleActionDto roleActionDto); + + List<User> getUsersByRoleId(Role role); + + Boolean addRolesFromOrgDomain(CreateOrgResponse res); + +} diff --git a/src/main/java/com/tarento/retail/service/UserService.java b/src/main/java/com/tarento/retail/service/UserService.java new file mode 100644 index 0000000000000000000000000000000000000000..b0bf590297ce302509731dfe25f7599011ca26b3 --- /dev/null +++ b/src/main/java/com/tarento/retail/service/UserService.java @@ -0,0 +1,228 @@ +package com.tarento.retail.service; + +import java.util.List; +import java.util.Set; + +import org.springframework.web.multipart.MultipartFile; + +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.MasterRoleDto; +import com.tarento.retail.dto.UserCountryDto; +import com.tarento.retail.dto.UserDto; +import com.tarento.retail.dto.UserMasterRoleCountryOrgDto; +import com.tarento.retail.dto.UserMasterRoleDto; +import com.tarento.retail.dto.UserRoleDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Country; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.model.UserAuthentication; +import com.tarento.retail.model.UserDeviceToken; +import com.tarento.retail.model.UserProfile; + +public interface UserService { + + /** + * This method receives the List of Role IDs from the controller and passes the + * same to DAO to fetch the List of Actions allowed and configured for the Role + * ID + * + * @param roleID + * @return + */ + public List<Action> findAllActionsByRoleID(List<Integer> roleID); + + /** + * This method receives the User high level object. This is passed to DAO after + * Password encryption to save the same into Database + * + * @param user + * @return + */ + User save(User user); + + /** + * This method receives the existing User object to update the details in the + * Database for the respective User + * + * @param user + * @return + */ + User update(User user); + + /** + * This method receives the User Authentication Details on every login to save + * the Auth Token for the sake of further validations while accessing other + * features in the application + * + * @param user + * @return + */ + UserAuthentication save(UserAuthentication user); + + /** + * This method supports pagination and fetches the User Profiles for the + * respective search criteria Search can happen based on Page Number, Number of + * Records, Active status of the user Keyword to search the user and also based + * on the Roles Assigned to the User + * + * @param pageNumber + * @param numberOfRecords + * @param active + * @param keyword + * @param roles + * @return + */ + List<UserProfile> findAll(Integer pageNumber, Integer numberOfRecords, Boolean active, String keyword, + List<Long> roles, String countryCode, Long orgId); + + /** + * This method receives the String Username to fetch the respective User record + * from the Database + * + * @param username + * @return + */ + User findOne(String username); + + UserDto findUserRolesActions(String username); + + /** + * This method receives the Long ID to fetch the respective User Profile from + * the database + * + * @param id + * @return + */ + UserProfile findById(Long id, Long orgId); + + /** + * This method receives the list of Users IDs and passes the same to Data layer + * to get and fetch the User Profiles for that User ID List + * + * @param userIdList + * @return + */ + List<UserProfile> findListOfUsers(List<Long> userIdList); + + /** + * This method receives the User ID and find the corresponding roles for the + * User ID and lists out the Roles as a response + * + * @param userId + * @return + */ + public List<Role> findAllRolesByUser(Long userId, String orgId); + + /** + * This method receives the User ID and then fetches the Role ID for the same + * With the help of Role ID, it fetches the corresponding Actions which are + * allowed and mapped. As a result, this responds Action object + * + * @param userId + * @return + */ + public Set<Action> findAllActionsByUser(Long userId, String orgId); + + /** + * This method carries the Phone Number and fetches the corresponding User high + * level object for the Phone Number + * + * @param phoneNo + * @return + */ + User findMobile(String phoneNo); + + /** + * This method receives the User Role Object. For a User ID and each Role ID in + * the list, this method creates a mapping so that User Role Mapping is added + * + * @param userRole + * @return + */ + + Boolean mapUserToRole(UserRoleDto userRole); + + /** + * This method receives the User Profile which contains the secondary details of + * the User. Method is invoked internally on creating User + * + * @param profile + * @return + */ + UserProfile saveUserProfile(UserProfile profile); + + /** + * This method receives an already existing User Profile object which is passed + * on to Data Layer Method ensures that the update is successful. + * + * @param profile + * @return + */ + UserProfile updateUserProfile(UserProfile profile); + + /** + * This method receives the User Profile object which carries the Profile Image + * Updates the same and responds with the same object + * + * @param profile + * @return + */ + UserProfile updateUserProfileImage(UserProfile profile); + + Long checkUserNameExists(String emailId, String phoneNo); + + Boolean uploadFile(MultipartFile file, long userId); + + Long getNumberOfUsers(Long role, Boolean active); + + Long getNumberOfRoles(); + + List<Country> getCountryList(); + + List<Country> getCountryListForUser(Long userId); + + Boolean mapUserToCountry(UserCountryDto userCountry); + + Boolean invalidateToken(String authToken); + + Boolean findUserByToken(String authToken); + + Boolean checkUserTokenExists(Long userId, String deviceToken); + + Boolean updateUserDeviceToken(Long userId, String deviceToken, Long authTokenRef); + + /** + * This method receives the list of Users IDs and passes the same to Data layer + * to get and fetch the User Device Tokens which are registered by Mobile + * Application + * + * @param userIdList + * @return + */ + List<UserDeviceToken> getDeviceTokenForUsers(List<Long> userIdList); + + Long fetchAuthTokenReference(String authToken); + + Boolean hasAccess(List<Role> roles); + + Boolean createCountry(CountryDto countryDto); + + Boolean updateCountry(CountryDto countryDto); + + public List<Country> getCountryListForOrg(Long orgId); + + public Boolean checkCountryAlreadyExists(String code, Long orgId); + + Boolean deleteUserToRole(UserRoleDto userRole); + + Boolean deleteCountryForOrg(CountryDto countryDto); + + Boolean deleteUser(UserDto userDto); + + List<UserDto> getUsersByMasterRole(String roleCode, Long orgId); + + Boolean mapUserMasterRoleCountryOrg(UserMasterRoleCountryOrgDto userMasterRoleCountryOrgDto); + + List<MasterRoleDto> getMasterRoleByOrgDomainId(Long orgDomainId); +} \ No newline at end of file diff --git a/src/main/java/com/tarento/retail/service/impl/RoleActionServiceImpl.java b/src/main/java/com/tarento/retail/service/impl/RoleActionServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..c31a72f8652b108dada1c620a9fc976be2850d59 --- /dev/null +++ b/src/main/java/com/tarento/retail/service/impl/RoleActionServiceImpl.java @@ -0,0 +1,159 @@ +package com.tarento.retail.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.mysql.fabric.xmlrpc.base.Array; +import com.tarento.retail.dao.RoleDao; +import com.tarento.retail.dto.CreateOrgResponse; +import com.tarento.retail.dto.DomainRoleDto; +import com.tarento.retail.dto.RoleActionDto; +import com.tarento.retail.dto.RoleActionListDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.service.RoleActionService; +import com.tarento.retail.util.Constants; + +@Service(value = Constants.ROLE_ACTION_SERVICE) +public class RoleActionServiceImpl implements RoleActionService { + + private static final String SUPER_ADMIN = "SUPER_ADMIN"; + private static final String ORG_ADMIN = "ORG_ADMIN"; + + @Autowired + private RoleDao roleDao; + + @Override + public Role saveRole(Role role) { + // Check if Role exist in Role table + Role existingRole = roleDao.findById(role.getId()); + if (existingRole == null) { + // Update role_org mapping only + existingRole = roleDao.saveRole(role); + + } + roleDao.updateOrgRole(existingRole.getId(), role.getOrgId()); + return existingRole; + + } + + @Override + public Role updateRole(Role role) { + + return roleDao.updateRole(role); + } + + @Override + public Action saveAction(Action action) { + return roleDao.saveAction(action); + } + + @Override + public List<Role> getAllRoles(Long orgCode) { + return roleDao.getAllRoles(orgCode); + } + + @Override + public List<DomainRoleDto> getAllRolesByDomain(String orgDomain) { + return roleDao.getAllRolesByDomain(orgDomain); + } + + @Override + public Role findById(Long id) { + return roleDao.findById(id); + } + + @Override + public boolean checkRoleAccess(Long userId, Long orgId) { + + Role role = roleDao.findById(userId, orgId); + if (SUPER_ADMIN.equals(role.getName()) || ORG_ADMIN.equals(role.getName())) { + return true; + } + return false; + } + + @Override + public Boolean deleteRole(Role role) { + List<String> orgDomain = roleDao.getDefaultRoles(role.getId()); + // Unmapp roles + Boolean success = roleDao.deleteOrgRole(role.getId(), role.getOrgId()); + if (orgDomain == null || orgDomain.isEmpty()) { + success = roleDao.deleteRole(role); + } + return success; + } + + @Override + public List<Action> getMappedActionToRole(Long role) { + return roleDao.getMappedActionRole(role); + } + + @Override + public List<Action> getUnmappedActionToRole(Long role) { + return roleDao.getUnmappedActionRole(role); + } + + @Override + public Boolean mapActionToRole(RoleActionDto roleActionDto) { + return roleDao.mapActionToRole(roleActionDto); + } + + @Override + public Boolean unmapActionFromRole(RoleActionDto roleActionDto) { + return roleDao.unmapActionFromRole(roleActionDto); + } + + @Override + public List<User> getUsersByRoleId(Role role) { + return roleDao.getUsersByRoleId(role); + } + + // ADD ROLES FROM ORG DOMAIN AND ASSIGN ACTIONS of DOMAIN_ROLE TO ROLES + @Override + public Boolean addRolesFromOrgDomain(CreateOrgResponse res) { + boolean success = false; + List<DomainRoleDto> domainRoleDtoList = null; + + // Get All Domain Roles + domainRoleDtoList = roleDao.getAllRolesByDomain(res.getOrgDomain()); + + // ADD NEW ROLE BY USING DOMAIN ROLE DETAILS + if (domainRoleDtoList != null) { + for (DomainRoleDto roleDto : domainRoleDtoList) { + Role role = new Role(); + role.setName(roleDto.getRoleName()); + role.setDescription(roleDto.getRoleDescription()); + role.setCode(roleDto.getRoleCode()); + role.setAdmin(roleDto.isOrgAdmin()); + role.setOrgId(res.getId()); // orgId + + // ADD NEW ROLE and GET ID + Role createdRole = new Role(); + createdRole = roleDao.saveRole(role); + if (roleDto.getActionsIds() != null) { + if (roleDto.getActionsIds().split(",").length != 0) { + String[] arrOfActionIds = roleDto.getActionsIds().split(","); + ArrayList<Long> idList = new ArrayList<Long>(); + for (String id : arrOfActionIds) { + idList.add(Long.parseLong(id)); + } + RoleActionListDto roleActionListDto = new RoleActionListDto(); + roleActionListDto.setActionIds(idList); + roleActionListDto.setRole_id(createdRole.getId()); + // Map All the actions to role + if (!roleActionListDto.getActionIds().isEmpty()) { + success = roleDao.mapAllActionsToRole(roleActionListDto); + } + } + } + } + } + return success; + } + +} diff --git a/src/main/java/com/tarento/retail/service/impl/UserServiceImpl.java b/src/main/java/com/tarento/retail/service/impl/UserServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..3469180b5b80aef3e0da9c44b5fe20c38d3f94e1 --- /dev/null +++ b/src/main/java/com/tarento/retail/service/impl/UserServiceImpl.java @@ -0,0 +1,492 @@ +package com.tarento.retail.service.impl; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.mysql.fabric.xmlrpc.base.Array; +import com.tarento.retail.dao.RoleDao; +import com.tarento.retail.dao.UserDao; +import com.tarento.retail.dto.CountryDto; +import com.tarento.retail.dto.MasterRoleDto; +import com.tarento.retail.dto.UserCountryDto; +import com.tarento.retail.dto.UserDto; +import com.tarento.retail.dto.UserMasterRoleCountryOrgDto; +import com.tarento.retail.dto.UserRoleDto; +import com.tarento.retail.model.Action; +import com.tarento.retail.model.Country; +import com.tarento.retail.model.Role; +import com.tarento.retail.model.User; +import com.tarento.retail.model.UserAuthentication; +import com.tarento.retail.model.UserDeviceToken; +import com.tarento.retail.model.UserProfile; +import com.tarento.retail.model.mapper.SqlDataMapper.UserProfileMapper; +import com.tarento.retail.model.mapper.SqlDataMapper.UserRoleActionMapper; +import com.tarento.retail.model.mapper.SqlDataMapper.UserRoleMapper; +import com.tarento.retail.service.UserService; +import com.tarento.retail.util.Constants; + +@Service(value = Constants.USER_SERVICE) + +public class UserServiceImpl implements UserDetailsService, UserService { + public static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); + public static ConcurrentHashMap<String, UserDto> userRoleActionMap = new ConcurrentHashMap<>(); + + @Autowired + private UserDao userDao; + + @Autowired + RoleDao roleDao; + + @Autowired + private BCryptPasswordEncoder bcryptEncoder; + + public List<Action> findAllActionsByRoleID(List<Integer> roleID) { + List<Action> actions = new ArrayList<Action>(); + List<Action> completeActions = new ArrayList<Action>(); + for (int roleid : roleID) { + actions = userDao.findAllActionsByRoleID(roleid); + completeActions.addAll(actions); + } + return completeActions; + } + + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userDao.findOnlyUser(username); + if (user == null) { + throw new UsernameNotFoundException("Invalid username or password."); + } + return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), + getAuthority()); + } + + private List<SimpleGrantedAuthority> getAuthority() { + return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")); + } + + public List<UserProfile> findAll(Integer pageNumber, Integer numberOfRecords, Boolean active, String keyword, + List<Long> roles, String countryCode, Long orgId) { + List<UserProfile> profileList = new ArrayList<>(); + + Integer startIndex = 0; + if (pageNumber != null && pageNumber >= 0) { + startIndex = ((pageNumber == 0) ? (pageNumber) : (pageNumber - 1) * numberOfRecords); + } + UserProfileMapper mapper = userDao.findAll(active, keyword, roles, countryCode, orgId); + if (mapper != null) { + Iterator<Entry<Long, UserProfile>> userItr = mapper.userMap.entrySet().iterator(); + while (userItr.hasNext()) { + Entry<Long, UserProfile> entry = userItr.next(); + if (null != entry.getValue()) { + profileList.add(entry.getValue()); + } + } + } + return applyPagignation(startIndex, numberOfRecords, profileList); + } + + private List<UserProfile> applyPagignation(Integer startIndex, Integer numberOfRecords, + List<UserProfile> profileList) { + List<UserProfile> finalProfileList = new ArrayList<>(); + if (numberOfRecords == null) { + numberOfRecords = profileList.size(); + } + for (int i = startIndex; i < (startIndex + numberOfRecords) && i < profileList.size(); i++) { + finalProfileList.add(profileList.get(i)); + } + return finalProfileList; + } + + @Override + public User findOne(String username) { + return userDao.findByUsername(username); + } + + @Override + public UserProfile findById(Long id, Long orgId) { + List<UserProfile> profileList = new ArrayList<>(); + UserProfileMapper mapper = userDao.findOne(id, orgId); + if (mapper != null) { + Iterator<Entry<Long, UserProfile>> userItr = mapper.userMap.entrySet().iterator(); + while (userItr.hasNext()) { + Entry<Long, UserProfile> entry = userItr.next(); + if (null != entry.getValue()) { + profileList.add(entry.getValue()); + } + } + + for (UserProfile profile : profileList) { + List<Role> roleList = mapper.userRoleMap.get(profile.getId()); + if (roleList != null) { + profile.setRoles(roleList); + } + } + } + return (profileList != null && !profileList.isEmpty()) ? profileList.get(0) : null; + } + + @Override + public User save(User user) { + String encryptedPassword = bcryptEncoder.encode(user.getPassword()); + user.setPassword(encryptedPassword); + return userDao.save(user); + } + + @Override + public UserAuthentication save(UserAuthentication user) { + return userDao.save(user); + } + + @Override + public User update(User user) { + return userDao.update(user); + } + + @Override + public List<Role> findAllRolesByUser(Long userId, String orgId) { + UserRoleMapper mapper = userDao.findAllRolesByUser(userId, orgId); + List<Role> roleList = new ArrayList<>(); + Iterator<Entry<Long, Role>> itr = mapper.roleMap.entrySet().iterator(); + while (itr.hasNext()) { + roleList.add(itr.next().getValue()); + } + return roleList; + } + + @Override + public Set<Action> findAllActionsByUser(Long userId, String orgId) { + Set<Action> actions = new HashSet<Action>(); + UserRoleMapper mapper = userDao.findAllRolesByUser(userId, orgId); + List<Role> roleList = new ArrayList<>(); + Iterator<Entry<Long, Role>> itr = mapper.roleMap.entrySet().iterator(); + while (itr.hasNext()) { + roleList.add(itr.next().getValue()); + } + for (Role role : roleList) { + actions.addAll(roleDao.findAllActionsByRole(role.getId())); + } + + return actions; + } + + @Override + public User findMobile(String phoneNo) { + return userDao.findMobile(phoneNo); + } + + @Override + public Boolean mapUserToRole(UserRoleDto userRole) { + return userDao.mapUserToRole(userRole); + } + + @Override + public UserProfile saveUserProfile(UserProfile profile) { + User newUser = new User(); + newUser.setUsername(profile.getUsername()); + newUser.setEmailId(profile.getEmailId()); + newUser.setPassword(profile.getPassword()); + newUser.setPhoneNo(profile.getPhoneNo()); + newUser.setIsActive(profile.getIsActive()); + newUser.setIsDeleted(profile.getIsDeleted()); + newUser.setOrgId(profile.getOrgId()); + newUser.setCountryCode(profile.getCountryCode()); + newUser.setTimeZone(profile.getTimeZone()); + newUser.setAvatarUrl(profile.getAvatarUrl()); + User savedUser = save(newUser); + profile.setId(savedUser.getId()); + return userDao.saveUserProfile(profile); + } + + @Override + public UserProfile updateUserProfileImage(UserProfile profile) { + return userDao.updateUserProfileImage(profile); + } + + @Override + public Long checkUserNameExists(String emailId, String phoneNo) { + Long userId = userDao.checkUserNameExists(emailId, phoneNo); + return userId; + } + + @Override + public Boolean uploadFile(MultipartFile file, long userId) { + try { + + // Get the file and save it somewhere + if (!new File(Constants.UPLOADED_FOLDER).exists()) { + if (new File(Constants.UPLOADED_FOLDER).mkdir()) { + LOGGER.info("Directory is created!"); + } else { + LOGGER.error("Failed to create directory!"); + } + } else { + LOGGER.info("Folder exist"); + } + + UserProfile userProfile = new UserProfile(); + byte[] bytes = file.getBytes(); + Path path = Paths.get(Constants.UPLOADED_FOLDER + userId + "_" + file.getOriginalFilename()); + LOGGER.info("Path before write: " + path); + Path path1 = Files.write(path, bytes); + LOGGER.info("Path after write : " + path1); + if (path1 != null) { + List<UserProfile> profileList = new ArrayList<>(); + UserProfileMapper userProfileMapper = userDao.findOneUser(userId); + + if (userProfileMapper != null) { + Iterator<Entry<Long, UserProfile>> userItr = userProfileMapper.userMap.entrySet().iterator(); + while (userItr.hasNext()) { + Entry<Long, UserProfile> entry = userItr.next(); + if (null != entry.getValue()) { + profileList.add(entry.getValue()); + } + } + + for (UserProfile profile : profileList) { + List<Role> roleList = userProfileMapper.userRoleMap.get(profile.getId()); + if (roleList != null) { + profile.setRoles(roleList); + } + } + } + userProfile = (profileList != null && !profileList.isEmpty()) ? profileList.get(0) : null; + + userProfile.setAvatarUrl(userId + "_" + file.getOriginalFilename()); + UserProfile profile = this.updateUserProfileImage(userProfile); + if (profile.getAvatarUrl() == userProfile.getAvatarUrl()) + return true; + else + return false; + } else + return false; + + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + @Override + public List<UserProfile> findListOfUsers(List<Long> userIdList) { + List<UserProfile> profileList = new ArrayList<>(); + UserProfileMapper mapper = userDao.findListOfUsers(userIdList); + if (mapper != null) { + Iterator<Entry<Long, UserProfile>> userItr = mapper.userMap.entrySet().iterator(); + while (userItr.hasNext()) { + Entry<Long, UserProfile> entry = userItr.next(); + if (null != entry.getValue()) { + profileList.add(entry.getValue()); + } + } + + for (UserProfile profile : profileList) { + List<Role> roleList = mapper.userRoleMap.get(profile.getId()); + if (roleList != null) { + profile.setRoles(roleList); + } + } + } + return profileList; + } + + @Override + public UserProfile updateUserProfile(UserProfile profile) { + User newUser = new User(); + newUser.setId(profile.getId()); + newUser.setUsername(profile.getUsername()); + newUser.setEmailId(profile.getEmailId()); + newUser.setPassword(profile.getPassword()); + newUser.setPhoneNo(profile.getPhoneNo()); + newUser.setIsActive(profile.getIsActive()); + newUser.setIsDeleted(profile.getIsDeleted()); + newUser.setTimeZone(profile.getTimeZone()); + newUser.setAvatarUrl(profile.getAvatarUrl()); + update(newUser); + return userDao.updateUserProfile(profile); + } + + @Override + public Long getNumberOfUsers(Long role, Boolean active) { + return userDao.getNumberOfUsers(role, active); + } + + @Override + public Long getNumberOfRoles() { + return userDao.getNumberOfRoles(); + } + + @Override + public List<Country> getCountryList() { + return userDao.getCountryList(); + } + + @Override + public List<Country> getCountryListForUser(Long userId) { + return userDao.getCountryListForUser(userId); + } + + @Override + public List<Country> getCountryListForOrg(Long orgId) { + return userDao.getCountryListForOrg(orgId); + } + + @Override + public Boolean mapUserToCountry(UserCountryDto userCountry) { + return userDao.mapUserToCountry(userCountry); + } + + @Override + public Boolean invalidateToken(String authToken) { + return userDao.invalidateToken(authToken); + } + + @Override + public Boolean findUserByToken(String authToken) { + return userDao.findUserByToken(authToken); + } + + @Override + public Boolean checkUserTokenExists(Long userId, String deviceToken) { + return userDao.checkUserTokenExists(userId, deviceToken); + } + + @Override + public Boolean updateUserDeviceToken(Long userId, String deviceToken, Long authTokenRef) { + return userDao.insertUserDeviceToken(userId, deviceToken, authTokenRef); + } + + @Override + public List<UserDeviceToken> getDeviceTokenForUsers(List<Long> userIdList) { + return userDao.getDeviceTokenForUserList(userIdList); + } + + @Override + public Long fetchAuthTokenReference(String authToken) { + return userDao.fetchAuthTokenReference(authToken); + } + + @Override + public Boolean hasAccess(List<Role> roles) { + List<Long> roleIds = new ArrayList<>(); + for (Role role : roles) { + roleIds.add(role.getId()); + } + List<Action> userActions = userDao.findAllActionsByRoleIDs(roleIds); + return false; + } + + @Override + public Boolean createCountry(CountryDto countryDto) { + return userDao.saveCountry(countryDto); + } + + @Override + public Boolean updateCountry(CountryDto countryDto) { + return userDao.updateCountry(countryDto); + } + + @Override + public Boolean checkCountryAlreadyExists(String code, Long orgId) { + return userDao.checkCountryExistsWithCode(code, orgId); + } + + @Override + public Boolean deleteUserToRole(UserRoleDto userRole) { + return userDao.deleteUserToRole(userRole); + } + + @Override + public Boolean deleteCountryForOrg(CountryDto countryDto) { + System.out.println("ID: " + countryDto.getId() + " OrgId " + countryDto.getOrgId()); + return userDao.deleteCountryForOrg(countryDto); + } + + @Override + public Boolean deleteUser(UserDto userDto) { + return userDao.deleteUser(userDto); + } + + @Override + public List<UserDto> getUsersByMasterRole(String roleCode, Long orgId) { + return userDao.getUsersByMasterRole(roleCode, orgId); + } + + @Override + public Boolean mapUserMasterRoleCountryOrg(UserMasterRoleCountryOrgDto userMasterRoleCountryOrgDto) { + return userDao.mapUserMasterRoleCountryOrg(userMasterRoleCountryOrgDto); + } + + @Override + public List<MasterRoleDto> getMasterRoleByOrgDomainId(Long orgDomainId) { + return userDao.getMasterRoleByOrgDomainId(orgDomainId); + } + + @Override + public UserDto findUserRolesActions(String username) { + if(userRoleActionMap.contains(username)) { + return userRoleActionMap.get(username); + } else { + UserRoleActionMapper mapper = userDao.findUserRolesActions(username); + UserDto userDto = getUserFromMapper(mapper); + userRoleActionMap.put(userDto.getUserName(), userDto); + return userDto; + } + + } + + private UserDto getUserFromMapper(UserRoleActionMapper mapper) { + UserDto dto = new UserDto(); + Iterator<Entry<Long, UserDto>> itr = mapper.userMap.entrySet().iterator(); + List<Role> roleList = new ArrayList<>(); + Set<Action> actionSet = new HashSet<Action>(); + while(itr.hasNext()) { + Entry<Long, UserDto> userEntry = itr.next(); + Long userId = userEntry.getKey(); + dto = userEntry.getValue(); + Map<Long, Role> roleMap = mapper.userRoleMap.get(userId); + if(roleMap != null) { + Iterator<Entry<Long, Role>> roleItr = roleMap.entrySet().iterator(); + while(roleItr.hasNext()) { + Entry<Long, Role> roleEntry = roleItr.next(); + Long roleId = roleEntry.getKey(); + Role role = roleEntry.getValue(); + roleList.add(role); + Map<Long, Action> roleActionMap = mapper.roleActionMap.get(roleId); + if(roleActionMap != null) { + Iterator<Entry<Long, Action>> actionItr = roleActionMap.entrySet().iterator(); + while(actionItr.hasNext()) { + Entry<Long, Action> actionEntry = actionItr.next(); + Action action = actionEntry.getValue(); + actionSet.add(action); + } + } + } + } + } + dto.setRoles(roleList); + dto.setActions(actionSet); + return dto; + } +} diff --git a/src/main/java/com/tarento/retail/util/Constants.java b/src/main/java/com/tarento/retail/util/Constants.java new file mode 100644 index 0000000000000000000000000000000000000000..d61abc570cbf320015974b3228519798be1e5806 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/Constants.java @@ -0,0 +1,155 @@ +package com.tarento.retail.util; + +public class Constants { + + /** + * Header and Request Parameters + */ + public static final long ACCESS_TOKEN_VALIDITY_SECONDS = 30 * 24 * 60 * 60; + public static final String SIGNING_KEY = "devglan123r"; + public static final String JWT_ISSUER = "http://devglan.com"; + public static final String JWT_GRANTED_AUTHORITY = "ROLE_ADMIN"; + public static final String TOKEN_PREFIX = "Bearer "; + public static final String HEADER_STRING = "Authorization"; + public static final String HEADER_APPLICATION_JSON = "application/json"; + public static final String ERROR_CODE = "errorCode"; + public static final String ERROR_FIELD = "errorField"; + public static final String ERROR_MESSAGE_CODE = "errorMessageCode"; + public static final String ERROR_MESSAGE_VALUE = "common.error."; + public static final String SUCCESS_CODE = "successCode"; + public static final String ERROR_MESSAGE = "errorMessage"; + public static final String SUCCESS_MESSAGE = "successMessage"; + public static final String AUTH_HEADER = "Authorization"; + + /** + * Query Parameters and Response Parameters + */ + public static String USER_INFO_HEADER = "x-user-info"; + public static String SUCCESS = "success"; + public static String ASC = "asc"; + public static String DESC = "desc"; + public static String TRUE = "true"; + public static String FALSE = "false"; + public static String STRING_BLANK = ""; + public static String COMMA_SPACE_SEPARATOR = ", "; + public static final String DATE = "date"; + public static String QUERY_ALERT_SUBJECT = "Query Alert!!"; + public static String SCHEDULER_ALERT_SUBJECT = "Scheduler Alert!!"; + public static String STRING_SPACE = " "; + public static String STRING_HYPEN = "-"; + public static String NEW_MESSAGE = "New"; + public static String READ_MESSAGE = "Read"; + public static String DELETE_MESSAGE = "Delete"; + public static String SEND_MESSAGE = "Send"; + public static String FILE_TYPE = "PDF,DOC,TXT,JPG,JPEG,PNG,GIF,AAC,MP3,MP4"; + public static String IMAGE_FILE_TYPE = "JPG,JPEG,PNG,GIF"; + public static String FCM_API_URL = "fcm.api.url"; + public static String FCM_API_KEY = "fcm.api.key"; + + /** + * URLs and Paths + */ + public static String UPLOADED_FOLDER = "/home/uploads/"; + + /** + * Status Code and Messages + */ + public static int UNAUTHORIZED_ID = 401; + public static int SUCCESS_ID = 200; + public static int FAILURE_ID = 320; + public static String UNAUTHORIZED = "Invalid credentials. Please try again."; + public static String PROCESS_FAIL = "Process failed, Please try again."; + + /** + * Allowed Origins for CORS Bean + */ + public static final String GET = "GET"; + public static final String POST = "POST"; + public static final String PUT = "PUT"; + public static final String DELETE = "DELETE"; + public static final String OPTIONS = "OPTIONS"; + + /** + * Qualifiers and Services + */ + public static final String USER_SERVICE = "userService"; + public static final String USER_DAO = "userDao"; + public static final String ROLE_ACTION_SERVICE = "roleActionService"; + public static final String ROLE_DAO = "roleDao"; + + public static enum CountryList { + SWE(1, "Sweden", "SWEDEN"), NOR(2, "Norway", "NORWAY"), FIN(3, "Finland", "FINLAND"), IND(4, "India", "INDIA"); + private int countryCode; + private String value; + private String name; + + CountryList(int statusId, String value, String name) { + this.countryCode = statusId; + this.value = value; + this.name = name; + } + + public int getStatusId() { + return countryCode; + } + + public void setStatusId(int statusId) { + this.countryCode = statusId; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + public static enum MasterRoleList { + COUNTRY_MANAGER(1, "COUNTRY MANAGER", "CNTR_MNGR"), SALES_AREA_MANAGER(2, "SALES AREA MANAGER", + "SL_AR_MNGR"), STORE_MANAGER(3, "STORE MANAGER", "ST_MNGR"); + private int id; + private String code; + private String name; + + public int getId() { + return id; + } + + private MasterRoleList(int id, String code, String name) { + this.id = id; + this.code = code; + this.name = name; + } + + public void setId(int id) { + this.id = id; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/src/main/java/com/tarento/retail/util/CustomException.java b/src/main/java/com/tarento/retail/util/CustomException.java new file mode 100644 index 0000000000000000000000000000000000000000..20c1b4273c9d5d6173921a16346a9615aa4a57a7 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/CustomException.java @@ -0,0 +1,53 @@ +package com.tarento.retail.util; + + +public class CustomException { + public CustomException() { + } + + public CustomException(Integer errorCode, String errorMessage, String errorMessageCode, CustomResponse response) { + this.errorCode = errorCode; + this.errorMessage = errorMessage; + this.errorMessageCode = errorMessageCode; + this.response = response; + } + + protected Integer errorCode; + protected String errorMessage; + protected String errorMessageCode; + protected CustomResponse response; + + public Integer getErrorCode() { + return errorCode; + } + + public void setErrorCode(Integer errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getErrorMessageCode() { + return errorMessageCode; + } + + public void setErrorMessageCode(String errorMessageCode) { + this.errorMessageCode = errorMessageCode; + } + + public void setResponse(CustomResponse response) { + this.response = response; + } + + public CustomException(int errorCode, String errorMessage) { + this.errorCode = errorCode; + this.errorMessage = errorMessage; + this.errorMessageCode = Constants.ERROR_MESSAGE_VALUE + errorCode; + } +} diff --git a/src/main/java/com/tarento/retail/util/CustomListResponse.java b/src/main/java/com/tarento/retail/util/CustomListResponse.java new file mode 100644 index 0000000000000000000000000000000000000000..3f8e4def2234e742323135fb84d860dfd1b2a519 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/CustomListResponse.java @@ -0,0 +1,31 @@ +package com.tarento.retail.util; + +public class CustomListResponse { + private int page; + private int pageSize; + private int count; + + public int getPage() { + return page; + } + + public void setPage(int page) { + this.page = page; + } + + public int getPageSize() { + return pageSize; + } + + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } +} diff --git a/src/main/java/com/tarento/retail/util/CustomResponse.java b/src/main/java/com/tarento/retail/util/CustomResponse.java new file mode 100644 index 0000000000000000000000000000000000000000..e89b0153f0f4092cb0ac91ef3647c5b244cb2b87 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/CustomResponse.java @@ -0,0 +1,45 @@ +package com.tarento.retail.util; + +import java.util.ArrayList; +import java.util.List; + +public class CustomResponse { + private String status; + private String success; + private List<Object> data = new ArrayList<Object>(); + + public CustomResponse() { + } + + public CustomResponse(String status, String success, List<Object> data) { + this.status = status; + this.success = success; + this.data = data; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getSuccess() { + return success; + } + + public void setSuccess(String success) { + this.success = success; + } + + public List<Object> getData() { + return data; + } + + public void setData(List<Object> data) { + this.data = data; + } + + +} diff --git a/src/main/java/com/tarento/retail/util/CustomSuccess.java b/src/main/java/com/tarento/retail/util/CustomSuccess.java new file mode 100644 index 0000000000000000000000000000000000000000..3fa6caf9bfd2c9317a5bfcbf3b843cb80353d43c --- /dev/null +++ b/src/main/java/com/tarento/retail/util/CustomSuccess.java @@ -0,0 +1,104 @@ +package com.tarento.retail.util; + + +import java.util.HashMap; +import java.util.List; + +public class CustomSuccess { + protected Integer successCode; + protected String successMessage; + protected Object data; + protected List<Object> dataList; + protected CustomResponse customResponse=null; + + public CustomSuccess(int successCode, String successMessage){ + this.successCode=successCode; + this.successMessage=successMessage; + } + + public CustomSuccess(Object data){ + if(data instanceof List){ + this.dataList=(List)data; + } else{ + this.data=data; + } + } + + + public Integer getSuccessCode() { + return successCode; + } + + public void setSuccessCode(Integer successCode) { + this.successCode = successCode; + } + + public String getSuccessMessage() { + return successMessage; + } + + public void setSuccessMessage(String successMessage) { + this.successMessage = successMessage; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public List<Object> getDataList() { + return dataList; + } + + public void setDataList(List<Object> dataList) { + this.dataList = dataList; + } + + public CustomResponse getCustomResponse() { + if(customResponse != null){ + return customResponse; + } + customResponse=new CustomResponse(); + customResponse.setSuccess(Constants.SUCCESS); + if(data != null){ + customResponse.getData().add(data); + }else if(dataList != null){ + customResponse.getData().addAll(dataList); + }else if(successCode != null){ + HashMap<String,Object> responseData=new HashMap<String,Object>(); + responseData.put(Constants.SUCCESS_CODE,successCode); + responseData.put(Constants.SUCCESS_MESSAGE,successMessage); + customResponse.getData().add(responseData); + } + return customResponse; + } + + public CustomResponse getCustomResponse(Object object) { + if(customResponse != null){ + return customResponse; + } + customResponse=new CustomResponse(); + customResponse.setSuccess(Constants.SUCCESS); + customResponse.setStatus("200"); + if(data != null){ + customResponse.getData().add(data); + }else if(dataList != null){ + customResponse.getData().addAll(dataList); + }else if(successCode != null){ + HashMap<String,Object> responseData=new HashMap<String,Object>(); + responseData.put(Constants.SUCCESS_CODE,successCode); + responseData.put(Constants.SUCCESS_MESSAGE,successMessage); + responseData.put("responseData",object); + customResponse.getData().add(responseData); + } + return customResponse; + } + + public void setCustomResponse(CustomResponse customResponse) { + this.customResponse = customResponse; + } + +} diff --git a/src/main/java/com/tarento/retail/util/JSONObjectUtil.java b/src/main/java/com/tarento/retail/util/JSONObjectUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..e127ea1338bc76cd29c612e5f8f27521616508d3 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/JSONObjectUtil.java @@ -0,0 +1,63 @@ +package com.tarento.retail.util; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; + +/** + * Created by Abhishek on 10/5/2017. + */ +@Service(value = "jsonObjectUtil") +public class JSONObjectUtil { + @Autowired + public ObjectMapper mapper; + @Autowired + public Gson gson; + + private static Logger logger = Logger.getLogger(JSONObjectUtil.class); + + + /** + * @return + */ + public static String getJsonString(ObjectMapper objectMapper,Object object) throws JsonProcessingException { + //initialize(); + if(objectMapper != null){ + return objectMapper.writeValueAsString(object); + } + return null; + } + + public String getJsonString(Object object) throws JsonProcessingException { + //initialize(); + if(mapper != null){ + return mapper.writeValueAsString(object); + } + if(gson != null){ + return gson.toJson(object); + } + return null; + } + + + public ObjectMapper getMapper() { + return mapper; + } + + public void setObjectMapper(ObjectMapper objectMapper){ + mapper=objectMapper; + } + + public Gson getGson() { + return gson; + } + + public void setGson(Gson gsonn) + { + gson = gsonn; + } +} diff --git a/src/main/java/com/tarento/retail/util/JsonKey.java b/src/main/java/com/tarento/retail/util/JsonKey.java new file mode 100644 index 0000000000000000000000000000000000000000..d9757aac8109175611e50056711741b403e66675 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/JsonKey.java @@ -0,0 +1,97 @@ +/** + * + */ +package com.tarento.retail.util; + +/** + * @author Abhishek + * + */ +public class JsonKey { + /* + * USER_NAME contains userName as key + */ + public static final String USER_ID = "userId"; + /* + * USER_NAME contains userName as key + */ + public static final String USER_NAME = "username"; + /* + * PASSWORD contains password + */ + public static final String PASSWORD = "password"; + /* + * OLD_PASSWORD + */ + public static final String OLD_PASSWORD = "oldPass"; + /* + * NEW_PASSWORD + */ + public static final String NEW_PASSWORD = "newPass"; + /* + * DEVICE_TYPE user device type + */ + public static final String DEVICE_TYPE = "deviceType"; + /* + * DEVICE_ID user device id. + */ + public static final String DEVICE_ID = "deviceId"; + /* + * TIMEZONE + */ + public static final String TIMEZONE = "timeZone"; + /* + * SESSION + */ + public static final String SESSION = "sessionId"; + /* + * FIRST_NAME + */ + public static final String FIRST_NAME = "firstName"; + /* + * LAST_NAME + */ + public static final String LAST_NAME = "lastName"; + + public static final String URL = "url"; + + public static final String USERNAME = "username"; + + public static final String LINK = "link"; + + public static final String ROLE_IDS = "roleIds"; + + public static final String ROLENAME = "roleName"; + /* + * EMAIL + */ + public static final String EMAIL = "email"; + public static final String STATUS_CODE = "statusCode"; + public static final String STATUS = "statusInfo"; + public static final String STATUS_MESSAGE = "statusMessage"; + public static final String ERROR_MESSAGE = "errorMessage"; + /** + * RESPONSE. + */ + public static final String RESPONSE = "response"; + public static final String RESPONSE_DATA = "responseData"; + + /** + * IS_ACTIVE. + */ + public static final String IS_ACTIVE = "isActive"; + /** + * IS_DELETED. + */ + public static final String IS_DELETED = "isDeleted"; + + public static final String TIME = "time"; + + public static final String SUBSCRIPTION_NAME = "subscriptionName"; + + public static final String ASSET_TYPE = "assetType"; + public static final String ASSET_NAME = "assetName"; + public static final String FROM_USER = "fromUser"; + + +} diff --git a/src/main/java/com/tarento/retail/util/PathRoutes.java b/src/main/java/com/tarento/retail/util/PathRoutes.java new file mode 100644 index 0000000000000000000000000000000000000000..16f973d9975cd6202fea80b6279324a814ed1e04 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/PathRoutes.java @@ -0,0 +1,65 @@ +package com.tarento.retail.util; + +/** + * + * @author Darshan Nagesh + * + */ + +public interface PathRoutes { + + final String USER_ACTIONS_URL = "/user"; + final String AUTH_URL = "/auth"; + + public interface UserRoutes { + final String USER_ACTIONS_POST = "/actions/_get"; + final String COUNTRY_LIST_GET = "/getCountryList"; + final String COUNTRY_LIST_USER_GET = "/getCountryList/{id}"; + final String EMPLOYMENT_TYPES_GET = "/getEmploymentTypes"; + final String NUMBER_OF_USERS_GET = "/getNumberOfUsers"; + final String NUMBER_OF_ROLES_GET = "/getNumberOfRoles"; + final String LIST_USER_GET = "/getAllUser"; + final String USER_BY_ID_GET = "/getUserById"; + final String CREATE_UPDATE_USER_POST = "/createOrUpdate"; + final String USER_ROLE_MAPPING_POST = "/role/mapping"; + final String USER_COUNTRY_MAPPING_POST = "/country/mapping"; + final String USER_DETAILS_GET = "/getUserDetails"; + final String SINGLE_FILE_UPLOAD_POST = "/upload"; + final String IMAGE_GET = "/images"; + final String USER_DEVICE_TOKEN_POST = "/updateUserDeviceToken"; + final String LOGOUT_GET = "/logout"; + final String CREATE_UPDATE_COUNTRY = "/createOrUpdateCountry"; + final String ORG_COUNTRY_LIST_GET = "/org/getCountryList"; + final String REMOVE_ROLE_MAPPING = "/role/mapping/delete"; + final String DELETE_COUNTRY = "/deleteCountry"; + final String DELETE_USER = "/deleteUser"; + final String GET_USER_LIST_BY_ORG = "/getUserListByOrg"; + final String GET_USERS_BY_MASTER_ROLE = "getUsersByMasterRole"; + final String MAP_USER_MASTER_ROLE_COUNTRY_ORG = "mapUserMasterRoleCountryOrg"; + } + + public interface AuthenticationRoutes { + final String AUTH_LOGIN_POST = "/login"; + final String AUTH_TOKEN_VALIDATE_POST = "/token/validate"; + final String AUTH_TOKEN_VALIDATE_GET = "/tokenValidate"; + + } + + public interface RoleActionRoutes { + final String LIST_ROLES_GET = "/roles/{orgId}"; + final String GET_DEFAULT_ROLES_BY_DOMAIN = "/domainRole"; + + final String ADD_ROLE_POST = "/add/role"; + final String ROLE_BY_ID_GET = "/role/{id}"; + final String UPDATE_ROLE_POST = "/role/update"; + final String NEW_ACTION_POST = "/feature"; + final String DELETE_ROLE_POST = "/deleteRole"; + final String MAP_ACTION_TO_ROLE = "/mapActionToRole"; + final String UNMAP_ACTION_TO_ROLE = "/unmapActionToRole"; + final String GET_MAP_ACTION_LIST = "/getMapActionToRole"; + final String GET_UNMAP_ACTION_LIST = "/getUnmapActionToRole"; + final String GET_MASTER_ROLE_BY_ORG_DOMAIN = "/getMasterRoleByOrgDomain"; + final String GET_USER_BY_ROLE_POST = "/getUsersByRole"; + final String ADD_ORG_DOMAIN_ROLES="/addOrgDomainRoles"; + } +} diff --git a/src/main/java/com/tarento/retail/util/ResponseCode.java b/src/main/java/com/tarento/retail/util/ResponseCode.java new file mode 100644 index 0000000000000000000000000000000000000000..9d41f26204a974950d96d8b09a7f7c63f9d7e6f6 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/ResponseCode.java @@ -0,0 +1,83 @@ +package com.tarento.retail.util; + +/** + * + * @author Abhishek + * + */ +public enum ResponseCode { + UnAuthorised(Constants.UNAUTHORIZED_ID, Constants.UNAUTHORIZED), Success( + Constants.SUCCESS_ID, Constants.SUCCESS),FAILURE( + Constants.FAILURE_ID, Constants.PROCESS_FAIL); + /** + * error code contains int value + */ + private int errorCode; + /** + * errorMessage contains proper error message. + */ + private String errorMessage; + + /** + * @param errorCode + * @param errorMessage + */ + private ResponseCode(int errorCode, String errorMessage) { + this.errorCode = errorCode; + this.errorMessage = errorMessage; + } + + /** + * + * @param errorCode + * @return + */ + public String getMessage(int errorCode) { + return ""; + } + + /** + * @return + */ + public int getErrorCode() { + return errorCode; + } + + /** + * @param errorCode + */ + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + /** + * @return + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * @param errorMessage + */ + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + /** + * This method will provide status message based on code + * + * @param code + * @return String + */ + public static String getResponseMessage(int code) { + String value = ""; + ResponseCode responseCodes[] = ResponseCode.values(); + for (ResponseCode actionState : responseCodes) { + if (actionState.getErrorCode() == code) { + value = actionState.getErrorMessage(); + } + } + return value; + } +} diff --git a/src/main/java/com/tarento/retail/util/ResponseGenerator.java b/src/main/java/com/tarento/retail/util/ResponseGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..1c1b586134a3138e4061a674fbc655f03adb3ba6 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/ResponseGenerator.java @@ -0,0 +1,75 @@ +package com.tarento.retail.util; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class ResponseGenerator { + + + private static ObjectMapper objectMapper = new ObjectMapper(); + + public static String failureResponse() throws JsonProcessingException{ + ObjectNode response = objectMapper.createObjectNode(); + response.put(JsonKey.STATUS_CODE, ResponseCode.FAILURE.getErrorCode()); + response.put(JsonKey.STATUS_MESSAGE, + ResponseCode.FAILURE.getErrorMessage()); + response.put(JsonKey.ERROR_MESSAGE, + ResponseCode.FAILURE.getErrorMessage()); + return JSONObjectUtil.getJsonString(objectMapper,response); + } + + + public static String failureResponse(String message) throws JsonProcessingException{ + ObjectNode actualResponse = objectMapper.createObjectNode(); + + ObjectNode response = objectMapper.createObjectNode(); + response.put(JsonKey.STATUS_CODE, ResponseCode.FAILURE.getErrorCode()); + response.put(JsonKey.STATUS_MESSAGE, + ResponseCode.FAILURE.getErrorMessage()); + response.put(JsonKey.ERROR_MESSAGE,message); + actualResponse.putPOJO(JsonKey.STATUS,response); + + return JSONObjectUtil.getJsonString(objectMapper,actualResponse); + } + + /** + * this method will crate success response and send to controller. + * + * @param obj + * Object + * @return ObjectNode object. + */ + public static String successResponse(Object obj) throws JsonProcessingException { + ObjectNode actualResponse = objectMapper.createObjectNode(); + + ObjectNode response = objectMapper.createObjectNode(); + response.put(JsonKey.STATUS_CODE, ResponseCode.Success.getErrorCode()); + response.put(JsonKey.STATUS_MESSAGE, ResponseCode.Success.getErrorMessage()); + response.put(JsonKey.ERROR_MESSAGE, ""); + actualResponse.putPOJO(JsonKey.STATUS,response); + if (obj != null) { + actualResponse.putPOJO(JsonKey.RESPONSE_DATA, obj); + } + + return JSONObjectUtil.getJsonString(objectMapper,actualResponse); + } + + /** + * this method will crate success response and send to controller. + * + * @return ObjectNode object. + */ + public static String successResponse() throws JsonProcessingException{ + ObjectNode actualResponse = objectMapper.createObjectNode(); + + ObjectNode response = objectMapper.createObjectNode(); + response.put(JsonKey.STATUS_CODE, ResponseCode.Success.getErrorCode()); + response.put(JsonKey.STATUS_MESSAGE, + ResponseCode.Success.getErrorMessage()); + response.put(JsonKey.ERROR_MESSAGE, ""); + actualResponse.putPOJO(JsonKey.STATUS,response); + + return JSONObjectUtil.getJsonString(objectMapper,actualResponse); + } +} diff --git a/src/main/java/com/tarento/retail/util/ResponseMessages.java b/src/main/java/com/tarento/retail/util/ResponseMessages.java new file mode 100644 index 0000000000000000000000000000000000000000..16cb80f19c0009cd35e524f65c00ed264f5d3c34 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/ResponseMessages.java @@ -0,0 +1,49 @@ +package com.tarento.retail.util; + +public interface ResponseMessages { + + final String UNAVAILABLE = "UNAVAILABLE"; + final String INVALID = "INVALID"; + final String ALREADY_EXISITS = "ALREADYEXISTS"; + final String INTERNAL_ERROR = "INTERNALERROR"; + + public interface ErrorMessages { + final Integer CUSTOM_ERROR_ID = 9999; + final String ROLE_NAME_UNAVAILABLE = "Role Name is mandatory. Please add and try again"; + final String ROLE_ID_UNAVAILABLE = "Role ID is mandatory. Please add and try again"; + final String ROLE_DETAILS_UNAVAILABLE = "Role Details are not available. Please check"; + final String ROLE_DETAILS_NOTSAVED = "Unable to save the Role Details. Please try again later"; + final String USER_ROLE_MAPPING_NOTSAVED = "Unable to save the User Role mapping"; + final String USER_ID_UNAVAILABLE = "User ID is mandatory. Please add and try again"; + final String ROLE_ID_INVALID = "Role ID cannot be Zero. Please check and try again!"; + final String FEATURE_NAME_UNAVAILABLE = "Feature Name is mandatory. Please add and try again"; + final String FEATURE_CODE_UNAVAILABLE = "Feature Code is mandatory. Please add and try again"; + final String FEATURE_URL_UNAVAILABLE = "Feature URL is mandatory. Please add and try again"; + final String FEATURE_DETAILS_UNAVAILABLE = "Feature Details are not available. Please check"; + final String FEATURE_DETAILS_NOTSAVED = "Unable to save the Feature Details. Please try again later"; + final String USER_PROFILE_UNAVAILABLE = "User Profile Details are not found. Please check"; + final String USER_NAME_ALREADY_EXISTS = "UserName already exists. Please try with a different input"; + final String USER_PROFILE_ID_MANDATORY = "User Profile ID is mandatory. Please check"; + final String USER_PROFILE_SAVE_FAILURE = "Could not save the User Profile. Please check"; + final String EMAIL_PHONE_ALREADY_EXISTS = "This email or phone number already exists. Please reenter and check "; + final String EMAIL_MANDATORY = "Email Address is mandatory. Please enter and try again"; + final String COUNTRY_ID_UNAVAILABLE = "Country ID is mandatory. Please add and try again"; + final String COUNTRY_DETAILS_UNAVAILABLE = "Country Details are not available. Please check"; + final String LOGOUT_FAILED = "User Log Out action has failed. Please try again"; + final String UNAUTHORIZED_PERMISSION = "User does not have permision to create User. Please Check"; + final String UNAUTHORIZED_ROLE_MAPPING_PERMISSION = "User does not have role mapping permisoin to User. Please Check"; + final String ORG_DOMAIN_CODE_UNAVAILABLE = "ORG Domain code is mandatory. Please add and try again"; + final String ORG_ID_UNAVAILABLE = "ORG ID is mandatory. Please add and try again"; + } + + public interface SuccessMessages { + final String ROLE_CREATED = "Role has been added successfully!"; + final String ROLE_UPDATED = "Role has been updated successfully!"; + final String USER_ROLE_MAPPED = "User has been mapped to Role"; + final String REMOVE_USER_ROLE_MAPPED = "User has been removed to Role"; + final String USER_COUNTRY_MAPPED = "User has been mapped to Country"; + final String ACTION_ADDED = "Feature has been added successfully!"; + final String LOGOUT_SUCCESS = "User Logged out successfully"; + } + +} diff --git a/src/main/java/com/tarento/retail/util/ResponseUtil.java b/src/main/java/com/tarento/retail/util/ResponseUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..b490e49778492c5a98316314653fa57f8135cc82 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/ResponseUtil.java @@ -0,0 +1,95 @@ +package com.tarento.retail.util; + +import java.io.IOException; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.cxf.jaxrs.ext.MessageContext; + +public class ResponseUtil { + + /** + * Method to throw bad request with error message + * + * @param errorDescription + */ + public static void sendBadRequest(String errorDescription) { + ResponseBuilder resp = Response.status(Response.Status.BAD_REQUEST); + resp.entity(errorDescription); + WebApplicationException ex = new WebApplicationException(resp.build()); + throw ex; + } + + /** + * Method to throw Unauthorized request with error message + * + * @param errorDescription + */ + public static Response sendUnauthorized(String errorDescription) throws JsonProcessingException{ + ResponseBuilder resp = Response.status(Response.Status.UNAUTHORIZED); + resp.entity(ResponseGenerator.failureResponse(errorDescription)); + return resp.build(); + } + + /** + * Method to throw Internal server error + * + * @param errorDescription + */ + public static Response sendServerError(String errorDescription) { + ResponseBuilder resp = Response.status(Response.Status.INTERNAL_SERVER_ERROR); + resp.entity(errorDescription); + return resp.build(); + } + + /** + * Method to throw Unauthorized request with error message + * + * @param errorDescription + */ + public static void unauthorizedResponse(HttpServletResponse response, String errorDescription) throws IOException { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType("application/json"); + response.getWriter().write(errorDescription); + } + + public static Response sendOK(ObjectNode obj) { + ResponseBuilder resp = Response.status(Response.Status.OK); + resp.entity(obj); + return resp.build(); + } + + public static Response sendOK(String obj) { + ResponseBuilder resp = Response.status(Response.Status.OK); + resp.entity(obj); + return resp.build(); + } + + public static void sendRedirect(MessageContext context, String path){ + try{ + HttpServletResponse response = context.getHttpServletResponse(); + response.sendRedirect(path); + }catch(Exception e){ + sendServerError("Unable to redirect"); + } + } + + public static void sendInternalError(String errorDescription) throws JsonProcessingException { + ResponseBuilder resp = Response.status(Response.Status.INTERNAL_SERVER_ERROR); + resp.entity(ResponseGenerator.failureResponse(errorDescription)); + WebApplicationException ex = new WebApplicationException(resp.build()); + throw ex; + } + + public static void sendInternalError() throws JsonProcessingException { + ResponseBuilder resp = Response.status(Response.Status.INTERNAL_SERVER_ERROR); + resp.entity(ResponseGenerator.failureResponse()); + WebApplicationException ex = new WebApplicationException(resp.build()); + throw ex; + } +} diff --git a/src/main/java/com/tarento/retail/util/Sql.java b/src/main/java/com/tarento/retail/util/Sql.java new file mode 100644 index 0000000000000000000000000000000000000000..344ce0cc9d90270dad0c8daaacb5563eebb6b803 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/Sql.java @@ -0,0 +1,172 @@ +package com.tarento.retail.util; + +/** + * This interface will hold all the SQL Quries which are being used by the + * application Internally, the inner interface will have the queries separated + * based on the functionalities that they are associated with + * + * @author Darshan Nagesh + * + */ +public interface Sql { + + final String ID = "id"; + + /** + * All the queries associated with the Common activities or transactions will be + * placed here + * + * @author Darshan Nagesh + * + */ + public interface Common { + final String VERIFY_PASSWORD = "SELECT id FROM user WHERE password = ? AND username = ? "; + final String WHERE_CLAUSE = " WHERE "; + final String AND_CONDITION = " AND "; + final String OR_CONDITION = " OR "; + final String OPEN_BRACE = "("; + final String CLOSE_BRACE = ")"; + final String GET_COUNTRY_LIST = "SELECT id, name, code, currency, phone_code, FALSE as is_default FROM country "; + final String GET_COUNTRY_LIST_FOR_USER = "SELECT c.id, c.name, c.code, c.currency, c.phone_code, cu.is_default FROM country c left join country_user cu ON c.id = cu.country_id where cu.user_id = ?"; + final String GET_COUNTRY_LIST_FOR_ORG = "SELECT id, name, code, currency, phone_code, url FROM country WHERE org_id = ?"; + final String BY_ROLE_ID = " role_id in (<ROLE_ID>) "; + final String DELETE_COUNTRY_FOR_USER = "DELETE from country_user where country_id=?"; + final String DELETE_COUNTRY_FOR_ORG = "DELETE from country where id=? AND org_id=? "; + } + + public interface RoleAction { +// final String GET_ALL_ROLES = "SELECT id, role_name, r.code , description, org_id FROM role r INNER JOIN role_org ro ON r.id= ro.role_id WHERE ro.org_id = ?"; + final String GET_ALL_ROLES = "SELECT id, role_name, code , description, org_id FROM role where org_id=?"; + // final String GET_ROLE_BY_ORG_DOMAIN = "select * from org_domain_role odr + // INNER JOIN role r ON odr.role_id = r.id where org_domain=?"; + final String GET_ROLE_BY_ORG_DOMAIN = "select * from org_domain_role where org_domain=?"; + final String SELECT_ROLES_ON_ID = "SELECT * FROM role WHERE id=?"; + final String GET_DEFAULT_ROLES = "SELECT * FROM org_domain_role WHERE role_id = ?"; + final String GET_ROLE_BY_USER = "select r.role_id as id, r.description as description, r.role_name as role_name, r.org_id as org_id from user usr inner join user_role ur on usr.id = ur.user_id inner join role r on r.id = ur.role_id where usr.id = ? and r.org_id= ?"; + final String SELECT_ROLE_ACTIONS_ON_ROLEID = "SELECT * FROM role_actions WHERE role_id=?"; + final String SELECT_ACTIONS_ON_ID = "SELECT * FROM actions WHERE id=?"; + final String SAVE_NEW_ROLE = "INSERT INTO role (role_name,description,code, is_org_admin, org_id) VALUES (? , ?, ?,?,?)"; + + final String UPDATE_ROLE = "UPDATE role SET role_name = ?, description = ? WHERE id= ? "; + final String UPDATE_ROLE_ORG = "INSERT INTO role_org(role_id, org_id) value (?,?) "; + + final String INSERT_ACTION = "INSERT INTO retail_actions (description, module_code, module_name, url) VALUES (?, ?, ?, ?)"; + final String DELETE_ROLE = "DELETE from role where id=?"; + final String MAP_ACTION_TO_ROLE = "insert into role_actions(role_id,action_id) values(?,?)"; +// final String MAP_ACTION_TO_ROLE = "insert into role_actions(role_id,action_id, org_id) values(?,?,?)"; + final String UNMAP_ORG_ROLE = "DELETE FROM role_org WHERE role_id = ? AND org_id = ?"; + final String UNMAP_ACTION_TO_ROLE = "delete from role_actions where action_id=? and role_id = ?"; + final String GET_MAPPED_ACTION_ROLE_LIST = "select * from retail_user.actions where id IN (select action_id as id from retail_user.role_actions where role_id=?)"; + final String GET_UNMAPPED_ACTION_ROLE_LIST = "select * from retail_user.actions where id NOT IN (select action_id as id from retail_user.role_actions where role_id=?)"; + // final String DELETE_USER_ROLE="DELETE from "; + final String GET_USERS_BY_ROLE_ID = "select id, username, email_id, phone_no, org_id, timezone from retail_user.user where id IN ( select user_id from retail_user.user_role where role_id=? AND org_id=?)"; + } + + public interface UserQueries { + final String SELECT_USER_BY_TOKEN = "SELECT COUNT(*) FROM user_authentication WHERE auth_token = ? "; + final String SELECT_USER_ON_USERNAME = "SELECT * FROM user usr inner join country_user cu on usr.id =cu.user_id inner join country c on cu.country_id = c.id where username=? or phone_no = ?"; + + final String SELECT_ONLY_USER = "SELECT id, username, password, email_id, phone_no FROM user where username = ? or phone_no = ? "; + + final String MAP_USER_TO_ROLE = "INSERT INTO user_role (user_id, role_id, org_id) VALUES (?, ?, ?)"; + final String MAP_USER_TO_COUNTRY = "INSERT INTO retail_user.country_user (user_id, country_id, is_default) VALUES (?, ?, ?)"; + final String REMOVE_USER_ROLE_MAP = "DELETE FROM user_role WHERE user_id = ?"; + final String REMOVE_USER_COUNTRY_MAP = "DELETE FROM country_user WHERE user_id = ? "; + final String ADD_NEW_COUNTRY = "INSERT INTO country(code, name, currency, phone_code, url, org_id) VALUES(?, ?, ?, ?, ?, ?)"; + final String UPDATE_COUNTRY = "UPDATE country SET code=?, name= ?,currency = ?, phone_code= ? where id = ?"; + final String INSERT_USER_PROFILE = "INSERT INTO user_profile (user_id, first_name, last_name, age, phone_number, dob, gender, " + + "avatar_url, work_start_date, work_end_date, email_id, country, registration_date, " + + "created_by, created_date, updated_by, updated_date, employment_type) VALUES " + + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "; + final String GET_COUNTRY_BY_CODE = "SELECT * FROM country WHERE code= ? and org_id= ? "; + + final String Update_USER_PROFILE = "UPDATE user_profile SET user_id = ?, first_name = ?, last_name = ?, age = ?, phone_number = ?, dob = ?, gender = ?, " + + "avatar_url = ?, work_start_date = ?, work_end_date = ?, salary = ?, email_id = ?, country = ?, is_active = ?, is_deleted = ?, registration_date = ?, " + + "created_by = ?, created_date = ?, updated_by = ?, updated_date = ?"; + + final String Update_USER_PROFILE_PROFILE_IMAGE = "UPDATE user_profile SET avatar_url = ? WHERE id = ?"; + + final String GET_USER_ACTIONS = "SELECT * FROM actions ma inner join role_actions mra on mra.action_id = ma.id where ma.enabled = true and mra.role_id in (<roleIds>)"; + final String USER_PROFILE_FETCH = "select usr.id, usr.timezone, usr.username, usr.email_id, usr.phone_no, " + + "prof.first_name, prof.last_name, prof.age, prof.dob, prof.gender, prof.avatar_url, " + + "prof.work_start_date, prof.work_end_date, prof.salary, prof.email_id, c.name as country, usr.is_active, usr.is_deleted, prof.registration_date, " + + "prof.created_date, prof.created_by, prof.updated_date, prof.updated_by, prof.employment_type, usrrole.role_id, role.role_name, role.description " + + "from user usr LEFT JOIN country_user cu ON usr.id=cu.user_id LEFT JOIN country c ON cu.country_id = c.id LEFT JOIN user_profile prof ON usr.id = prof.user_id " + + "LEFT JOIN user_role usrrole ON usr.id = usrrole.user_id " + + "LEFT JOIN role role ON role.id = usrrole.role_id"; + final String GET_USER_BY_ID = USER_PROFILE_FETCH + " WHERE usr.id = ?"; + final String GET_USER_AUTH_DETAILS = "SELECT id, user_id, auth_token FROM user_authentication WHERE id=?"; + final String SAVE_USER = "INSERT INTO user(username,password,email_id, phone_no, is_active, is_deleted, org_id , timezone, avatar_url) VALUES (?,?,?,?,?,?, ?,?,?)"; + final String SAVE_USER_AUTHENTICATION = "INSERT INTO user_authentication(user_id,auth_token) VALUES (?,?)"; + final String GET_USER_ROLE = "SELECT user_id, role_id FROM user_role WHERE user_id=?"; + final String GET_ROLES_FOR_USER = " select ur.user_id, ur.role_id, r.role_name, r.description , r.is_super_admin as is_super_admin , \r\n" + + "r.org_id as org_id from user_role ur LEFT JOIN role r ON ur.role_id = r.id \r\n" + + "WHERE ur.user_id = ? and r.org_id = ? "; + final String GET_USER_BY_PHONE = "SELECT usr.id as id, username, password, email_id, phone_no, usr.org_id, c.code as code, usr.timezone FROM user usr left join country_user cu on usr.id = cu.user_id left join country c on c.id = cu.country_id WHERE phone_no=?"; + final String USER_ACTIVE_CONDITION = " WHERE usr.is_active = ? "; + final String WHERE_CLAUSE = " WHERE "; + final String AND_CONDITION = " AND "; + final String OR_CONDITION = " OR "; + + final String USER_PROFILE_FETCH_PAGINATION_1 = "select usr.id, usr.username, usr.email_id, usr.phone_no, prof.first_name, prof.last_name, prof.age, prof.dob, prof.gender, prof.avatar_url, prof.work_start_date, prof.work_end_date, prof.salary, prof.email_id, prof.country, usr.is_active, usr.is_deleted, prof.registration_date, prof.created_date, prof.created_by, prof.updated_date, prof.updated_by, prof.employment_type, usrrole.role_id, role.role_name, role.description, role.privilege " + + " from (select id, username, email_id, phone_no, is_active, is_deleted from user "; + final String USER_ACTIVE_CONDITION_PAGINATION = " WHERE is_active = ? "; + final String USER_PROFILE_FETCH_PAGINATION_2 = " order by id limit ?,?) usr LEFT JOIN user_profile prof ON usr.id = prof.user_id " + + " LEFT JOIN user_role usrrole ON usr.id = usrrole.user_id " + + " LEFT JOIN role role ON role.id = usrrole.role_id "; + final String TAIL_CONDITIONS_EMAIL_LIKE = " usr.email_id LIKE ?"; + final String TAIL_CONDITIONS_FIRSTNAME_LIKE = " prof.first_name LIKE ?"; + final String TAIL_CONDITIONS_LASTNAME_LIKE = " prof.last_name LIKE ?"; + final String TAIL_CONDITIONS_COUNTRY_LIKE = " prof.country LIKE ?"; + final String TAIL_CONDITIONS_USER_ACTIVE = " usr.is_active is TRUE "; + final String TAIL_CONDITIONS_USER_INACTIVE = " usr.is_active is FALSE "; + final String TAIL_CONDITIONS_USER_ROLEIN = " usrrole.role_id IN "; + final String TAIL_CONDITIONS_COUNTRY_EQUALS = " prof.country = ? "; + final String ORDER_BY_USER_ID = " ORDER BY usr.id "; + final String USER_ID_EQUAL_CONDITION = " usr.id = ?"; + final String USER_ID_IN_CONDITION = " usr.id IN "; + final String USER_ORG_ID = " usr.org_id = ? "; + final String USER_ROLE_ORG_ID = "usrrole.org_id=?"; + final String UPDATE_USER = "UPDATE user SET email_id = ?, username = ?, phone_no = ?, is_active = ?, is_deleted = ? , timezone= ?, avatar_url where id = ? "; + final String UPDATE_USER_PROFILE = "UPDATE user_profile SET first_name = ?, last_name = ?, age = ?, phone_number = ?, dob = ?, gender = ?, work_start_date = ?, " + + "work_end_date = ?, country = ?, updated_date = ?, updated_by = ?, employment_type = ?, registration_date = ?, avatar_url=? WHERE user_id = ? "; + final String GET_USER_COUNT = "SELECT count(*) FROM user usr"; + final String GET_USER_COUNT_ON_ACTIVE_STATUS = "SELECT count(*) FROM user usr where usr.is_active = ? "; + final String GET_USER_COUNT_FOR_ROLE = "SELECT count(*) FROM user usr LEFT JOIN user_role usrrole ON usr.id = usrrole.user_id where usrrole.role_id = ? " + + "and usr.is_active IS TRUE"; + final String GET_ROLE_COUNT = "SELECT count(*) FROM role"; + + final String INVALIDATE_TOKEN = "DELETE from user_authentication WHERE auth_token = ? "; + final String CHECK_USER_DEVICE_TOKEN = "SELECT COUNT(*) FROM user_device WHERE user_id = ? AND device_token = ? "; + final String INSERT_USER_DEVICE_TOKEN = "INSERT INTO user_device (user_id, device_token, created_date, user_auth_id) VALUES (?,?,?,?) "; + final String UPDATE_USER_DEVICE_TOKEN = "UPDATE user_device SET device_token = ?, created_date = ? WHERE user_id = ? "; + final String FETCH_USER_DEVICE_TOKEN = " SELECT device.id, device.user_id, device.device_token FROM user_device device WHERE device.user_id IN "; + final String USER_DEVICE_ROLE_CONDITION = " and exists (select 1 from user_role where user_id = device.user_id and role_id IN (1,2)) " + + "and not exists (select 1 from user_role where user_id = device.user_id and role_id NOT IN (1,2)) "; + final String FETCH_AUTH_TOKEN_REF = "SELECT id FROM user_authentication WHERE auth_token = ? "; + final String REMOVE_USER_DEVICE_TOKEN = "DELETE from user_device WHERE user_auth_id IN (SELECT id FROM user_authentication WHERE auth_token =?) "; + final String DELETE_USER = "DELETE from user WHERE id=?"; + final String DELETE_USER_ROLE = "DELETE from user_role where user_id=?"; + final String DELETE_COUNTRY_USER = "DELETE from country_user where user_id=?"; + + final String DELETE_USER_PROFILE = "DELETE from user_profile where user_id=?"; + final String GET_USERS_BY_MASTER_ROLE = "SELECT usr.id, usr.username FROM user usr INNER JOIN user_role ur ON usr.id = ur.user_id INNER JOIN role r ON ur.role_id = r.id WHERE r.code= ? AND ur.org_id = ?"; + final String MAP_USER_MASTER_ROLE_COUNTRY_ORG = "insert into retail_user.master_role_country_user_org(master_role_id,user_id,country_id,org_id) values(?,?,?,?)"; + final String GET_MASTER_ROLE_LIST_BY_ORG_DOMAIN = "select * from retail_user.master_role where id IN (select master_role_id from " + + "retail_user.master_role_org_domain where org_domain_id=?)"; + final String GET_USER_ROLE_ACTIONS = " SELECT usr.id as userId, usr.password as userPassword, usr.username as username, usr.email_id as userEmailId, usr.phone_no as userPhoneNo, " + + " usr.is_active as userIsActive, usr.is_deleted as userIsDeleted, usr.org_id as userOrgId, usr.avatar_url as userAvatarUrl, " + + " cu.country_id as userCountryId, " + + " r.id as roleId, r.role_name as roleName, r.code as roleCode, r.description as roleDescription, r.is_super_admin as isSuperAdmin, "+ + " r.is_org_admin as isOrgAdmin, r.org_id as roleOrgId, " + + " act.id as actionId, act.name as actionName, act.url as actionUrl " + + " from user usr LEFT JOIN country_user cu ON usr.id = cu.user_id " + + " LEFT JOIN user_role ur ON ur.user_id = usr.id " + + " LEFT JOIN role r ON ur.role_id = r.id " + + " LEFT JOIN role_org ro ON ro.role_id = r.id " + + " LEFT JOIN role_actions ra ON r.id = ra.role_id " + + " LEFT JOIN actions act ON ra.action_id = act.id " + + " WHERE usr.username = ? "; + } + +} diff --git a/src/main/java/com/tarento/retail/util/sql/Clause.java b/src/main/java/com/tarento/retail/util/sql/Clause.java new file mode 100644 index 0000000000000000000000000000000000000000..90a28998e80cf392eb7004a1c4ca5bca3ab9beb2 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/sql/Clause.java @@ -0,0 +1,10 @@ +package com.tarento.retail.util.sql; + +/** + * Created by sumonto on 8/3/18. + */ +public interface Clause { + final static String Where = " WHERE "; + final static String And = " AND "; + final static String Or = " OR "; +} diff --git a/src/main/java/com/tarento/retail/util/sql/UserSQL.java b/src/main/java/com/tarento/retail/util/sql/UserSQL.java new file mode 100644 index 0000000000000000000000000000000000000000..53298705d03e915b598d1b6b19d0829c9b385d17 --- /dev/null +++ b/src/main/java/com/tarento/retail/util/sql/UserSQL.java @@ -0,0 +1,35 @@ +package com.tarento.retail.util.sql; + +public interface UserSQL { + + interface InsertQuery{ + final String ADD_USER = "INSERT INTO user(username,password,age) VALUES (?,?,?)"; + final String ADD_USER_AUTHENTICATION = "INSERT INTO user_authentication(user_id,auth_token) VALUES (?,?)"; + + } + + interface UpdateQuery{ + final String UPDATE_USER = "UPDATE user SET (username,password,age) VALUES (?,?,?)"; + + } + + interface FindQuery{ + final String FIND_USER = "SELECT * FROM user"; + final String FIND_USER_AUTHENTICATION = "SELECT * FROM user_authentication"; + final String FIND_USER_ROLE = "SELECT * FROM musti_user_role"; + final String FIND_ROLE = "SELECT * FROM musti_role"; + final String FIND_ROLE_ACTION = "SELECT * FROM musti_role_actions"; + final String FIND_ACTION = "SELECT * FROM musti_actions"; + + } + + interface Conditions{ + final String byId = " id=?"; + final String byPhoneNo = " phone_no=?"; + final String byUserName = " username=?"; + final String byUserId = " user_id=?"; + final String byRoleId = " role_id=?"; + + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..42cf5c1b8a311ccb8ada9e03346f6a028da017ef --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,26 @@ +# SET CONTEXT PATH +server.port=8081 + +#spring.datasource.driver-class-name=com.mysql.jdbc.Driver +#spring.datasource.url=jdbc:mysql://52.29.100.78:3306/retail_user +#spring.datasource.username=root +#spring.datasource.password=Rain123#$ +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://localhost:3306/retail_user?useSSL=false +spring.datasource.username=root +spring.datasource.password=root + +spring.http.multipart.max-file-size=10MB +spring.http.multipart.max-request-size=10MB + +flyway.enabled=false +flyway.user=root +flyway.password=root +flyway.outOfOrder=true +flyway.table=retail_user_schema_version +flyway.baseline-on-migrate=true +flyway.url=jdbc:mysql://localhost:3306/retail_user +flyway.locations=db/migration/ddl + + + diff --git a/src/main/resources/application.properties.j2 b/src/main/resources/application.properties.j2 new file mode 100644 index 0000000000000000000000000000000000000000..232fe7ea7ed9c335a79f7219a13eff703cd49453 --- /dev/null +++ b/src/main/resources/application.properties.j2 @@ -0,0 +1,19 @@ +# SET CONTEXT PATH +server.port=8081 + +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://172.31.37.107:3306/retail_user +spring.datasource.username=kronos_rain +spring.datasource.password=Kr03osR1n + +spring.http.multipart.max-file-size=10MB +spring.http.multipart.max-request-size=10MB + +flyway.enabled=false +flyway.user=root +flyway.password=Rain123#$ +flyway.outOfOrder=true +flyway.table=retail_user_schema_version +flyway.baseline-on-migrate=true +flyway.url=jdbc:mysql://localhost:3306/retail_user +flyway.locations=db/migration/ddl \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191102113316__retail_basic_user_ddl.sql b/src/main/resources/db/migration/ddl/V20191102113316__retail_basic_user_ddl.sql new file mode 100644 index 0000000000000000000000000000000000000000..d69ee80363c8cde073e7818c6a1704dd308b719d --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191102113316__retail_basic_user_ddl.sql @@ -0,0 +1,162 @@ +CREATE TABLE `address` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `street` varchar(50) DEFAULT NULL, + `city` varchar(50) DEFAULT NULL, + `state` varchar(50) DEFAULT NULL, + `pincode` bigint(20) NOT NULL, + `address_loc` varchar(100) DEFAULT NULL, + `country_code` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=1100 DEFAULT CHARSET=latin1; + + +CREATE TABLE `country` ( + `id` bigint(3) NOT NULL AUTO_INCREMENT, + `code` varchar(45) DEFAULT NULL, + `name` varchar(100) NOT NULL, + `currency` varchar(45) DEFAULT NULL, + `phone_code` varchar(45) DEFAULT NULL, + `url` varchar(200) DEFAULT NULL, + `org_id` int NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1; + +CREATE TABLE `user` ( + `id` bigint(20) AUTO_INCREMENT, + `password` varchar(255) NOT NULL, + `username` varchar(255) NOT NULL, + `email_id` varchar(255) DEFAULT NULL, + `phone_no` varchar(45) DEFAULT NULL, + `is_active` tinyint(1) DEFAULT '1', + `is_deleted` tinyint(1) DEFAULT '0', + `org_id` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `username` (`username`) +) ENGINE=InnoDB AUTO_INCREMENT=147 DEFAULT CHARSET=latin1; + + +CREATE TABLE `country_user` ( + `user_id` bigint(20) NOT NULL, + `country_id` bigint(3) NOT NULL, + `is_default` tinyint(1) DEFAULT NULL, + KEY `fk_country_user_userid_idx` (`user_id`), + KEY `fk_country_user_countryid_idx` (`country_id`), + CONSTRAINT `fk_country_user_countryid` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fk_country_user_userid` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + + +CREATE TABLE `actions` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `display_name` varchar(255) NOT NULL, + `url` varchar(500) NOT NULL, + `service_code` varchar(100) NOT NULL, + `menu_group_code` varchar(45) NOT NULL, + `menu_group_name` varchar(255) DEFAULT NULL, + `colour_code` varchar(45) NOT NULL, + `enabled` tinyint(4) NOT NULL, + `created_user` bigint(20) NOT NULL, + `created_date` datetime DEFAULT NULL, + `update_user` bigint(20) DEFAULT NULL, + `update_date` datetime DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=100 DEFAULT CHARSET=latin1 ENGINE=InnoDB AUTO_INCREMENT=78 DEFAULT CHARSET=latin1; + + +CREATE TABLE `role` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `role_name` varchar(255) NOT NULL, + `code` varchar(125) NOT NULL, + `description` varchar(255) DEFAULT NULL, + `is_super_admin` bit(1) DEFAULT NULL, + `is_org_admin` bit(1) DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=2000 DEFAULT CHARSET=latin1; + + + CREATE TABLE `role_org`( + `role_id` bigint(20) NOT NULL, + `org_id` bigint(20) NOT NULL +)ENGINE=InnoDB DEFAULT CHARSET=latin1; + + +CREATE TABLE `role_actions` ( + `role_id` bigint(20) NOT NULL, + `action_id` bigint(20) NOT NULL, + KEY `role_id` (`role_id`), + KEY `action_id` (`action_id`), + CONSTRAINT `role_actions_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`), + CONSTRAINT `role_actions_ibfk_2` FOREIGN KEY (`action_id`) REFERENCES `actions` (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=latin1; + + + CREATE TABLE `user_role` ( + `user_id` bigint(20) DEFAULT NULL, + `role_id` bigint(20) DEFAULT NULL, + `org_id` bigint(20) DEFAULT NULL, + KEY `fk_user_role_userId` (`user_id`), + KEY `fk_user_role_roleId` (`role_id`), + CONSTRAINT `fk_user_role_userId` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`), + CONSTRAINT `fk_user_role_roleId` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) + )ENGINE=InnoDB AUTO_INCREMENT=70 DEFAULT CHARSET=latin1; ; + +CREATE TABLE `user_profile` ( + `id` bigint(5) AUTO_INCREMENT, + `user_id` bigint(20) NOT NULL, + `first_name` varchar(100) DEFAULT NULL, + `last_name` varchar(100) DEFAULT NULL, + `age` int(3) DEFAULT NULL, + `phone_number` varchar(20) DEFAULT NULL, + `dob` varchar(50) DEFAULT NULL, + `gender` varchar(10) DEFAULT NULL, + `avatar_url` varchar(200) DEFAULT NULL, + `user_profilecol` varchar(45) DEFAULT NULL, + `work_start_date` datetime DEFAULT NULL, + `work_end_date` datetime DEFAULT NULL, + `salary` bigint(20) DEFAULT NULL, + `email_id` varchar(100) DEFAULT NULL, + `country` varchar(200) DEFAULT NULL, + `registration_date` datetime DEFAULT NULL, + `created_date` datetime DEFAULT CURRENT_TIMESTAMP, + `created_by` bigint(20) DEFAULT NULL, + `updated_date` datetime DEFAULT CURRENT_TIMESTAMP, + `updated_by` bigint(20) DEFAULT NULL, + `employment_type` varchar(45) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `fk_user_profile_user_idx` (`user_id`), + KEY `fk_user_profile_created_by_idx` (`created_by`), + KEY `fk_user_profile_updated_by_idx` (`updated_by`), + CONSTRAINT `fk_user_profile_created_by` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fk_user_profile_updated_by` FOREIGN KEY (`updated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fk_user_profile_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=70 DEFAULT CHARSET=latin1; + +CREATE TABLE `user_device` ( + `id` bigint(20) AUTO_INCREMENT, + `user_id` bigint(20) DEFAULT NULL, + `device_token` varchar(200) DEFAULT NULL, + `created_date` bigint(20) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `fk_user_device_user_id_idx` (`user_id`), + CONSTRAINT `fk_user_device_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=latin1; + + +CREATE TABLE `user_authentication` ( + `id` bigint(20) AUTO_INCREMENT, + `user_id` bigint(20) NOT NULL, + `auth_token` text NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3005 DEFAULT CHARSET=latin1; + + +CREATE TABLE org_domain_role( + org_domain varchar(20) NOT NULL, + role_id bigint(20) NOT NULL +); + + + + + diff --git a/src/main/resources/db/migration/ddl/V20191102114728__retail_user_seed.sql b/src/main/resources/db/migration/ddl/V20191102114728__retail_user_seed.sql new file mode 100644 index 0000000000000000000000000000000000000000..d28ce797b0a7afe86b3e382c251cc56d9105a224 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191102114728__retail_user_seed.sql @@ -0,0 +1,13 @@ +INSERT INTO role(id,role_name, code, description, is_super_admin, is_org_admin) +values(2000,'Super Admin', 'SUPER_ADMIN', 'Super Admin Role', true, false), +(2001,'Organization Admin', 'ORG_ADMIN', 'Organization Admin Role', false, true), +(2002,'Country Manager', 'COUNTRY_MANAGER', 'Country Manager Role', false, false), +(2003, 'Sales Area Manager', 'SALESAREA_MANAGER', 'Sales Area Manager Role', false, false), +(2004, 'Store Manager', 'STORE_MANAGER', 'Store Manager Role', false, false); + + +INSERT INTO org_domain_role(org_domain, role_id) +values('RL',2001), +('RL',2002), +('RL',2003), +('RL',2004); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191102115951__alter_actions_table.sql b/src/main/resources/db/migration/ddl/V20191102115951__alter_actions_table.sql new file mode 100644 index 0000000000000000000000000000000000000000..86b4b2f065ac787962ece43928e72dab680297b3 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191102115951__alter_actions_table.sql @@ -0,0 +1,6 @@ +ALTER TABLE actions DROP COLUMN menu_group_code; + +ALTER TABLE actions DROP COLUMN menu_group_name; + + +ALTER TABLE actions DROP COLUMN colour_code; \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191102165844__add_actions_role_details.sql b/src/main/resources/db/migration/ddl/V20191102165844__add_actions_role_details.sql new file mode 100644 index 0000000000000000000000000000000000000000..ce7172cec4d0bd3716d555ce39935a49ca200f2a --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191102165844__add_actions_role_details.sql @@ -0,0 +1,176 @@ + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +values + +(100,'View chart','View Chart','/dashboard/getChart','dashboard',1,147,now(),NULL,NULL), +(101,'View Dashboard Config','View Dashboard Config','/dashboard/getDashboardConfig','dashboard',1,147,now(),NULL,NULL), +(102,'Get Dashboard Header','Get Dashboard Header','/dashboard/getDashboardHeader','dashboard',1,147,now(),NULL,NULL), +(103,'Add organization','Add Organization','/master/addOrganization','master',1,147,now(),NULL,NULL), +(104,'Update Organization','Update orgnization','/master/updateOrganization','master',1,147,now(),NULL,NULL), +(105,'View Organization','View orgnization','/master/getOrganization','master',1,147,now(),NULL,NULL), +(106,'Add or Update Org Config','Organization Configuration','/master/addUpdateOrgConfig','master',1,147,now(),NULL,NULL), +(107,'Get ALL Store','Get All Stores','/master/store/get','master',1,147,now(),NULL,NULL), +(108,'Delete Store','Delete Store','/master/store/deleteStore','master',1,147,now(),NULL,NULL), +(109,'User mapping to store','User to Store','/master/store/storeUser','master',1,147,now(),NULL,NULL), +(110,'Get Domain','Get Org Domain','/master/orgDomain','master',1,147,now(),NULL,NULL), +(111,'Get Area List','Get Area List','/master/salesArea/getSalesAreas','master',1,147,now(),NULL,NULL), +(112,'Get All Stores','Get All Stores','/master/store/getAll','master',1,147,now(),NULL,NULL), +(113,'Create or Update Store','Store Creation or Updation ','/master/store/create','master',1,147,now(),NULL,NULL), +(114,'Get All Space','Get All Space','/master/store/getAllSpace','master',1,147,now(),NULL,NULL), +(115,'Map Sales Area to Country','Map Sales Area to Country','/master/salesArea/mapSalesAreaToCountry','master',1,147,now(),NULL,NULL), +(116,'Sales Area Creation','Sales Area Creation','/master/salesArea/create','master',1,147,now(),NULL,NULL), +(117,'Space Creation','Space Creation','/master/store/createSpace','master',1,147,now(),NULL,NULL), +(118,'Map Stores to Sales Area','Map Stores To Sales Area','/master/salesArea/mapStoresToSalesArea','master',1,147,now(),NULL,NULL), +(119,'Get ALL Sales Area','Get ALL Sales Area','/master/salesArea/getAllSalesAreas','master',1,147,now(),NULL,NULL), +(120,'Delete Sales Area to Country','Delete Sales Area to Country','/master/salesArea/deleteSalesAreaToCountry','master',1,147,now(),NULL,NULL), +(121,'Delete Store and Sales Area Mapping','Delete Store and Sales Area Mapping','/master/salesArea/deleteStoreToSalesArea','master',1,147,now(),NULL,NULL), +(122,'Delete Map Store and Space','Delete Map Store and Space','/master/store/deleteStoreToSpace','master',1,147,now(),NULL,NULL), +(123,'Map Store and Space','Map Store and Space','/master/store/mapStoreToSpace','master',1,147,now(),NULL,NULL), +(124,'GET All Store','Get All Store','/master/store/getAllStore','master',1,147,now(),NULL,NULL), +(125,'Add or Update Pulse','Add or Update Pulse','/master/addOrUpdatePulseConfig','master',1,147,now(),NULL,NULL), +(126,'Get Pulse','Get Pulse','/master/getPulseRatingConfig','master',1,147,now(),NULL,NULL), +(127,'Get All Pulse Config','Get All Pulse Config','/master/getAllPulseRatingConfig','master',1,147,now(),NULL,NULL), +(128,'Map All Pulse Config','Map All Pulse Config','/master/updateConfigToStoreSpace','master',1,147,now(),NULL,NULL), +(129,'Delete Sales Area','Delete sales area','/master/salesArea/deleteSalesArea','master',1,147,now(),NULL,NULL), +(130,'Delete Space','Delete space','/master/store/deleteSpace','master',1,147,now(),NULL,NULL), +(131,'Delete Pulse Config','Delete pulse Config','/master/deletePulseConfig/{id}','master',1,147,now(),NULL,NULL), +(132,'List All Roles','List all roles','/user/roles/{orgId}','user',1,147,now(),NULL,NULL), +(133,'Update Role','Update Role','/user/role/update','user',1,147,now(),NULL,NULL), +(134,'Add User','Add User','/user/createOrUpdate','user',1,147,now(),NULL,NULL), +(135,'Map user country','Map country to User','/user/mapping/country','user',1,147,now(),NULL,NULL), +(136,'Map User Country','Map User Country','/user/country/mapping','user',1,147,now(),NULL,NULL), +(137,'Add country','Add new country','/user/createOrUpdateCountry','user',1,147,now(),NULL,NULL), +(138,'Token Valication','Token Validation','/user/tokenValidate','user',1,147,now(),NULL,NULL), +(139,'Get Country List','Get Country List','/user/getCountryList','user',1,147,now(),NULL,NULL), +(140,'Get Org Country List','Get Org Country List','/user/org/getCountryList','user',1,147,now(),NULL,NULL), +(141,'User Role Mapping','User Role Mapping','/user/role/mapping','user',1,147,now(),NULL,NULL), +(142,'Get All Users','Get All Users','/user/getAllUser','user',1,147,now(),NULL,NULL), +(143,'Get User Detail','Get User Detail','/user/user/{id}','user',1,147,now(),NULL,NULL), +(144,'Delete User-Role Mapping','Delete User-Role Mapping','/user/role/mapping/delete','user',1,147,now(),NULL,NULL), +(145,'Get Org detail','Get Org Detail','/master/org/{id}','user',1,147,now(),NULL,NULL), +(146,'Add Role','Add Role','/user/add/role','user',1,147,now(),NULL,NULL), +(147,'Access Admin Dashboard Url','Access Admin Dashboard Url','/dash','admin',1,147,now(),NULL,NULL); + + + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,100), +(2000,101), +(2000,102), +(2000,103), +(2000,104), +(2000,105), +(2000,106), +(2000,107), +(2000,108), +(2000,109), +(2000,110), +(2000,111), +(2000,112), +(2000,113), +(2000,114), +(2000,115), +(2000,116), +(2000,117), +(2000,118), +(2000,119), +(2000,120), +(2000,121), +(2000,122), +(2000,123), +(2000,124), +(2000,125), +(2000,126), +(2000,127), +(2000,128), +(2000,129), +(2000,130), +(2000,131), +(2000,132), +(2000,133), +(2000,134), +(2000,135), +(2000,136), +(2000,137), +(2000,138), +(2000,139), +(2000,140), +(2000,141), +(2000,142), +(2000,143), +(2000,144), +(2000,145), +(2000,146), +(2000,147); + + +INSERT INTO role_actions(role_id, action_id) +values +(2001,100), +(2001,101), +(2001,102), +(2001,103), +(2001,104), +(2001,105), +(2001,106), +(2001,107), +(2001,108), +(2001,109), +(2001,110), +(2001,111), +(2001,112), +(2001,113), +(2001,114), +(2001,115), +(2001,116), +(2001,117), +(2001,118), +(2001,119), +(2001,120), +(2001,121), +(2001,122), +(2001,123), +(2001,124), +(2001,125), +(2001,126), +(2001,127), +(2001,128), +(2001,129), +(2001,130), +(2001,131), +(2001,132), +(2001,133), +(2001,134), +(2001,135), +(2001,136), +(2001,137), +(2001,138), +(2001,139), +(2001,140), +(2001,141), +(2001,142), +(2001,143), +(2001,144), +(2001,145), +(2001,146), +(2001,147); + +INSERT INTO role_actions(role_id, action_id) +values +(2002,100), +(2002,101), +(2002,102), +(2002,105), +(2003,100), +(2003,101), +(2003,102), +(2003,105), +(2004,100), +(2004,101), +(2004,102), +(2004,105); + + + diff --git a/src/main/resources/db/migration/ddl/V20191102172623__superadmin_user.sql b/src/main/resources/db/migration/ddl/V20191102172623__superadmin_user.sql new file mode 100644 index 0000000000000000000000000000000000000000..f5056895d1ee0e536e95330bdf190c354f309fb7 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191102172623__superadmin_user.sql @@ -0,0 +1,12 @@ + +INSERT INTO user(id,password,username,email_id, phone_no,is_active, is_deleted,org_id) +value(147,'$2a$10$fGCOo1khhaxJWRQJ0EsmbODPtvn.cQq/wX7RZ6GMnjypSBzSPHDw6','satishkumar.nirmalkar@tarento.com', 'satishkumar.nirmalkar@tarento.com', null, true,false,5000); + +INSERT INTO user_role(user_id, role_id, org_id) +value(147,2000,5000); + + INSERT INTO country(id,code,name,currency,phone_code, url,org_id) + value(1,'IND','India','INR','91','https://restcountries.eu/data/ind.svg',5000); + + INSERT INTO country_user(user_id, country_id) + value(147,1); diff --git a/src/main/resources/db/migration/ddl/V20191103144918__default_add_role_org.sql b/src/main/resources/db/migration/ddl/V20191103144918__default_add_role_org.sql new file mode 100644 index 0000000000000000000000000000000000000000..54dd70fb7480519f391705b934749a8ccff43ceb --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191103144918__default_add_role_org.sql @@ -0,0 +1,10 @@ +INSERT INTO role_org(role_id, org_id) +value(2000,5000); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (148,'Get ALL Space By Org','Get ALL Space By Org','/master/store/getAllSpaceByOrg','user',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,148), +(2001,148); diff --git a/src/main/resources/db/migration/ddl/V20191103160532__action_role_update.sql b/src/main/resources/db/migration/ddl/V20191103160532__action_role_update.sql new file mode 100644 index 0000000000000000000000000000000000000000..664a2b589fe555d9b168065c41ccf9f2d637ddaf --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191103160532__action_role_update.sql @@ -0,0 +1,7 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (149,'Get All Role By OrgDomain','Get All Role By OrgDomain','/user/domainRole','user',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,149), +(2001,149); diff --git a/src/main/resources/db/migration/ddl/V20191103185612__add_action_data_map_unmap.sql b/src/main/resources/db/migration/ddl/V20191103185612__add_action_data_map_unmap.sql new file mode 100644 index 0000000000000000000000000000000000000000..8467410334dc20c824324c846cbd4f920d5c997d --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191103185612__add_action_data_map_unmap.sql @@ -0,0 +1,13 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (150,'Get Unmap Action','Get All UnMapped Action','/user/getUnmapActionToRole','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (151,'Get map Action','Get mapped Action','/user/getMapActionToRole','user',1,147,now(),NULL,NULL); + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,150), +(2001,150), +(2000,151), +(2001,151); diff --git a/src/main/resources/db/migration/ddl/V20191103190842__add_map_action_role.sql b/src/main/resources/db/migration/ddl/V20191103190842__add_map_action_role.sql new file mode 100644 index 0000000000000000000000000000000000000000..7dd77aa64d01036d949346e15ba84032cd6c35f8 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191103190842__add_map_action_role.sql @@ -0,0 +1,15 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (152,'Map Action Role','Map Action Role','/user/mapActionToRole','user',1,147,now(),NULL,NULL); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (153,'UnMap Action Role','UnMap Action Role','/user/unmapActionToRole','user',1,147,now(),NULL,NULL); + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,152), +(2001,152), +(2000,152), +(2001,153); + diff --git a/src/main/resources/db/migration/ddl/V20191103232058__add_dashboard_apis.sql b/src/main/resources/db/migration/ddl/V20191103232058__add_dashboard_apis.sql new file mode 100644 index 0000000000000000000000000000000000000000..b2a48c406c8421c6554f072da3b4235339f49ebe --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191103232058__add_dashboard_apis.sql @@ -0,0 +1,25 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (154,'Get Service Api','Get Service Api','/meta/getAllServiceApi','user',1,147,now(),NULL,NULL); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (155,'Get All Charts','Get All Charts','/meta/getAllChart','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (156,'Get All Visualizations','Get All Visualizations','/dashboard/getAllVisualizations','user',1,147,now(),NULL,NULL); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (157,'Get All Dashboards','Get All Dashboards','/dashboard/getAllDashboard','user',1,147,now(),NULL,NULL); + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,154), +(2001,154), +(2000,155), +(2001,155), +(2000,156), +(2001,156), +(2000,157), +(2001,157); diff --git a/src/main/resources/db/migration/ddl/V20191103235241__add_chart.sql b/src/main/resources/db/migration/ddl/V20191103235241__add_chart.sql new file mode 100644 index 0000000000000000000000000000000000000000..42943c3339c8e465dd4a6f07f4455e742ba1bf12 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191103235241__add_chart.sql @@ -0,0 +1,70 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (158,'Add Chart','Add Chart','/meta/addChart','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (159,'Add Visualization','Add Visualization','/dashboard/addNewVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (160,'Add Dashboard','Add Dashboard','/dashboard/addNewDashboard','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (161,'Get Dashboard Detail','Get Dashboard Detail','/dashboard/getDashboardDetail','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (162,'Get Mapped Visualization','Get Mapped Visualization','/dashboard/getMappedVisualization','user',1,147,now(),NULL,NULL); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (163,'Get UnMapped Visualization','Get UnMapped Visualization','/dashboard/getUnmappedVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (164,'Get Role By Dashboard','Get Role By Dashboard','/dashboard/getRoleByDashboard','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (165,'Get Chart By Visualization','Get Chart By Visualization','/dashboard/getChartByVisualization','user',1,147,now(),NULL,NULL); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (166,'Get Visualization','Get Visualization','/dashboard/getVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (167,'Get Unmapped Visualization','Get Unmapped Visualization','/dashboard/getUnmappedChartToVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (168,'Get mapped Visualization','Get Unmapped Visualization','/dashboard/getUnmappedChartToVisualization','user',1,147,now(),NULL,NULL); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (169,'Get Role By Visualization','Get Role By Visualization','/dashboard/getRoleByVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (170,'Get Chart By Visualization','Get Chart By Visualization','/dashboard/getUnmappedChartToVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,158), +(2001,158), +(2000,159), +(2001,159), +(2000,160), +(2001,160), +(2000,161), +(2001,161), +(2000,162), +(2001,162), +(2000,163), +(2001,163), +(2000,164), +(2001,164), +(2000,165), +(2001,165), +(2000,166), +(2001,166), +(2000,167), +(2001,167), +(2000,168), +(2001,168), +(2000,169), +(2001,169), +(2000,170), +(2001,170); diff --git a/src/main/resources/db/migration/ddl/V20191104001205__map_role_to_visualization_dashboard.sql b/src/main/resources/db/migration/ddl/V20191104001205__map_role_to_visualization_dashboard.sql new file mode 100644 index 0000000000000000000000000000000000000000..c59cee159433d021f4ebc53bba129ac5670e539c --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191104001205__map_role_to_visualization_dashboard.sql @@ -0,0 +1,24 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (171,'Map Role to Visualization','Map Role to Visualization','/dashboard/mapRoleToVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (172,'Map Role to Dashboard','Map Role to Dashboard','/dashboard/mapRoleToDashboard','user',1,147,now(),NULL,NULL); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (173,'Update Dashboard','Update Dashboard','/dashboard/updateDashboard','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (174,'Update Visualization','Update Visualization','/dashboard/updateVisualization','user',1,147,now(),NULL,NULL); + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,171), +(2001,171), +(2000,172), +(2001,172), +(2000,173), +(2001,173), +(2000,174), +(2001,174); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191104002145__map_role_to_visualization.sql b/src/main/resources/db/migration/ddl/V20191104002145__map_role_to_visualization.sql new file mode 100644 index 0000000000000000000000000000000000000000..165967f1b636ae5e3c43b25158ca57875f5851b4 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191104002145__map_role_to_visualization.sql @@ -0,0 +1,12 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (175,'Map Visualization - Dashboard','Map Visualization - Dashboard','/dashboard/mapVisualizationToDashboard','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (176,'UnMap Visualization - Dashboard','UnMap Visualization - Dashboard','/dashboard/unmapVisualizationFromDashboard','user',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,175), +(2001,175), +(2000,176), +(2001,176); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191104120101__add_manager_api_actions.sql b/src/main/resources/db/migration/ddl/V20191104120101__add_manager_api_actions.sql new file mode 100644 index 0000000000000000000000000000000000000000..1708865ad1083d2d736c8d7150c3b3068140f080 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191104120101__add_manager_api_actions.sql @@ -0,0 +1,18 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (177,'Add Store Manager','Add Store Manager','/master/store/addStoreManager','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (178,'Add SalesArea Manager','Add SalesArea Manager','/master/salesArea/addSalesAreaManager','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (179,'Add Country Manager','Add Country Manager','/master/addCountryManager','user',1,147,now(),NULL,NULL); + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,177), +(2001,177), +(2000,178), +(2001,178), +(2000,179), +(2001,179); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191104132607__get_master_role_based_user_api.sql b/src/main/resources/db/migration/ddl/V20191104132607__get_master_role_based_user_api.sql new file mode 100644 index 0000000000000000000000000000000000000000..209ca4f14922dec3819e81ea9ba19d97a72e23cf --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191104132607__get_master_role_based_user_api.sql @@ -0,0 +1,9 @@ + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (180,'Get Default Role Based User','Get Default Role Based User','/user/getUsersByMasterRole','user',1,147,now(),NULL,NULL); + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,180), +(2001,180); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191105115049__super_admin_password.sql b/src/main/resources/db/migration/ddl/V20191105115049__super_admin_password.sql new file mode 100644 index 0000000000000000000000000000000000000000..0b15514a0db1e3ec2e67ab60d112e02b130bbe62 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191105115049__super_admin_password.sql @@ -0,0 +1 @@ +UPDATE user SET password='$2a$10$0KZDNm35EYJP7XR0VthjY.HuuTNKoi9SarSsPDwgry2TvU9XwFbXW' WHERE id=147; \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191106005826__map_unmap_visualization.sql b/src/main/resources/db/migration/ddl/V20191106005826__map_unmap_visualization.sql new file mode 100644 index 0000000000000000000000000000000000000000..bb449cd0fc9793ab166b36174d406071b15f7737 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191106005826__map_unmap_visualization.sql @@ -0,0 +1,33 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (181,'Unmap Chart From Visualization','Unmap Chart From Visualization','/dashboard/unmapChartToVisualization','dashboard',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (182,'Map Chart To Visualization','Map Chart To Visualization','/dashboard/mapChartToVisualization','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (183,'Get Chart','Get Chart','/meta/getChart','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (184,'Delete Chart','Delete Chart','/meta/deleteChart','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (185,'Update Chart','Update Chart','/meta/updateChart','user',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (186,'Update Organization','Update Organization','/master/updateOrg','user',1,147,now(),NULL,NULL); + + +INSERT INTO role_actions(role_id, action_id) +values +(2000,181), +(2001,181), +(2000,182), +(2001,182), +(2000,183), +(2001,183), +(2000,184), +(2001,184), +(2000,185), +(2001,185), +(2000,186), +(2001,186); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191106014505__add_new_action_to_get_chart_type_service.sql b/src/main/resources/db/migration/ddl/V20191106014505__add_new_action_to_get_chart_type_service.sql new file mode 100644 index 0000000000000000000000000000000000000000..90385789bc588d3090385db59c8908977bd45b91 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191106014505__add_new_action_to_get_chart_type_service.sql @@ -0,0 +1,8 @@ + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (187,'Get Chart Type By Api','Get Chart By Api','/master/getChartTypeByApi','master',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,187), +(2001,187); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191107154538__add_store_space_pulse_api.sql b/src/main/resources/db/migration/ddl/V20191107154538__add_store_space_pulse_api.sql new file mode 100644 index 0000000000000000000000000000000000000000..905bf590e1ec8e6c1309597a297e2b21931feec9 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191107154538__add_store_space_pulse_api.sql @@ -0,0 +1,13 @@ + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (188,'Update QR Code','Update QR Code','/master/updateQRCode','master',1,147,now(),NULL,NULL); + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (189,'Get All Store Space Mapping','Get All Store Space Mapping','/master/updateQRCode','master',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,188), +(2001,188), +(2000,188), +(2001,189); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191107164323__add_fix_to_action_api.sql b/src/main/resources/db/migration/ddl/V20191107164323__add_fix_to_action_api.sql new file mode 100644 index 0000000000000000000000000000000000000000..e9517db8db43c5530b6e2e58ddc8a4876fc0b6d6 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191107164323__add_fix_to_action_api.sql @@ -0,0 +1 @@ +UPDATE actions SET url='/master/getAllPulseMap' WHERE id =189; \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191107171517__enable_age_group_api.sql b/src/main/resources/db/migration/ddl/V20191107171517__enable_age_group_api.sql new file mode 100644 index 0000000000000000000000000000000000000000..15f383ded325c127d35019bc7cea9b1545ef81f5 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191107171517__enable_age_group_api.sql @@ -0,0 +1,7 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (190,'Enable Or Disable Age Group','Enable Or Disable Age Group','/master/enableAgeGroup','master',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,190), +(2001,190); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191107201905__add_get_all_map.sql b/src/main/resources/db/migration/ddl/V20191107201905__add_get_all_map.sql new file mode 100644 index 0000000000000000000000000000000000000000..d77749cf9e015c7969ee9bba104fe71b87aa7af0 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191107201905__add_get_all_map.sql @@ -0,0 +1,3 @@ +INSERT INTO role_actions(role_id, action_id) +value +(2000,189); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191111112308__add_delete_pulse_store_space_api.sql b/src/main/resources/db/migration/ddl/V20191111112308__add_delete_pulse_store_space_api.sql new file mode 100644 index 0000000000000000000000000000000000000000..9321e77e36ed0bb36e2030e69b4b76c8bb5a4686 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191111112308__add_delete_pulse_store_space_api.sql @@ -0,0 +1,7 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (191,'Delete Pulse Store Space Api','Delete Store Space Config Api','/master/deletePulseConfigToStoreSpace','master',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,191), +(2001,191); \ No newline at end of file diff --git a/src/main/resources/db/migration/ddl/V20191112134859__add_timezone_user.sql b/src/main/resources/db/migration/ddl/V20191112134859__add_timezone_user.sql new file mode 100644 index 0000000000000000000000000000000000000000..f38317e6e9c1bb523ebb4555829c309d578cfc88 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191112134859__add_timezone_user.sql @@ -0,0 +1,2 @@ +ALTER TABLE user ADD COLUMN timezone varchar(100) ; + diff --git a/src/main/resources/db/migration/ddl/V20191113110206__get_update_api_store_space.sql b/src/main/resources/db/migration/ddl/V20191113110206__get_update_api_store_space.sql new file mode 100644 index 0000000000000000000000000000000000000000..a1cdce5b2d57c1c84279b773332c02c648ac69b8 --- /dev/null +++ b/src/main/resources/db/migration/ddl/V20191113110206__get_update_api_store_space.sql @@ -0,0 +1,26 @@ +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (192,'Get Sales Area Api','Get Sales Area Api','/master/salesArea/getSalesAreas','master',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,192), +(2001,192); + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (193,'Update Sales Area Api','Update Sales Area Api','/master/salesArea/update','master',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,193), +(2001,193); + + + +INSERT INTO actions(id,name,display_name, url, service_code, enabled, created_user, created_date, update_user, update_date) +value (194,'Get Store Api','Get Store Api','/master/store/get','master',1,147,now(),NULL,NULL); + +INSERT INTO role_actions(role_id, action_id) +values +(2000,194), +(2001,194); \ No newline at end of file diff --git a/src/main/resources/db/migration/migrate.sh b/src/main/resources/db/migration/migrate.sh new file mode 100644 index 0000000000000000000000000000000000000000..43960b25cdb623199c07f41a38df386b6aa92dc6 --- /dev/null +++ b/src/main/resources/db/migration/migrate.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +flyway -url=$DB_URL -table=$SCHEMA_TABLE -user=$FLYWAY_USER -password=$FLYWAY_PASSWORD -locations=$FLYWAY_LOCATIONS -baselineOnMigrate=true -outOfOrder=true -ignoreMissingMigrations=true migrate \ No newline at end of file diff --git a/src/main/resources/db/migration/migration_file_name_gen.sh b/src/main/resources/db/migration/migration_file_name_gen.sh new file mode 100755 index 0000000000000000000000000000000000000000..807ef79c4a29b9a8fb050948379436bb47b9027e --- /dev/null +++ b/src/main/resources/db/migration/migration_file_name_gen.sh @@ -0,0 +1,20 @@ +#!/bin/sh + + +echo "Please enter your script file name : " +read given_name +file_name=$given_name + +current_time=$(date "+%Y%m%d%H%M%S") + +echo "Current Time : $current_time" + +new_fileName="V""$current_time"__"$file_name" + +echo "New FileName: " "$new_fileName" + +mv $file_name $new_fileName + +echo "$new_fileName created under ${PWD}, copy this file to add your migrations folder" + + diff --git a/src/main/resources/db/test/role_dataset.xml b/src/main/resources/db/test/role_dataset.xml new file mode 100644 index 0000000000000000000000000000000000000000..b3eb10ba101fb1db83319312142a029a5c2f53b7 --- /dev/null +++ b/src/main/resources/db/test/role_dataset.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<dataset> + + + <retail_role id="1" budget="10000" deadline="2015-03-01 00:00:00" priority="H" title="Project 1" manager_ID="1" /> + <retail_role id="3" budget="30000" deadline="2015-05-01 00:00:00" priority="H" title="Project 3" manager_ID="2" /> +</dataset> \ No newline at end of file diff --git a/src/test/java/com/tarento/retail/config/CORSFilterTest.java b/src/test/java/com/tarento/retail/config/CORSFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4f982621f9bab593a51bd8f957df9bac765e90fd --- /dev/null +++ b/src/test/java/com/tarento/retail/config/CORSFilterTest.java @@ -0,0 +1,59 @@ +package com.tarento.retail.config; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.mock.web.MockFilterChain; + +public class CORSFilterTest extends Mockito { + + CORSFilter corsFilter; + ServletRequest req; + ServletResponse res; + FilterChain filterChain; + + @Before + public void init() { + req = mock(HttpServletRequest.class); + res = mock(HttpServletResponse.class); + + } + + @Test + public void doFilterTest() throws IOException, ServletException { + filterChain = mock(MockFilterChain.class); + + corsFilter = new CORSFilter(); + Mockito.doNothing().when(filterChain).doFilter(req, res); + corsFilter.doFilter(req, res, filterChain); + + } + + @Test(expected = ServletException.class) + public void doFilterTestException() throws IOException, ServletException { + filterChain = mock(MockFilterChain.class); + corsFilter = new CORSFilter(); + doThrow(new ServletException()).when(filterChain).doFilter(req, res); + corsFilter.doFilter(req, res, filterChain); + + } + + @Test(expected = IOException.class) + public void doFilterTestIOException() throws IOException, ServletException { + filterChain = mock(MockFilterChain.class); + corsFilter = new CORSFilter(); + doThrow(new IOException()).when(filterChain).doFilter(req, res); + corsFilter.doFilter(req, res, filterChain); + + } + +} diff --git a/src/test/java/com/tarento/retail/config/JwtAuthenticationFilterTest.java b/src/test/java/com/tarento/retail/config/JwtAuthenticationFilterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0603378653562f1d0a1d3808b07ecda4a3948a40 --- /dev/null +++ b/src/test/java/com/tarento/retail/config/JwtAuthenticationFilterTest.java @@ -0,0 +1,176 @@ +package com.tarento.retail.config; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.security.SignatureException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; + +import io.jsonwebtoken.ExpiredJwtException; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({SecurityContextHolder.class}) +public class JwtAuthenticationFilterTest { + + + @Mock + private JwtTokenUtil jwtTokenUtil; + + @Mock + private UserDetailsService userDetailsService; + + @InjectMocks + JwtAuthenticationFilter jwtFilter = new JwtAuthenticationFilter(); + + + ServletRequest req; + ServletResponse res; + FilterChain filterChain; + + @Before + public void init() { + req = mock(HttpServletRequest.class); + res = mock(HttpServletResponse.class); + + } + + @Test + public void doFilterInternal() throws IOException, ServletException{ + + req = Mockito.mock(HttpServletRequest.class); + res = Mockito.mock(HttpServletResponse.class); + filterChain = mock(FilterChain.class); + HttpServletRequest http = (HttpServletRequest)req ; + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + PowerMockito.mockStatic(SecurityContextHolder.class); + // PowerMockito.mock(SecurityContext.class); + SecurityContext context = mock(SecurityContext.class); + Mockito.when(context.getAuthentication()).thenReturn(null); + when(SecurityContextHolder.getContext()).thenReturn(context); + + + UserDetails user = mock(UserDetails.class); + Mockito.when(userDetailsService.loadUserByUsername("tesla")).thenReturn(user); + + Mockito.doNothing().when(filterChain).doFilter(req, res); + //JwtTokenUtil jwtToken = mock(JwtTokenUtil.class); + Mockito.when(jwtTokenUtil.getUsernameFromToken("eiuroeirj")).thenReturn("tesla"); + Mockito.when(jwtTokenUtil.validateToken("eiuroeirj", user)).thenReturn(true); + + jwtFilter.doFilterInternal(http,(HttpServletResponse) res, filterChain); + + } + + @Test + public void doFilterInternalExceptionIllegal() throws IOException, ServletException{ + + req = Mockito.mock(HttpServletRequest.class); + res = Mockito.mock(HttpServletResponse.class); + filterChain = mock(FilterChain.class); + HttpServletRequest http = (HttpServletRequest)req ; + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + PowerMockito.mockStatic(SecurityContextHolder.class); + // PowerMockito.mock(SecurityContext.class); + SecurityContext context = mock(SecurityContext.class); + Mockito.when(context.getAuthentication()).thenReturn(null); + when(SecurityContextHolder.getContext()).thenReturn(context); + + + UserDetails user = mock(UserDetails.class); + Mockito.when(userDetailsService.loadUserByUsername("tesla")).thenReturn(user); + + Mockito.doNothing().when(filterChain).doFilter(req, res); + //JwtTokenUtil jwtToken = mock(JwtTokenUtil.class); + Mockito.doThrow(IllegalArgumentException.class).when(jwtTokenUtil).getUsernameFromToken("eiuroeirj"); + Mockito.when(jwtTokenUtil.validateToken("eiuroeirj", user)).thenReturn(true); + + jwtFilter.doFilterInternal(http,(HttpServletResponse) res, filterChain); + + } + @Test + public void doFilterInternalExpiredJwtException() throws IOException, ServletException{ + + req = Mockito.mock(HttpServletRequest.class); + res = Mockito.mock(HttpServletResponse.class); + filterChain = mock(FilterChain.class); + HttpServletRequest http = (HttpServletRequest)req ; + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + PowerMockito.mockStatic(SecurityContextHolder.class); + // PowerMockito.mock(SecurityContext.class); + SecurityContext context = mock(SecurityContext.class); + Mockito.when(context.getAuthentication()).thenReturn(null); + when(SecurityContextHolder.getContext()).thenReturn(context); + + + UserDetails user = mock(UserDetails.class); + Mockito.when(userDetailsService.loadUserByUsername("tesla")).thenReturn(user); + + Mockito.doNothing().when(filterChain).doFilter(req, res); + //JwtTokenUtil jwtToken = mock(JwtTokenUtil.class); + Mockito.doThrow(ExpiredJwtException.class).when(jwtTokenUtil).getUsernameFromToken("eiuroeirj"); + Mockito.when(jwtTokenUtil.validateToken("eiuroeirj", user)).thenReturn(true); + + jwtFilter.doFilterInternal(http,(HttpServletResponse) res, filterChain); + + } + + @Test(expected = SignatureException.class) + public void doFilterInternalSignatureException() throws IOException, ServletException{ + + req = Mockito.mock(HttpServletRequest.class); + res = Mockito.mock(HttpServletResponse.class); + filterChain = mock(FilterChain.class); + HttpServletRequest http = (HttpServletRequest)req ; + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + Mockito.when(http.getHeader("Authorization")).thenReturn("Bearer eiuroeirj"); + + PowerMockito.mockStatic(SecurityContextHolder.class); + // PowerMockito.mock(SecurityContext.class); + SecurityContext context = mock(SecurityContext.class); + Mockito.when(context.getAuthentication()).thenReturn(null); + when(SecurityContextHolder.getContext()).thenReturn(context); + + + UserDetails user = mock(UserDetails.class); + Mockito.when(userDetailsService.loadUserByUsername("tesla")).thenReturn(user); + + Mockito.doNothing().when(filterChain).doFilter(req, res); + //JwtTokenUtil jwtToken = mock(JwtTokenUtil.class); + Mockito.doThrow(SignatureException.class).when(jwtTokenUtil).getUsernameFromToken("eiuroeirj"); + Mockito.when(jwtTokenUtil.validateToken("eiuroeirj", user)).thenReturn(true); + + jwtFilter.doFilterInternal(http,(HttpServletResponse) res, filterChain); + + } +} diff --git a/src/test/java/com/tarento/retail/config/JwtTokenUtilTest.java b/src/test/java/com/tarento/retail/config/JwtTokenUtilTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5f5533468fbf1bc894d6d3352aaaed039f6bc149 --- /dev/null +++ b/src/test/java/com/tarento/retail/config/JwtTokenUtilTest.java @@ -0,0 +1,42 @@ +package com.tarento.retail.config; + +import static org.mockito.Mockito.mock; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.security.core.userdetails.UserDetails; + +import com.tarento.retail.model.User; + +import junit.framework.Assert; + +public class JwtTokenUtilTest { + + + User user; + + @Before + public void init(){ + user = new User(); + user.setEmailId("test@gmail.com"); + user.setUsername("teslae"); + + } + + @SuppressWarnings("deprecation") + @Test + public void getToken(){ + JwtTokenUtil jwtToken = new JwtTokenUtil(); + String authToken =jwtToken.generateToken(user); + String name = jwtToken.getUsernameFromToken(authToken); + Assert.assertEquals("teslae", name); + UserDetails userDetails = mock(UserDetails.class); + Mockito.when(userDetails.getUsername()).thenReturn("teslae"); + + + Boolean val = jwtToken.validateToken(authToken, userDetails); + Assert.assertTrue(val); + } + +} diff --git a/src/test/java/com/tarento/retail/config/TestConfiguration.java b/src/test/java/com/tarento/retail/config/TestConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..99a3bbb3bda2caa879f06f9c58fa2d304f65fce1 --- /dev/null +++ b/src/test/java/com/tarento/retail/config/TestConfiguration.java @@ -0,0 +1,8 @@ +package com.tarento.retail.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages={"com.tarento.retail.config"}) +public class TestConfiguration{ } \ No newline at end of file