Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions retail-managment-system/rms-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,38 @@



<!-- security Start -->

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- password validation-->
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>1.3.1</version>
</dependency>

<!-- security End -->
</dependencies>

<build>
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,36 +1,93 @@
//package com.rms.config;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//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.web.cors.CorsConfiguration;
//import org.springframework.web.cors.CorsConfigurationSource;
//import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
//
//@Configuration
//@EnableWebSecurity
//public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//
// protected void configure(HttpSecurity http) throws Exception {
// http.cors().configurationSource(corsConfigurationSource()).and().csrf().disable();
// }
//
// @Bean
// public CorsConfigurationSource corsConfigurationSource() {
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// CorsConfiguration config = new CorsConfiguration();
// config.setAllowCredentials(true);
// config.addAllowedOrigin("*");
// config.addAllowedHeader("Authorization");
// config.addAllowedHeader("Content-Type");
// config.addAllowedHeader("x-auth-token");
// config.addAllowedHeader("If-None-Match");
// config.addAllowedHeader("If-Match");
// config.addExposedHeader("ETag");
// config.addAllowedMethod("*");
// source.registerCorsConfiguration("/**", config);
// return source;
// }
//}
package com.rms.config;
import com.rms.security.CustomUserDetailsService;
import com.rms.security.RestAuthenticationEntryPoint;
import com.rms.security.TokenAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.builders.WebSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private final CustomUserDetailsService customUserDetailsService;

private final RestAuthenticationEntryPoint restAuthenticationEntryPoint;




@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public TokenAuthenticationFilter authenticationJwtTokenFilter() {
return new TokenAuthenticationFilter();
}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.cors().configurationSource(corsConfigurationSource()).and().csrf().disable().exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().antMatchers("/auth/**").permitAll();
http.authorizeRequests().antMatchers("/customer/**","/installment/**",
"/investor/**","/employee/**","/profits/**"
,"/role/**","/store/**","/supplier/**",
"/transaction/**","/user/**","/user-role/**").hasRole("ADMIN");
//for swagger
http.authorizeRequests().antMatchers("/v3/api-docs/*", "/v3/api-docs", "/swagger-ui.html", "/swagger-ui/*").permitAll();
http.authorizeRequests().anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}

@Override
public void configure(WebSecurity web) throws Exception {

}


@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration().applyPermitDefaultValues();
corsConfiguration.addAllowedMethod(HttpMethod.PUT);
corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);
corsConfiguration.addAllowedMethod(HttpMethod.PATCH);
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.rms.repository;

import com.rms.domain.security.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
Expand All @@ -10,6 +12,17 @@

@Repository
public interface UserRepository extends JpaRepository<User , Integer> {


@Query(value = "SELECT u FROM User u LEFT JOIN FETCH u.employee WHERE u.id= :id")
Optional<User> findById(@Param("id") Integer id);

@Query("select u from User u where u.userName = :userName")
Optional<User> findByUserName(@Param("userName") String userName);


@Query(value = "Select u.userName FROM User u WHERE u.userName= :username ")
Optional<String> checkUsername(@Param("username") String username);


}
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.rms.repository;

import com.rms.domain.security.Role;
import com.rms.domain.security.UserRole;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
Expand All @@ -16,6 +19,8 @@ public interface UserRoleRepository extends JpaRepository<UserRole , Integer> {
Optional<Integer> findRoleIdByUserIdAndRoleId(@Param("userId") Integer userId, @Param("roleId") Integer roleId);


@Query(value = "SELECT ur.role FROM UserRole ur WHERE ur.user.userName= :username")
List<Role> findByUserName(@Param("username") String username);

@Query(value = "SELECT ur FROM UserRole ur JOIN FETCH ur.role WHERE ur.user.id= :userId",
countQuery = "SELECT COUNT(ur) FROM UserRole ur WHERE ur.user.id= :userId")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package com.rms.rest.handler;

import com.rms.domain.core.Employee;
import com.rms.domain.security.Role;
import com.rms.domain.security.User;
import com.rms.domain.security.UserRole;
import com.rms.rest.dto.UserDto;
import com.rms.rest.dto.common.PaginatedResultDto;
import com.rms.rest.exception.*;
import com.rms.rest.modelmapper.UserMapper;
import com.rms.rest.modelmapper.common.PaginationMapper;
import com.rms.service.EmployeeService;
import com.rms.service.RoleService;
import com.rms.service.UserRoleService;
import com.rms.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
Expand All @@ -26,11 +30,8 @@ public class UserHandler {
private UserMapper mapper ;
private EmployeeService employeeService ;
private PaginationMapper paginationMapper ;





private UserRoleService userRoleService;
private RoleService roleService;

public ResponseEntity<?> getAll (Integer page , Integer size)
{
Expand All @@ -52,21 +53,22 @@ public ResponseEntity<?> getById (Integer id)

public ResponseEntity<?> save(UserDto dto)
{
Optional<User> existedUsername = userService.findUserName(dto.getUserName());
existedUsername.ifPresent(e -> {
throw new ResourceAlreadyExistsException(User.class.getSimpleName(), "User Name " ,
dto.getUserName(), ErrorCodes.DUPLICATE_RESOURCE.getCode());
});
User user =mapper.toEntity(dto);
userService.save(user);
UserDto userDto = mapper.toDto(user);
return ResponseEntity.created(URI.create("/user/" + userDto.getId())).body(userDto);
Optional<String> existedUsername= userService.findUsername(dto.getUserName());
if (existedUsername.isPresent()){
throw new ResourceAlreadyExistsException(User.class.getSimpleName(),
"username", dto.getUserName(), ErrorCodes.DUPLICATE_RESOURCE.getCode());
}

User user = mapper.toEntity(dto);
userService.save(user);
UserDto usersDto=mapper.toDto(user);
return ResponseEntity.created(URI.create("/user/" + usersDto.getId())).body(usersDto);
}
public ResponseEntity<?> update (Integer id , UserDto userDto)
{
User existedUser= userService.getById(id).orElseThrow(
()-> new ResourceNotFoundException(User.class.getSimpleName() , id));
Optional<User> existedUsername = userService.findUserName(userDto.getUserName());
Optional<User> existedUsername = userService.getByUserName(userDto.getUserName());

if (existedUsername.isPresent() && !existedUsername.get().getId().equals(id)) {
throw new ResourceAlreadyExistsException(User.class.getSimpleName(), "Username", userDto.getUserName(), ErrorCodes.DUPLICATE_RESOURCE.getCode());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.rms.security;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/auth")
@AllArgsConstructor
@Tag(name = "Authentication", description = "REST API for Authentication")
@Log4j2
public class AuthController {

private AuthHandler authHandler;

@PostMapping(value = "/login")
public ResponseEntity<?> login(@Valid @RequestBody LoginRequestDto loginRequest) {
//TODO:add encryption/decryption
return authHandler.login(loginRequest);
}


@PostMapping(value = "/refresh")
public ResponseEntity<?> refreshToken(@RequestBody RefreshTokenRequestDto refreshToken) {
return authHandler.refresh(refreshToken);
}

@GetMapping(value = "/user-info")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<?> getUserInfo(@AuthenticationPrincipal UserDetails userDetails) {
return authHandler.getUserInfo(userDetails);
}
}
Loading