├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── src ├── main │ ├── java │ │ └── com │ │ │ └── gucardev │ │ │ └── jwtproject │ │ │ ├── model │ │ │ ├── ROLES.java │ │ │ ├── qrLogin │ │ │ │ ├── LoginQRCodeType.java │ │ │ │ └── LoginQRCode.java │ │ │ ├── Role.java │ │ │ ├── RefreshToken.java │ │ │ └── User.java │ │ │ ├── request │ │ │ ├── RoleRequest.java │ │ │ ├── RoleGrantRevokeRequest.java │ │ │ ├── LoginRequest.java │ │ │ ├── RefreshTokenRequest.java │ │ │ ├── CreateUserRequest.java │ │ │ └── UpdateUserRequest.java │ │ │ ├── dto │ │ │ ├── RefreshTokenDto.java │ │ │ ├── RoleDto.java │ │ │ └── UserDto.java │ │ │ ├── repository │ │ │ ├── RoleRepository.java │ │ │ ├── UserRepository.java │ │ │ ├── LoginQRCodeRepository.java │ │ │ └── RefreshTokenRepository.java │ │ │ ├── config │ │ │ ├── BeanConfig.java │ │ │ ├── WebConfig.java │ │ │ ├── WebSocketConfig.java │ │ │ ├── RedisConfig.java │ │ │ ├── filter │ │ │ │ ├── CustomAuthorizationFilter.java │ │ │ │ └── CustomAuthenticationFilter.java │ │ │ └── SecurityConfig.java │ │ │ ├── exception │ │ │ ├── GeneralException.java │ │ │ ├── CustomAccessDeniedHandler.java │ │ │ ├── CustomAuthenticationExceptionHandler.java │ │ │ └── GeneralExceptionHandler.java │ │ │ ├── controller │ │ │ ├── TestController.java │ │ │ ├── RoleController.java │ │ │ ├── LoginSocketController.java │ │ │ ├── AuthController.java │ │ │ └── UserController.java │ │ │ ├── service │ │ │ ├── RoleService.java │ │ │ ├── LoginRequestService.java │ │ │ ├── AuthService.java │ │ │ └── UserService.java │ │ │ ├── JwtProjectApplication.java │ │ │ └── util │ │ │ └── JwtHelper.java │ └── resources │ │ └── application.yml └── test │ └── java │ └── com │ └── gucardev │ └── jwtproject │ └── JwtProjectApplicationTests.java ├── Dockerfile ├── docker-compose.yml ├── .gitignore ├── README.md ├── pom.xml ├── mvnw.cmd ├── mvnw └── jwt-auth-project.postman_collection.json /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gurkanucar/jwt-project/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/model/ROLES.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.model; 2 | 3 | public enum ROLES { 4 | SUPERADMIN, ADMIN, USER 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/model/qrLogin/LoginQRCodeType.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.model.qrLogin; 2 | 3 | public enum LoginQRCodeType { 4 | SERVER, CLIENT, MOBILE, ERROR 5 | } 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:11 2 | ARG JAR_FILE=target/jwt-project-0.0.1-SNAPSHOT.jar 3 | ADD ${JAR_FILE} jwt-project-0.0.1-SNAPSHOT.jar 4 | EXPOSE 8080 5 | ENTRYPOINT ["java", "-jar" , "jwt-project-0.0.1-SNAPSHOT.jar"] -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /src/test/java/com/gucardev/jwtproject/JwtProjectApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class JwtProjectApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | 4 | services: 5 | redisdb: 6 | image: "redis" 7 | ports: 8 | - "6379:6379" 9 | environment: 10 | - ALLOW_EMPTY_PASSWORD=yes 11 | app: 12 | build: . 13 | ports: 14 | - "8080:8080" 15 | environment: 16 | SPRING_REDIS_HOST: redisdb 17 | depends_on: 18 | - redisdb 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/request/RoleRequest.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | @NoArgsConstructor 11 | @Builder 12 | public class RoleRequest { 13 | 14 | private String name; 15 | private String detail; 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/dto/RefreshTokenDto.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | @Builder 11 | @Data 12 | public class RefreshTokenDto { 13 | 14 | private String accessToken; 15 | private String refreshToken; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/dto/RoleDto.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | @Builder 11 | @Data 12 | public class RoleDto { 13 | 14 | private Long id; 15 | private String name; 16 | private String detail; 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/request/RoleGrantRevokeRequest.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | @NoArgsConstructor 11 | @Builder 12 | public class RoleGrantRevokeRequest { 13 | 14 | private String username; 15 | private String role; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/request/LoginRequest.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @AllArgsConstructor 9 | @NoArgsConstructor 10 | @Builder 11 | @Data 12 | public class LoginRequest { 13 | 14 | private String username; 15 | private String email; 16 | private String password; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.repository; 2 | 3 | import com.gucardev.jwtproject.model.Role; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.Optional; 8 | 9 | @Repository 10 | public interface RoleRepository extends JpaRepository { 11 | 12 | Optional findRoleByName(String name); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.repository; 2 | 3 | import com.gucardev.jwtproject.model.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.Optional; 8 | 9 | @Repository 10 | public interface UserRepository extends JpaRepository { 11 | 12 | Optional findUserByUsername(String username); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | jwt-variables: 2 | KEY: jwtProject 3 | ISSUER: gucardev 4 | EXPIRES_ACCESS_TOKEN_MINUTE: 15 5 | EXPIRES_REFRESH_TOKEN_MINUTE: 150000 6 | 7 | 8 | spring: 9 | datasource: 10 | url: jdbc:h2:mem:database 11 | driver-class-name: org.h2.Driver 12 | 13 | h2: 14 | console: 15 | enabled: true 16 | jpa: 17 | hibernate: 18 | ddl-auto: create 19 | 20 | redis: 21 | host: ${SPRING_REDIS_HOST} 22 | port: 6379 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/dto/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.dto; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | import java.util.List; 10 | 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | @Builder 14 | @Data 15 | public class UserDto { 16 | 17 | private Long id; 18 | private String username; 19 | private String email; 20 | private List roles; 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/repository/LoginQRCodeRepository.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.repository; 2 | 3 | import com.gucardev.jwtproject.model.qrLogin.LoginQRCode; 4 | import org.springframework.data.repository.CrudRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.Optional; 8 | 9 | @Repository 10 | public interface LoginQRCodeRepository extends CrudRepository { 11 | 12 | Optional findLoginQRCodeByRoom(String room); 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/request/RefreshTokenRequest.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.validation.constraints.NotBlank; 9 | import javax.validation.constraints.NotNull; 10 | 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | @Builder 14 | @Data 15 | public class RefreshTokenRequest { 16 | 17 | @NotNull 18 | @NotBlank 19 | private String token; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/config/BeanConfig.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.config; 2 | 3 | import org.modelmapper.ModelMapper; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 7 | 8 | 9 | @Configuration 10 | public class BeanConfig { 11 | 12 | @Bean 13 | public BCryptPasswordEncoder passwordEncoder() { 14 | return new BCryptPasswordEncoder(); 15 | } 16 | 17 | @Bean 18 | public ModelMapper modelMapper() { 19 | return new ModelMapper(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | @Configuration 8 | public class WebConfig implements WebMvcConfigurer { 9 | 10 | @Override 11 | public void addCorsMappings(CorsRegistry registry) { 12 | registry.addMapping("/**") 13 | .allowedOrigins("*") 14 | .allowedMethods("HEAD","GET","POST","PUT","DELETE","PATCH","OPTIONS"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/repository/RefreshTokenRepository.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.repository; 2 | 3 | import com.gucardev.jwtproject.model.RefreshToken; 4 | import com.gucardev.jwtproject.model.User; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import java.util.Optional; 9 | 10 | @Repository 11 | public interface RefreshTokenRepository extends JpaRepository { 12 | 13 | Optional findByToken(String token); 14 | Optional findByUser(User user); 15 | 16 | void deleteRefreshTokenByUser(User user); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/request/CreateUserRequest.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.validation.constraints.Email; 9 | import javax.validation.constraints.NotNull; 10 | import javax.validation.constraints.Size; 11 | 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | @Builder 15 | @Data 16 | public class CreateUserRequest { 17 | 18 | @NotNull 19 | @Size(max = 50, min = 3) 20 | private String username; 21 | 22 | @NotNull 23 | @Email 24 | private String email; 25 | 26 | 27 | @NotNull 28 | @Size(max = 50, min = 8) 29 | private String password; 30 | 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.persistence.*; 9 | import java.io.Serializable; 10 | 11 | 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | @Builder 15 | @Data 16 | @Entity 17 | public class Role implements Serializable { 18 | 19 | private static final long serialVersionUID = 1L; 20 | 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private Long id; 24 | 25 | 26 | @Column(unique = true, nullable = false, length = 24) 27 | private String name; 28 | 29 | 30 | @Column(nullable = false, length = 24) 31 | private String detail; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/exception/GeneralException.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.exception; 2 | 3 | import lombok.Data; 4 | import org.springframework.http.HttpStatus; 5 | 6 | import java.time.LocalDate; 7 | 8 | 9 | @Data 10 | public class GeneralException extends RuntimeException { 11 | 12 | private final String message; 13 | private final HttpStatus status; 14 | private final LocalDate time; 15 | 16 | public GeneralException(String message, HttpStatus status) { 17 | this.message = message; 18 | this.status = status; 19 | this.time = LocalDate.now(); 20 | } 21 | 22 | public GeneralException(String message, int status) { 23 | this.message = message; 24 | this.status = HttpStatus.valueOf(status); 25 | this.time = LocalDate.now(); 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.controller; 2 | 3 | import org.springframework.http.ResponseEntity; 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | @RequestMapping("/test") 11 | public class TestController { 12 | 13 | @GetMapping 14 | public ResponseEntity hello() { 15 | return ResponseEntity.ok("Hello!"); 16 | } 17 | 18 | @PreAuthorize("hasAnyAuthority('SUPERADMIN') || hasAnyAuthority('ADMIN')") 19 | @GetMapping("/admin") 20 | public ResponseEntity admin() { 21 | return ResponseEntity.ok("Only admin can see this!"); 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/exception/CustomAccessDeniedHandler.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.exception; 2 | 3 | import org.springframework.security.access.AccessDeniedException; 4 | import org.springframework.security.web.access.AccessDeniedHandler; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | import java.io.IOException; 9 | 10 | public class CustomAccessDeniedHandler implements AccessDeniedHandler { 11 | 12 | 13 | @Override 14 | public void handle(HttpServletRequest request, HttpServletResponse response, 15 | AccessDeniedException accessDeniedException) throws IOException { 16 | 17 | response.setContentType("application/json"); 18 | response.setStatus(HttpServletResponse.SC_FORBIDDEN); 19 | response.getOutputStream().println("{ \"error\": \"" + accessDeniedException.getMessage() + "\" }"); 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/request/UpdateUserRequest.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.validation.constraints.Email; 9 | import javax.validation.constraints.NotBlank; 10 | import javax.validation.constraints.NotNull; 11 | import javax.validation.constraints.Size; 12 | 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | @Builder 16 | @Data 17 | public class UpdateUserRequest { 18 | 19 | @NotNull 20 | @Size(max = 50, min = 3) 21 | private String username; 22 | 23 | @NotNull 24 | @Email 25 | private String email; 26 | 27 | 28 | @NotNull 29 | @NotBlank 30 | private String name; 31 | 32 | @NotNull 33 | @NotBlank 34 | private String surname; 35 | 36 | @NotNull 37 | @Size(max = 50, min = 8) 38 | private String password; 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/model/qrLogin/LoginQRCode.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.model.qrLogin; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import org.springframework.data.redis.core.RedisHash; 9 | 10 | import javax.persistence.*; 11 | import javax.validation.constraints.NotEmpty; 12 | import javax.validation.constraints.NotNull; 13 | import java.io.Serializable; 14 | 15 | @Data 16 | @Builder 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | @RedisHash("LoginQRCode") 20 | public class LoginQRCode implements Serializable { 21 | 22 | @Id 23 | @GeneratedValue(strategy = GenerationType.IDENTITY) 24 | private Long id; 25 | 26 | @Column(unique = true) 27 | @NotNull 28 | @NotEmpty 29 | private String room; 30 | 31 | @NotNull 32 | @NotEmpty 33 | private String code; 34 | 35 | @Transient 36 | @Enumerated(EnumType.STRING) 37 | private LoginQRCodeType type; 38 | 39 | @Transient 40 | private String message; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/exception/CustomAuthenticationExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.exception; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.AuthenticationEntryPoint; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.ServletException; 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | 12 | @Component("restAuthenticationEntryPoint") 13 | public class CustomAuthenticationExceptionHandler implements AuthenticationEntryPoint { 14 | @Override 15 | public void commence(HttpServletRequest request, HttpServletResponse response, 16 | AuthenticationException authException) throws IOException, ServletException { 17 | response.setContentType("application/json"); 18 | response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 19 | response.getOutputStream().println("{ \"error\": \"" + authException.getMessage() + "\" }"); 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/config/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.config; 2 | 3 | 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 6 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 7 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 8 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; 9 | 10 | @Configuration 11 | @EnableWebSocketMessageBroker 12 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 13 | 14 | @Override 15 | public void registerStompEndpoints(StompEndpointRegistry registry) { 16 | registry.addEndpoint("/loginListener") 17 | .setAllowedOriginPatterns("*").withSockJS(); 18 | } 19 | 20 | @Override 21 | public void configureMessageBroker(MessageBrokerRegistry registry) { 22 | registry.setApplicationDestinationPrefixes("/app") 23 | .enableSimpleBroker("/topic"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/model/RefreshToken.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.model; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | import javax.persistence.*; 10 | import javax.validation.constraints.NotEmpty; 11 | import javax.validation.constraints.Size; 12 | import java.time.LocalDate; 13 | import java.time.LocalDateTime; 14 | 15 | @Entity 16 | @Data 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | @Builder 20 | @Table(name = "refresh_token") 21 | public class RefreshToken { 22 | 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private Long id; 27 | 28 | 29 | @ManyToOne//(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) 30 | private User user; 31 | 32 | 33 | @NotEmpty 34 | @Size(min = 32,max = 32) 35 | @Column(name = "token", nullable = false, unique = true, length = 32) 36 | private String token; 37 | 38 | 39 | @Column(name = "expiry_date", nullable = false) 40 | private LocalDateTime expiryDate; 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/service/RoleService.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.service; 2 | 3 | import com.gucardev.jwtproject.exception.GeneralException; 4 | import com.gucardev.jwtproject.model.Role; 5 | import com.gucardev.jwtproject.model.User; 6 | import com.gucardev.jwtproject.repository.RoleRepository; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.util.List; 11 | 12 | @Service 13 | public class RoleService { 14 | 15 | private final RoleRepository roleRepository; 16 | 17 | 18 | public RoleService(RoleRepository roleRepository) { 19 | this.roleRepository = roleRepository; 20 | 21 | } 22 | 23 | public List getRoles() { 24 | return roleRepository.findAll(); 25 | } 26 | 27 | 28 | public Role getRoleByName(String name) { 29 | return roleRepository.findRoleByName(name) 30 | .orElseThrow(() -> new GeneralException("Role not found!", HttpStatus.NOT_FOUND)); 31 | } 32 | 33 | 34 | public Role saveRole(Role role) { 35 | return roleRepository.save(role); 36 | } 37 | 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.redis.connection.RedisStandaloneConfiguration; 7 | import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 8 | import org.springframework.data.redis.core.RedisTemplate; 9 | import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; 10 | 11 | @Configuration 12 | @EnableRedisRepositories 13 | public class RedisConfig { 14 | 15 | 16 | @Value("${spring.redis.host}") 17 | private String redisHost; 18 | 19 | @Value("${spring.redis.port}") 20 | private int redisPort; 21 | 22 | @Bean 23 | public LettuceConnectionFactory redisStandAloneConnectionFactory() { 24 | return new LettuceConnectionFactory(new RedisStandaloneConfiguration(redisHost, redisPort)); 25 | } 26 | 27 | @Bean 28 | public RedisTemplate redisTemplate() { 29 | RedisTemplate template = new RedisTemplate<>(); 30 | template.setConnectionFactory(redisStandAloneConnectionFactory()); 31 | return template; 32 | } 33 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # QR Code Login - Backend Spring Boot 2 | 3 | #### Gurkan UCAR 4 | 5 |   6 | 7 | 8 | 9 | ### Used Packages 10 | 11 | **Stomp Socket:** socket server 12 | 13 | **Redis**: storing socket rooms and qr code values 14 | 15 | **Security:** user authorization and authentication operations 16 | 17 |   18 | 19 | ### How to run 20 | 21 | #### clone the project: https://github.com/gurkanucar/jwt-project 22 | 23 | ```bash 24 | git clone https://github.com/gurkanucar/jwt-project 25 | ``` 26 | 27 | #### create jar 28 | 29 | ```bash 30 | mvn clean install -DskipTests 31 | ``` 32 | 33 | #### build docker-compose 34 | 35 | ```bash 36 | docker-compose build --no-cache 37 | ``` 38 | 39 | #### run docker-compose 40 | 41 | ```bash 42 | docker-compose up --force-recreate 43 | ``` 44 | 45 | #### Postman Collection: 46 | 47 | [https://github.com/gurkanucar/jwt-project/blob/master/jwt-auth-project.postman_collection.json](https://github.com/gurkanucar/jwt-project/blob/master/jwt-auth-project.postman_collection.json) 48 | 49 | 50 | ### Example Video: 51 | 52 | [https://www.youtube.com/watch?v=i5btOYd0Exw](https://www.youtube.com/watch?v=i5btOYd0Exw) 53 | 54 | ### Other components: 55 | 56 | #### [frontend](https://github.com/gurkanucar/qr-login-fe) 57 | #### [mobile](https://github.com/gurkanucar/qr-login-mobile) 58 | #### [backend](https://github.com/gurkanucar/jwt-project) 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/controller/RoleController.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.controller; 2 | 3 | 4 | import com.gucardev.jwtproject.dto.RoleDto; 5 | import com.gucardev.jwtproject.model.Role; 6 | import com.gucardev.jwtproject.request.RoleGrantRevokeRequest; 7 | import com.gucardev.jwtproject.request.RoleRequest; 8 | import com.gucardev.jwtproject.service.RoleService; 9 | import org.modelmapper.ModelMapper; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import javax.validation.Valid; 14 | 15 | @RestController 16 | @RequestMapping("/role") 17 | public class RoleController { 18 | 19 | private final RoleService roleService; 20 | private final ModelMapper mapper; 21 | 22 | public RoleController(RoleService roleService, 23 | ModelMapper mapper) { 24 | this.roleService = roleService; 25 | this.mapper = mapper; 26 | } 27 | 28 | @PostMapping 29 | public ResponseEntity saveRole(@Valid @RequestBody RoleRequest roleRequest) { 30 | var role = mapper.map(roleRequest, Role.class); 31 | return ResponseEntity.status(201).body(roleService.saveRole(role)); 32 | } 33 | 34 | 35 | @GetMapping("/all") 36 | public ResponseEntity getRoles() { 37 | var list = roleService.getRoles() 38 | .stream().map(x -> mapper.map(x, RoleDto.class)); 39 | return ResponseEntity.ok(list); 40 | } 41 | 42 | 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/controller/LoginSocketController.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.controller; 2 | 3 | import com.gucardev.jwtproject.model.qrLogin.LoginQRCode; 4 | import com.gucardev.jwtproject.service.LoginRequestService; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.messaging.handler.annotation.DestinationVariable; 7 | import org.springframework.messaging.handler.annotation.Header; 8 | import org.springframework.messaging.handler.annotation.MessageMapping; 9 | import org.springframework.messaging.handler.annotation.Payload; 10 | import org.springframework.messaging.simp.SimpMessagingTemplate; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @Slf4j 15 | public class LoginSocketController { 16 | 17 | private final SimpMessagingTemplate messagingTemplate; 18 | private final LoginRequestService service; 19 | 20 | 21 | public LoginSocketController(SimpMessagingTemplate messagingTemplate, 22 | LoginRequestService service) { 23 | this.messagingTemplate = messagingTemplate; 24 | this.service = service; 25 | } 26 | 27 | @MessageMapping("/login/{room}") 28 | public void messageHandler(@DestinationVariable String room, 29 | @Payload LoginQRCode loginQRCode, 30 | @Header("simpSessionId") String sessionId) { 31 | log.info(String.format("Room: %s, model: %s ", room, loginQRCode.toString())); 32 | service.processMessage(room, loginQRCode, sessionId); 33 | //messagingTemplate.convertAndSend("/topic/fileStatus/" + id, msg); 34 | 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/model/User.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import org.hibernate.annotations.CreationTimestamp; 9 | import org.springframework.data.annotation.CreatedDate; 10 | 11 | import javax.persistence.*; 12 | import javax.validation.constraints.Email; 13 | import javax.validation.constraints.NotEmpty; 14 | import javax.validation.constraints.Size; 15 | import java.io.Serializable; 16 | import java.time.LocalDate; 17 | import java.util.ArrayList; 18 | import java.util.Collection; 19 | import java.util.List; 20 | 21 | import static javax.persistence.CascadeType.*; 22 | 23 | @NoArgsConstructor 24 | @AllArgsConstructor 25 | @Builder 26 | @Data 27 | @Entity 28 | public class User implements Serializable { 29 | 30 | private static final long serialVersionUID = 1L; 31 | 32 | @Id 33 | @GeneratedValue(strategy = GenerationType.IDENTITY) 34 | private Long id; 35 | 36 | @Column(unique = true) 37 | @Size(max = 50, min = 3) 38 | private String username; 39 | 40 | @NotEmpty 41 | @Size(max = 255) 42 | @Email 43 | private String email; 44 | 45 | @Size(max = 50, min = 3) 46 | private String name; 47 | 48 | @Size(max = 50, min = 3) 49 | private String surname; 50 | 51 | @NotEmpty 52 | @Column(length = 60) 53 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 54 | private String password; 55 | 56 | @CreatedDate 57 | @CreationTimestamp 58 | private LocalDate createdDate; 59 | 60 | @ManyToMany(fetch = FetchType.EAGER, cascade = MERGE) 61 | private List roles = new ArrayList<>(); 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.controller; 2 | 3 | import com.gucardev.jwtproject.dto.UserDto; 4 | import com.gucardev.jwtproject.request.CreateUserRequest; 5 | import com.gucardev.jwtproject.request.LoginRequest; 6 | import com.gucardev.jwtproject.request.RefreshTokenRequest; 7 | import com.gucardev.jwtproject.service.AuthService; 8 | import org.modelmapper.ModelMapper; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import javax.validation.Valid; 16 | 17 | @RestController 18 | @RequestMapping("/auth") 19 | public class AuthController { 20 | 21 | private final AuthService authService; 22 | private final ModelMapper mapper; 23 | 24 | 25 | public AuthController(AuthService authService, 26 | ModelMapper mapper) { 27 | this.authService = authService; 28 | this.mapper = mapper; 29 | } 30 | 31 | 32 | @PostMapping("/register") 33 | public ResponseEntity register(@Valid @RequestBody CreateUserRequest createUserRequest) { 34 | return ResponseEntity.ok().body(authService.registerUser(createUserRequest)); 35 | } 36 | 37 | @PostMapping("/login") 38 | public ResponseEntity login(@Valid @RequestBody LoginRequest loginRequest) { 39 | return ResponseEntity.ok().body(authService.login(loginRequest)); 40 | } 41 | 42 | @PostMapping("/logout") 43 | public ResponseEntity logout() { 44 | authService.logout(); 45 | return ResponseEntity.ok().build(); 46 | } 47 | 48 | 49 | @PostMapping("/refresh") 50 | public ResponseEntity refreshToken(@Valid @RequestBody RefreshTokenRequest refreshTokenRequest) { 51 | return ResponseEntity.ok().body(authService.refreshTokens(refreshTokenRequest.getToken())); 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/exception/GeneralExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.exception; 2 | 3 | 4 | import org.springframework.http.HttpHeaders; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.validation.FieldError; 8 | import org.springframework.web.bind.MethodArgumentNotValidException; 9 | import org.springframework.web.bind.annotation.ControllerAdvice; 10 | import org.springframework.web.bind.annotation.ExceptionHandler; 11 | import org.springframework.web.bind.annotation.RestControllerAdvice; 12 | import org.springframework.web.context.request.WebRequest; 13 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 14 | 15 | import javax.validation.constraints.NotNull; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | 20 | @RestControllerAdvice 21 | public class GeneralExceptionHandler extends ResponseEntityExceptionHandler { 22 | 23 | 24 | @Override 25 | protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, 26 | HttpHeaders headers, 27 | HttpStatus status, 28 | WebRequest request) { 29 | 30 | Map errors = new HashMap<>(); 31 | ex.getBindingResult().getAllErrors() 32 | .forEach(x -> { 33 | String fieldName = ((FieldError) x).getField(); 34 | String errorMessage = x.getDefaultMessage(); 35 | errors.put(fieldName, errorMessage); 36 | }); 37 | 38 | return ResponseEntity.badRequest().body(errors); 39 | } 40 | 41 | @ExceptionHandler(GeneralException.class) 42 | public ResponseEntity shortUrlNotFoundException(GeneralException e) { 43 | Map errors = new HashMap<>(); 44 | errors.put("error", e.getMessage()); 45 | return ResponseEntity.status(e.getStatus()).body(errors); 46 | } 47 | 48 | 49 | } -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/JwtProjectApplication.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject; 2 | 3 | import com.gucardev.jwtproject.model.ROLES; 4 | import com.gucardev.jwtproject.model.Role; 5 | import com.gucardev.jwtproject.model.User; 6 | import com.gucardev.jwtproject.service.RoleService; 7 | import com.gucardev.jwtproject.service.UserService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.CommandLineRunner; 10 | import org.springframework.boot.SpringApplication; 11 | import org.springframework.boot.autoconfigure.SpringBootApplication; 12 | 13 | import java.util.List; 14 | 15 | @SpringBootApplication 16 | public class JwtProjectApplication implements CommandLineRunner { 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(JwtProjectApplication.class, args); 20 | } 21 | 22 | 23 | @Autowired 24 | RoleService roleService; 25 | 26 | @Autowired 27 | UserService userService; 28 | 29 | @Override 30 | public void run(String... args) throws Exception { 31 | 32 | roleService.saveRole(Role.builder().name("USER").detail("simple operations").build()); 33 | roleService.saveRole(Role.builder().name("ADMIN").detail("admin operations").build()); 34 | roleService.saveRole(Role.builder().name("SUPERADMIN").detail("super operations").build()); 35 | User superadmin = userService.saveUser(User.builder().username("gurkan").email("g@mail.com").password("password").build()); 36 | userService.saveUser(User.builder().username("metin").email("m@mail.com").password("password").build()); 37 | userService.saveUser(User.builder().username("ali").email("a@mail.com").password("password").build()); 38 | userService.saveUser(User.builder().username("kartal").email("k@mail.com").password("password").build()); 39 | User admin = userService.saveUser(User.builder().username("sezai").email("s@mail.com").password("password").build()); 40 | 41 | 42 | var superAdminRole = roleService.getRoleByName(ROLES.SUPERADMIN.toString()); 43 | superadmin.setRoles(List.of(superAdminRole)); 44 | userService.updateUser(superadmin); 45 | 46 | var adminRole = roleService.getRoleByName(ROLES.ADMIN.toString()); 47 | admin.setRoles(List.of(adminRole)); 48 | userService.updateUser(admin); 49 | 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/config/filter/CustomAuthorizationFilter.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.config.filter; 2 | 3 | import com.gucardev.jwtproject.exception.GeneralException; 4 | import com.gucardev.jwtproject.service.AuthService; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.web.filter.OncePerRequestFilter; 9 | 10 | import javax.servlet.FilterChain; 11 | import javax.servlet.ServletException; 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | import java.io.IOException; 15 | 16 | import static org.springframework.http.HttpHeaders.AUTHORIZATION; 17 | 18 | public class CustomAuthorizationFilter extends OncePerRequestFilter { 19 | 20 | private final AuthService authService; 21 | 22 | public CustomAuthorizationFilter(AuthService authService) { 23 | this.authService = authService; 24 | } 25 | 26 | 27 | @Override 28 | protected void doFilterInternal(HttpServletRequest request, 29 | HttpServletResponse response, 30 | FilterChain filterChain) 31 | throws ServletException, IOException { 32 | 33 | 34 | // if (request.getServletPath().equals("/login")) 35 | // filterChain.doFilter(request, response); 36 | // 37 | // else { 38 | String authHeader = request.getHeader(AUTHORIZATION); 39 | 40 | if (authHeader != null && authHeader.startsWith("Bearer ")) { 41 | 42 | String token = authHeader.substring(7); 43 | 44 | try { 45 | UsernamePasswordAuthenticationToken authToken; 46 | authToken = authService.getAuthToken(token); 47 | SecurityContextHolder.getContext().setAuthentication(authToken); 48 | filterChain.doFilter(request, response); 49 | } catch (Exception e) { 50 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication."); 51 | //throw new GeneralException("Try to login again!", HttpStatus.UNAUTHORIZED); 52 | } 53 | 54 | } else { 55 | filterChain.doFilter(request, response); 56 | } 57 | 58 | //} 59 | 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/config/filter/CustomAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.config.filter; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.gucardev.jwtproject.exception.GeneralException; 5 | import com.gucardev.jwtproject.service.AuthService; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.security.authentication.AuthenticationServiceException; 8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.core.AuthenticationException; 11 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 12 | 13 | import javax.servlet.FilterChain; 14 | import javax.servlet.ServletException; 15 | import javax.servlet.http.HttpServletRequest; 16 | import javax.servlet.http.HttpServletResponse; 17 | import java.io.IOException; 18 | import java.util.Map; 19 | 20 | import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; 21 | 22 | @Slf4j 23 | public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter { 24 | 25 | 26 | private final AuthService authService; 27 | 28 | public CustomAuthenticationFilter(AuthService authService) { 29 | this.authService = authService; 30 | } 31 | 32 | 33 | @Override 34 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 35 | throws AuthenticationException { 36 | 37 | String username, password; 38 | 39 | try { 40 | Map requestMap = new ObjectMapper().readValue(request.getInputStream(), Map.class); 41 | username = requestMap.get("username"); 42 | password = requestMap.get("password"); 43 | } catch (IOException e) { 44 | throw new AuthenticationServiceException(e.getMessage(), e); 45 | } 46 | 47 | UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( 48 | username, password); 49 | 50 | return this.getAuthenticationManager().authenticate(authRequest); 51 | } 52 | 53 | 54 | @Override 55 | protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, 56 | Authentication authResult) throws IOException { 57 | 58 | Map tokens = authService.createTokens(authResult.getName()); 59 | 60 | response.setContentType(APPLICATION_JSON_VALUE); 61 | 62 | new ObjectMapper().writeValue(response.getOutputStream(), tokens); 63 | 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/util/JwtHelper.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.util; 2 | 3 | 4 | import com.auth0.jwt.JWT; 5 | import com.auth0.jwt.JWTVerifier; 6 | import com.auth0.jwt.algorithms.Algorithm; 7 | import com.auth0.jwt.interfaces.DecodedJWT; 8 | import com.gucardev.jwtproject.exception.GeneralException; 9 | import com.gucardev.jwtproject.model.Role; 10 | import com.gucardev.jwtproject.model.User; 11 | import org.springframework.beans.factory.annotation.Value; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 14 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 15 | import org.springframework.stereotype.Component; 16 | 17 | import java.time.LocalDate; 18 | import java.time.LocalDateTime; 19 | import java.util.*; 20 | import java.util.stream.Collectors; 21 | 22 | @Component 23 | public class JwtHelper { 24 | 25 | 26 | @Value("${jwt-variables.KEY}") 27 | private String KEY; 28 | 29 | @Value("${jwt-variables.ISSUER}") 30 | private String ISSUER; 31 | 32 | @Value("${jwt-variables.EXPIRES_ACCESS_TOKEN_MINUTE}") 33 | private Integer EXPIRES_ACCESS_TOKEN_MINUTE; 34 | 35 | 36 | public String createJwtToken(User user) { 37 | 38 | Algorithm algorithm = Algorithm.HMAC256(KEY.getBytes()); 39 | 40 | List roles = user.getRoles().stream().map(Role::getName).collect(Collectors.toList()); 41 | 42 | return JWT.create().withSubject(user.getUsername()) 43 | .withExpiresAt(new Date(System.currentTimeMillis() + (EXPIRES_ACCESS_TOKEN_MINUTE * 60 * 1000))) 44 | .withIssuedAt(convertToDateViaSqlDate(LocalDate.now())) 45 | .withIssuer(ISSUER) 46 | .withClaim("roles", roles).sign(algorithm); 47 | } 48 | 49 | 50 | public String generateRefreshToken() { 51 | return UUID.randomUUID().toString().replace("-", ""); 52 | } 53 | 54 | 55 | public UsernamePasswordAuthenticationToken getAuthToken(String token) { 56 | 57 | DecodedJWT decodedJWT = verifyJWT(token); 58 | String username = decodedJWT.getSubject(); 59 | String[] roles = decodedJWT.getClaim("roles").asArray(String.class); 60 | Collection authorities = new ArrayList<>(); 61 | Arrays.stream(roles).forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); 62 | return new UsernamePasswordAuthenticationToken(username, null, authorities); 63 | 64 | } 65 | 66 | public DecodedJWT verifyJWT(String token) { 67 | Algorithm algorithm = Algorithm.HMAC256(KEY.getBytes()); 68 | JWTVerifier verifier = JWT.require(algorithm).acceptExpiresAt(EXPIRES_ACCESS_TOKEN_MINUTE * 60).build(); 69 | 70 | try { 71 | return verifier.verify(token); 72 | } catch (Exception e) { 73 | throw new GeneralException(e.getMessage(), HttpStatus.BAD_REQUEST); 74 | } 75 | } 76 | 77 | 78 | public Date convertToDateViaSqlDate(LocalDate dateToConvert) { 79 | return java.sql.Date.valueOf(dateToConvert); 80 | } 81 | 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.controller; 2 | 3 | 4 | import com.gucardev.jwtproject.dto.UserDto; 5 | import com.gucardev.jwtproject.model.User; 6 | import com.gucardev.jwtproject.request.RoleGrantRevokeRequest; 7 | import com.gucardev.jwtproject.request.UpdateUserRequest; 8 | import com.gucardev.jwtproject.service.UserService; 9 | import org.modelmapper.ModelMapper; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.security.access.prepost.PreAuthorize; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | import javax.validation.Valid; 16 | import java.util.stream.Collectors; 17 | 18 | @RestController 19 | @RequestMapping("/user") 20 | @CrossOrigin 21 | public class UserController { 22 | 23 | 24 | private final UserService userService; 25 | private final ModelMapper mapper; 26 | 27 | 28 | public UserController(UserService userService, ModelMapper mapper) { 29 | this.userService = userService; 30 | this.mapper = mapper; 31 | } 32 | 33 | 34 | @PreAuthorize("hasAnyAuthority('SUPERADMIN') || hasAnyAuthority('ADMIN')") 35 | @GetMapping("/all") 36 | public ResponseEntity getAllUsers() { 37 | //convert to dto 38 | var list = userService.getAllUsers() 39 | .stream().map(x -> mapper.map(x, UserDto.class)) 40 | .collect(Collectors.toList()); 41 | return ResponseEntity.status(HttpStatus.OK).body(list); 42 | } 43 | 44 | @GetMapping("/myself") 45 | public ResponseEntity getMyself() { 46 | var dto = mapper.map(userService.getMyself(), UserDto.class); 47 | return ResponseEntity.status(HttpStatus.OK).body(dto); 48 | } 49 | 50 | @GetMapping("/{username}") 51 | public ResponseEntity getUser(@PathVariable String username) { 52 | var dto = mapper.map(userService.getUserByPermit(username), UserDto.class); 53 | return ResponseEntity.status(HttpStatus.OK).body(dto); 54 | } 55 | 56 | @PutMapping 57 | public ResponseEntity updateUser(@Valid @RequestBody UpdateUserRequest user) { 58 | userService.updateUser(user); 59 | return ResponseEntity.status(HttpStatus.OK).build(); 60 | } 61 | 62 | @DeleteMapping("/{username}") 63 | public ResponseEntity deleteUser(@PathVariable String username) { 64 | userService.deleteUser(username); 65 | return ResponseEntity.status(HttpStatus.OK).build(); 66 | } 67 | 68 | 69 | @PutMapping("/role") 70 | public ResponseEntity grantRole(@Valid @RequestBody RoleGrantRevokeRequest request) { 71 | var dto = mapper.map(userService.grantRole(request.getUsername(), request.getRole()), UserDto.class); 72 | return ResponseEntity.ok().body(dto); 73 | } 74 | 75 | @DeleteMapping("/role") 76 | public ResponseEntity revokeRole(@Valid @RequestBody RoleGrantRevokeRequest request) { 77 | var dto = mapper.map(userService.revokeRole(request.getUsername(), request.getRole()), UserDto.class); 78 | return ResponseEntity.ok().body(dto); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.6.6 9 | 10 | 11 | com.gucardev 12 | jwt-project 13 | 0.0.1-SNAPSHOT 14 | jwt-project 15 | jwt-project 16 | 17 | 11 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-data-jpa 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-security 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-validation 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | 38 | com.h2database 39 | h2 40 | runtime 41 | 42 | 43 | org.projectlombok 44 | lombok 45 | true 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | 52 | 53 | org.springframework.security 54 | spring-security-test 55 | test 56 | 57 | 58 | 59 | com.auth0 60 | java-jwt 61 | 3.19.1 62 | 63 | 64 | 65 | org.modelmapper 66 | modelmapper 67 | 2.4.5 68 | 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-starter-websocket 73 | 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-starter-data-redis 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | org.springframework.boot 86 | spring-boot-maven-plugin 87 | 88 | 89 | 90 | org.projectlombok 91 | lombok 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/service/LoginRequestService.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.service; 2 | 3 | import com.gucardev.jwtproject.exception.GeneralException; 4 | import com.gucardev.jwtproject.model.qrLogin.LoginQRCode; 5 | import com.gucardev.jwtproject.model.qrLogin.LoginQRCodeType; 6 | import com.gucardev.jwtproject.repository.LoginQRCodeRepository; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.messaging.simp.SimpMessagingTemplate; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.util.ArrayList; 13 | import java.util.Iterator; 14 | import java.util.List; 15 | import java.util.Optional; 16 | 17 | @Service 18 | @Slf4j 19 | public class LoginRequestService { 20 | 21 | private final LoginQRCodeRepository repository; 22 | 23 | private final SimpMessagingTemplate messagingTemplate; 24 | 25 | public LoginRequestService(LoginQRCodeRepository repository, 26 | SimpMessagingTemplate messagingTemplate) { 27 | this.repository = repository; 28 | this.messagingTemplate = messagingTemplate; 29 | } 30 | 31 | public LoginQRCode findByRoom(String room) { 32 | return convertIteratorToList(repository.findAll()).stream(). 33 | filter(p -> p.getRoom().equals(room)). 34 | findFirst().orElse(null); 35 | } 36 | 37 | public LoginQRCode save(LoginQRCode loginQRCode) { 38 | Optional optionalObject = convertIteratorToList(repository.findAll()).stream(). 39 | filter(p -> p.getRoom().equals(loginQRCode.getRoom())). 40 | findFirst(); 41 | 42 | if (optionalObject.isPresent()) { 43 | var obj = optionalObject.get(); 44 | log.info(String.format("updated => old: %s new: %s", obj.getCode(), loginQRCode.getCode())); 45 | obj.setCode(loginQRCode.getCode()); 46 | return repository.save(obj); 47 | } 48 | return repository.save(loginQRCode); 49 | } 50 | 51 | public void deleteByRoom(String room) { 52 | var temp = findByRoom(room); 53 | if (temp != null) { 54 | repository.delete(temp); 55 | } 56 | } 57 | 58 | 59 | public void processMessage(String room, LoginQRCode loginQRCode, String sessionID) { 60 | 61 | if (!room.equals(loginQRCode.getRoom())) { 62 | throw new GeneralException("rooms are different!", 400); 63 | } 64 | if (loginQRCode.getType().equals(LoginQRCodeType.CLIENT)) { 65 | save(loginQRCode); 66 | } else if (loginQRCode.getType().equals(LoginQRCodeType.MOBILE)) { 67 | var existing = findByRoom(loginQRCode.getRoom()); 68 | if (existing != null && existing.getCode().equals(loginQRCode.getCode())) { 69 | log.info("YES"); 70 | //loginQRCode.setMessage("MY JWT TOKEN"); 71 | loginQRCode.setType(LoginQRCodeType.SERVER); 72 | sendMessage(loginQRCode); 73 | deleteByRoom(room); 74 | } else { 75 | log.error("qr code is expired"); 76 | sendMessage(generateErrorMessage("QR Code is expired!", loginQRCode.getRoom())); 77 | } 78 | } 79 | 80 | } 81 | 82 | public void sendMessage(LoginQRCode loginQRCode) { 83 | messagingTemplate.convertAndSend("/topic/loginListener/" + loginQRCode.getRoom(), loginQRCode); 84 | } 85 | 86 | private List convertIteratorToList(Iterable iterator) { 87 | List list = new ArrayList<>(); 88 | iterator.iterator().forEachRemaining(list::add); 89 | return list; 90 | } 91 | 92 | private LoginQRCode generateErrorMessage(String message, String room) { 93 | return LoginQRCode.builder().room(room).message(message).type(LoginQRCodeType.ERROR).build(); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.config; 2 | 3 | import com.gucardev.jwtproject.config.filter.CustomAuthenticationFilter; 4 | import com.gucardev.jwtproject.config.filter.CustomAuthorizationFilter; 5 | import com.gucardev.jwtproject.exception.CustomAccessDeniedHandler; 6 | import com.gucardev.jwtproject.exception.CustomAuthenticationExceptionHandler; 7 | import com.gucardev.jwtproject.service.AuthService; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 12 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 16 | import org.springframework.security.config.http.SessionCreationPolicy; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.security.crypto.password.PasswordEncoder; 19 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 20 | import org.springframework.web.cors.CorsConfiguration; 21 | import org.springframework.web.cors.CorsConfigurationSource; 22 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 23 | 24 | import java.util.Arrays; 25 | 26 | import static org.springframework.http.HttpMethod.POST; 27 | import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; 28 | 29 | @Configuration 30 | @EnableWebSecurity 31 | @EnableGlobalMethodSecurity(prePostEnabled = true) 32 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 33 | 34 | private final UserDetailsService userDetailsService; 35 | private final PasswordEncoder passwordEncoder; 36 | private final AuthService authService; 37 | 38 | 39 | public SecurityConfig(UserDetailsService userDetailsService, 40 | PasswordEncoder passwordEncoder, 41 | AuthService authService) { 42 | this.userDetailsService = userDetailsService; 43 | this.passwordEncoder = passwordEncoder; 44 | this.authService = authService; 45 | } 46 | 47 | 48 | @Override 49 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 50 | auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); 51 | } 52 | 53 | 54 | @Override 55 | protected void configure(HttpSecurity http) throws Exception { 56 | CustomAuthenticationFilter customAuthFilter = 57 | new CustomAuthenticationFilter(authService); 58 | customAuthFilter.setAuthenticationManager(authenticationManagerBean()); 59 | 60 | http.cors().and() 61 | .authorizeRequests() 62 | .antMatchers("/loginListener/**").permitAll() 63 | .antMatchers(POST, "/auth/login", "/auth/register", "/auth/refresh").permitAll() 64 | .antMatchers("/h2-console/**", "/chat", "/loginListener", "/topic").permitAll() 65 | .antMatchers("/role/**").hasAnyAuthority("ADMIN", "SUPERADMIN") 66 | .anyRequest().authenticated() 67 | .and() 68 | .exceptionHandling().accessDeniedHandler(accessDeniedHandler()) 69 | .and() 70 | .addFilterAt(customAuthFilter, UsernamePasswordAuthenticationFilter.class) 71 | .exceptionHandling().authenticationEntryPoint(authenticationExceptionHandler()) 72 | .and() 73 | .addFilterBefore(new CustomAuthorizationFilter(authService), 74 | UsernamePasswordAuthenticationFilter.class) 75 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 76 | .and().csrf().disable(); 77 | 78 | } 79 | 80 | @Bean 81 | @Override 82 | public AuthenticationManager authenticationManagerBean() throws Exception { 83 | return super.authenticationManagerBean(); 84 | } 85 | 86 | @Bean 87 | public CustomAccessDeniedHandler accessDeniedHandler() { 88 | return new CustomAccessDeniedHandler(); 89 | 90 | } 91 | 92 | @Bean 93 | public CustomAuthenticationExceptionHandler authenticationExceptionHandler() { 94 | return new CustomAuthenticationExceptionHandler(); 95 | } 96 | 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/service/AuthService.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.service; 2 | 3 | 4 | import com.gucardev.jwtproject.exception.GeneralException; 5 | import com.gucardev.jwtproject.model.RefreshToken; 6 | import com.gucardev.jwtproject.model.User; 7 | import com.gucardev.jwtproject.repository.RefreshTokenRepository; 8 | import com.gucardev.jwtproject.request.CreateUserRequest; 9 | import com.gucardev.jwtproject.request.LoginRequest; 10 | import com.gucardev.jwtproject.util.JwtHelper; 11 | import org.springframework.beans.factory.annotation.Value; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 14 | import org.springframework.security.core.Authentication; 15 | import org.springframework.security.core.context.SecurityContextHolder; 16 | import org.springframework.stereotype.Service; 17 | 18 | import javax.transaction.Transactional; 19 | import java.time.LocalDateTime; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | @Service 24 | @Transactional 25 | public class AuthService { 26 | 27 | @Value("${jwt-variables.EXPIRES_REFRESH_TOKEN_MINUTE}") 28 | private String EXPIRES_REFRESH_TOKEN_MINUTE; 29 | 30 | private final UserService userService; 31 | private final RefreshTokenRepository refreshTokenRepository; 32 | private final JwtHelper jwtHelper; 33 | 34 | public AuthService(UserService userService, 35 | RefreshTokenRepository refreshTokenRepository, 36 | JwtHelper jwtHelper) { 37 | this.userService = userService; 38 | this.refreshTokenRepository = refreshTokenRepository; 39 | this.jwtHelper = jwtHelper; 40 | } 41 | 42 | private RefreshToken createRefreshToken(User user) { 43 | RefreshToken refreshToken = new RefreshToken(); 44 | String token; 45 | do { 46 | 47 | token = jwtHelper.generateRefreshToken(); 48 | 49 | } while (refreshTokenRepository.findByToken(token).isPresent()); 50 | 51 | refreshToken.setUser(user); 52 | refreshToken.setToken(token); 53 | refreshToken.setExpiryDate(LocalDateTime.now().plusMinutes(Long.parseLong(EXPIRES_REFRESH_TOKEN_MINUTE))); 54 | refreshTokenRepository.save(refreshToken); 55 | return refreshToken; 56 | } 57 | 58 | 59 | public Map createTokens(User user) { 60 | return createTokens(user.getUsername()); 61 | } 62 | 63 | public Map createTokens(String username) { 64 | 65 | var user = userService.getUserByUsername(username); 66 | 67 | String access_token = jwtHelper.createJwtToken(user); 68 | RefreshToken refreshToken = createRefreshToken(user); 69 | 70 | Map map = new HashMap(); 71 | map.put("access_token", access_token); 72 | map.put("refresh_token", refreshToken.getToken()); 73 | map.put("username", user.getUsername()); 74 | map.put("id", user.getId().toString()); 75 | return map; 76 | } 77 | 78 | 79 | public Map registerUser(CreateUserRequest createUserRequest) { 80 | 81 | var user = User.builder() 82 | .username(createUserRequest.getUsername()) 83 | .email(createUserRequest.getEmail()) 84 | .password(createUserRequest.getPassword()) 85 | .build(); 86 | userService.saveUser(user); 87 | return createTokens(user); 88 | 89 | } 90 | 91 | 92 | public Map login(LoginRequest loginRequest) { 93 | deleteOldTokensByLogin(loginRequest.getUsername()); 94 | var user = userService.checkLoginUser(loginRequest.getUsername(), loginRequest.getPassword()); 95 | return createTokens(user); 96 | } 97 | 98 | public void logout() { 99 | deleteOldTokensByUsername(getAuthenticatedUser().getUsername()); 100 | } 101 | 102 | public User getAuthenticatedUser() { 103 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 104 | return userService.getUserByUsername(auth.getName()); 105 | } 106 | 107 | public UsernamePasswordAuthenticationToken getAuthToken(String token) { 108 | return jwtHelper.getAuthToken(token); 109 | } 110 | 111 | 112 | public Map refreshTokens(String refreshToken) { 113 | 114 | RefreshToken token = getRefreshToken(refreshToken); 115 | 116 | if (token != null) { 117 | deleteRefreshToken(token.getToken()); 118 | 119 | return createTokens(token.getUser()); 120 | } else 121 | throw new GeneralException("Invalid refresh token!", HttpStatus.BAD_REQUEST); 122 | 123 | } 124 | 125 | public void deleteRefreshToken(String token) { 126 | RefreshToken refreshToken = getRefreshToken(token); 127 | refreshTokenRepository.delete(refreshToken); 128 | } 129 | 130 | public void deleteOldTokensByLogin(String username) { 131 | refreshTokenRepository.deleteRefreshTokenByUser(userService.getUserByUsername(username)); 132 | } 133 | 134 | public void deleteOldTokensByUsername(String username) { 135 | User user = userService.getUserByUsername(username); 136 | 137 | if (refreshTokenRepository.findByUser(user).isPresent()) { 138 | refreshTokenRepository.deleteRefreshTokenByUser(user); 139 | } else { 140 | throw new GeneralException("you already have been logouted!", HttpStatus.BAD_REQUEST); 141 | } 142 | 143 | } 144 | 145 | 146 | protected RefreshToken getRefreshToken(String token) { 147 | return refreshTokenRepository.findByToken(token) 148 | .orElseThrow(() -> new GeneralException("token not found", HttpStatus.NOT_FOUND)); 149 | } 150 | 151 | 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/com/gucardev/jwtproject/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.gucardev.jwtproject.service; 2 | 3 | import com.gucardev.jwtproject.exception.GeneralException; 4 | import com.gucardev.jwtproject.model.ROLES; 5 | import com.gucardev.jwtproject.model.Role; 6 | import com.gucardev.jwtproject.model.User; 7 | import com.gucardev.jwtproject.repository.UserRepository; 8 | import com.gucardev.jwtproject.request.UpdateUserRequest; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.security.core.Authentication; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.security.core.context.SecurityContextHolder; 13 | import org.springframework.security.core.userdetails.UserDetails; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 16 | import org.springframework.security.crypto.password.PasswordEncoder; 17 | import org.springframework.stereotype.Service; 18 | 19 | import java.util.ArrayList; 20 | import java.util.Collection; 21 | import java.util.List; 22 | 23 | @Service 24 | public class UserService implements UserDetailsService { 25 | 26 | private final UserRepository userRepository; 27 | private final PasswordEncoder passwordEncoder; 28 | private final RoleService roleService; 29 | private final BCryptPasswordEncoder bCryptPasswordEncoder; 30 | 31 | public UserService(UserRepository userRepository, 32 | PasswordEncoder passwordEncoder, 33 | RoleService roleService, BCryptPasswordEncoder bCryptPasswordEncoder) { 34 | this.userRepository = userRepository; 35 | this.passwordEncoder = passwordEncoder; 36 | this.roleService = roleService; 37 | this.bCryptPasswordEncoder = bCryptPasswordEncoder; 38 | } 39 | 40 | @Override 41 | public UserDetails loadUserByUsername(String username) { 42 | User user = getUserByUsername(username); 43 | 44 | Collection authorities = new ArrayList<>(); 45 | user.getRoles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getName()))); 46 | 47 | return new org.springframework.security.core.userdetails.User( 48 | user.getUsername(), user.getPassword(), authorities); 49 | } 50 | 51 | public List getAllUsers() { 52 | return userRepository.findAll(); 53 | } 54 | 55 | public User getMyself() { 56 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 57 | return getUserByUsername(auth.getName()); 58 | } 59 | 60 | public User getUserByPermit(String username) { 61 | User user = getUserByUsername(username); 62 | if (!isAuthorized(user)) { 63 | throw new GeneralException("you can not make this operation!", HttpStatus.UNAUTHORIZED); 64 | } 65 | return user; 66 | } 67 | 68 | 69 | public User saveUser(User user) { 70 | 71 | if (userRepository.findUserByUsername(user.getUsername()).isPresent()) { 72 | throw new GeneralException("User already exists!", HttpStatus.CONFLICT); 73 | } 74 | 75 | var userRole = roleService.getRoleByName(ROLES.USER.toString()); 76 | user.setPassword(passwordEncoder.encode(user.getPassword())); 77 | user.setRoles(List.of(userRole)); 78 | User newUser; 79 | try { 80 | newUser = userRepository.save(user); 81 | } catch (Exception e) { 82 | throw new GeneralException("An error occurred while saving user!", 83 | HttpStatus.BAD_REQUEST); 84 | } 85 | return newUser; 86 | } 87 | 88 | public void updateUser(UpdateUserRequest userRequest) { 89 | // get the user if it is admin or himself 90 | User existing = getUserByPermit(userRequest.getUsername()); 91 | updateUser(existing); 92 | } 93 | 94 | public void updateUser(User user) { 95 | User existing = getUserByUsername(user.getUsername()); 96 | 97 | // DON'T UPDATE PASSWORD HERE!! 98 | // TODO create update password method 99 | // existing.setPassword(passwordEncoder.encode(user.getPassword())); 100 | existing.setEmail(user.getEmail()); 101 | existing.setName(user.getName()); 102 | existing.setSurname(user.getSurname()); 103 | if (doesIncludesRoles(List.of(ROLES.ADMIN, ROLES.SUPERADMIN), user.getRoles())) { 104 | existing.setRoles(user.getRoles()); 105 | } 106 | userRepository.save(existing); 107 | } 108 | 109 | 110 | public void deleteUser(String username) { 111 | // get the user if it is admin or himself 112 | User existing = getUserByPermit(username); 113 | userRepository.delete(existing); 114 | } 115 | 116 | 117 | protected User getUserByUsername(String username) { 118 | return userRepository.findUserByUsername(username) 119 | .orElseThrow(() -> new GeneralException("User not found!", HttpStatus.NOT_FOUND)); 120 | } 121 | 122 | protected User checkLoginUser(String username, String password) { 123 | var user = getUserByUsername(username); 124 | if (!bCryptPasswordEncoder.matches(password, user.getPassword())) { 125 | throw new GeneralException("wrong password!", HttpStatus.NOT_FOUND); 126 | } 127 | return user; 128 | } 129 | 130 | 131 | private boolean isAuthorized(User unknownUser) { 132 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 133 | User user = getUserByUsername(auth.getName()); 134 | 135 | var isAdmin = doesIncludesRoles( 136 | List.of(ROLES.SUPERADMIN, ROLES.ADMIN), 137 | user.getRoles()); 138 | 139 | var isOwner = unknownUser.getId().equals(user.getId()); 140 | 141 | return isAdmin || isOwner; 142 | } 143 | 144 | 145 | public User grantRole(String username, String roleName) { 146 | User user = getUserByUsername(username); 147 | Role role = roleService.getRoleByName(roleName); 148 | if (!user.getRoles().contains(role)) { 149 | user.getRoles().add(role); 150 | updateUser(user); 151 | } else { 152 | throw new GeneralException("Role already exists!", HttpStatus.NOT_ACCEPTABLE); 153 | } 154 | 155 | return user; 156 | } 157 | 158 | public User revokeRole(String username, String roleName) { 159 | User user = getUserByUsername(username); 160 | Role role = roleService.getRoleByName(roleName); 161 | var roles = user.getRoles(); 162 | if (roles.size() > 1 && !role.getName().equals(ROLES.SUPERADMIN.toString())) { 163 | user.getRoles().remove(role); 164 | updateUser(user); 165 | } else if (role.getName().equals(ROLES.SUPERADMIN.toString())) { 166 | throw new GeneralException("Are you kidding :D", HttpStatus.NOT_ACCEPTABLE); 167 | } else { 168 | throw new GeneralException("Every user must have a role at least!", HttpStatus.NOT_ACCEPTABLE); 169 | } 170 | return user; 171 | } 172 | 173 | 174 | protected boolean doesIncludesRoles(List checkRoles, List roles) { 175 | return roles.stream() 176 | .anyMatch(role -> checkRoles.stream() 177 | .anyMatch(x -> x.toString().equals(role.getName()))); 178 | } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /jwt-auth-project.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "4245c609-8458-496a-a0ec-be40112cfd20", 4 | "name": "jwt-auth-project", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "auth controller", 10 | "item": [ 11 | { 12 | "name": "register user", 13 | "request": { 14 | "method": "POST", 15 | "header": [], 16 | "body": { 17 | "mode": "raw", 18 | "raw": "{\r\n \"username\":\"gurkan\",\r\n \"email\":\"gurkan@gurkanucar.com\",\r\n \"password\":\"password\"\r\n}", 19 | "options": { 20 | "raw": { 21 | "language": "json" 22 | } 23 | } 24 | }, 25 | "url": { 26 | "raw": "http://localhost:8080/auth/register", 27 | "protocol": "http", 28 | "host": [ 29 | "localhost" 30 | ], 31 | "port": "8080", 32 | "path": [ 33 | "auth", 34 | "register" 35 | ] 36 | } 37 | }, 38 | "response": [] 39 | }, 40 | { 41 | "name": "login [SUPERADMIN]", 42 | "request": { 43 | "method": "POST", 44 | "header": [], 45 | "body": { 46 | "mode": "raw", 47 | "raw": "{\r\n \"username\":\"gurkan\",\r\n \"email\":\"g@mail.com\",\r\n \"password\":\"password\"\r\n}", 48 | "options": { 49 | "raw": { 50 | "language": "json" 51 | } 52 | } 53 | }, 54 | "url": { 55 | "raw": "http://localhost:8080/auth/login", 56 | "protocol": "http", 57 | "host": [ 58 | "localhost" 59 | ], 60 | "port": "8080", 61 | "path": [ 62 | "auth", 63 | "login" 64 | ] 65 | } 66 | }, 67 | "response": [] 68 | }, 69 | { 70 | "name": "login [ADMIN]", 71 | "request": { 72 | "method": "POST", 73 | "header": [], 74 | "body": { 75 | "mode": "raw", 76 | "raw": "{\r\n \"username\":\"sezai\",\r\n \"email\":\"s@mail.com\",\r\n \"password\":\"password\"\r\n}", 77 | "options": { 78 | "raw": { 79 | "language": "json" 80 | } 81 | } 82 | }, 83 | "url": { 84 | "raw": "http://localhost:8080/auth/login", 85 | "protocol": "http", 86 | "host": [ 87 | "localhost" 88 | ], 89 | "port": "8080", 90 | "path": [ 91 | "auth", 92 | "login" 93 | ] 94 | } 95 | }, 96 | "response": [] 97 | }, 98 | { 99 | "name": "login [USER]", 100 | "request": { 101 | "method": "POST", 102 | "header": [], 103 | "body": { 104 | "mode": "raw", 105 | "raw": "{\r\n \"username\":\"metin\",\r\n \"email\":\"m@mail.com\",\r\n \"password\":\"password\"\r\n}", 106 | "options": { 107 | "raw": { 108 | "language": "json" 109 | } 110 | } 111 | }, 112 | "url": { 113 | "raw": "http://localhost:8080/auth/login", 114 | "protocol": "http", 115 | "host": [ 116 | "localhost" 117 | ], 118 | "port": "8080", 119 | "path": [ 120 | "auth", 121 | "login" 122 | ] 123 | } 124 | }, 125 | "response": [] 126 | }, 127 | { 128 | "name": "login [USER] 2", 129 | "request": { 130 | "method": "POST", 131 | "header": [], 132 | "body": { 133 | "mode": "raw", 134 | "raw": "{\r\n \"username\":\"ali\",\r\n \"email\":\"a@mail.com\",\r\n \"password\":\"password\"\r\n}", 135 | "options": { 136 | "raw": { 137 | "language": "json" 138 | } 139 | } 140 | }, 141 | "url": { 142 | "raw": "http://localhost:8080/auth/login", 143 | "protocol": "http", 144 | "host": [ 145 | "localhost" 146 | ], 147 | "port": "8080", 148 | "path": [ 149 | "auth", 150 | "login" 151 | ] 152 | } 153 | }, 154 | "response": [] 155 | }, 156 | { 157 | "name": "logout", 158 | "request": { 159 | "auth": { 160 | "type": "bearer", 161 | "bearer": [ 162 | { 163 | "key": "token", 164 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhaG1ldCIsInJvbGVzIjpbIlJPTEVfVVNFUiJdLCJpc3MiOiI5MDAwMCJ9.BFmKtDFayoPbxIt4ZbMeIdKNNAGi4xVNR2PGYyFQJq8", 165 | "type": "string" 166 | } 167 | ] 168 | }, 169 | "method": "POST", 170 | "header": [], 171 | "body": { 172 | "mode": "raw", 173 | "raw": "", 174 | "options": { 175 | "raw": { 176 | "language": "json" 177 | } 178 | } 179 | }, 180 | "url": { 181 | "raw": "http://localhost:8080/auth/logout", 182 | "protocol": "http", 183 | "host": [ 184 | "localhost" 185 | ], 186 | "port": "8080", 187 | "path": [ 188 | "auth", 189 | "logout" 190 | ] 191 | } 192 | }, 193 | "response": [] 194 | }, 195 | { 196 | "name": "refresh", 197 | "request": { 198 | "auth": { 199 | "type": "noauth" 200 | }, 201 | "method": "POST", 202 | "header": [], 203 | "body": { 204 | "mode": "raw", 205 | "raw": "{\r\n \"token\":\"1a7d4357e37946218a5d31390ba29708\"\r\n}", 206 | "options": { 207 | "raw": { 208 | "language": "json" 209 | } 210 | } 211 | }, 212 | "url": { 213 | "raw": "http://localhost:8080/auth/refresh", 214 | "protocol": "http", 215 | "host": [ 216 | "localhost" 217 | ], 218 | "port": "8080", 219 | "path": [ 220 | "auth", 221 | "refresh" 222 | ] 223 | } 224 | }, 225 | "response": [] 226 | } 227 | ] 228 | }, 229 | { 230 | "name": "user controller", 231 | "item": [ 232 | { 233 | "name": "get all users [ADMIN]", 234 | "request": { 235 | "auth": { 236 | "type": "bearer", 237 | "bearer": [ 238 | { 239 | "key": "token", 240 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZXphaSIsInJvbGVzIjpbIkFETUlOIl0sImlzcyI6Imd1Y2FyZGV2IiwiZXhwIjoxNjQ5NzY5MzI1LCJpYXQiOjE2NDk3MTA4MDB9.4Eo-GbXEvj45gpMiRg7dm2H-pERBxPYsYRIO1AbeWT4", 241 | "type": "string" 242 | } 243 | ] 244 | }, 245 | "method": "GET", 246 | "header": [], 247 | "url": { 248 | "raw": "http://localhost:8080/user/all", 249 | "protocol": "http", 250 | "host": [ 251 | "localhost" 252 | ], 253 | "port": "8080", 254 | "path": [ 255 | "user", 256 | "all" 257 | ] 258 | } 259 | }, 260 | "response": [] 261 | }, 262 | { 263 | "name": "get user", 264 | "request": { 265 | "auth": { 266 | "type": "bearer", 267 | "bearer": [ 268 | { 269 | "key": "token", 270 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndXJrYW4iLCJyb2xlcyI6WyJTVVBFUkFETUlOIl0sImlzcyI6Imd1Y2FyZGV2IiwiZXhwIjoxNjQ5NzcxMDU0LCJpYXQiOjE2NDk3MTA4MDB9.WpwNmeR2SjXR-QHL6fJxr4b47UWZ04PxNe1UOCibsFc", 271 | "type": "string" 272 | } 273 | ] 274 | }, 275 | "method": "GET", 276 | "header": [], 277 | "url": { 278 | "raw": "http://localhost:8080/user/gurkan", 279 | "protocol": "http", 280 | "host": [ 281 | "localhost" 282 | ], 283 | "port": "8080", 284 | "path": [ 285 | "user", 286 | "gurkan" 287 | ] 288 | } 289 | }, 290 | "response": [] 291 | }, 292 | { 293 | "name": "grantRole", 294 | "request": { 295 | "auth": { 296 | "type": "bearer", 297 | "bearer": [ 298 | { 299 | "key": "token", 300 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndXJrYW4iLCJyb2xlcyI6WyJBRE1JTiJdLCJpc3MiOiJndWNhcmRldiIsImV4cCI6MTY0OTc2NzgxNCwiaWF0IjoxNjQ5NzEwODAwfQ.nCAOMI0INcLKC1A0KREbKfXFEaW5-IRlAz-mfnA6pnc", 301 | "type": "string" 302 | } 303 | ] 304 | }, 305 | "method": "PUT", 306 | "header": [], 307 | "body": { 308 | "mode": "raw", 309 | "raw": "{\r\n \"username\":\"gurkan\",\r\n \"role\":\"ADMIN\"\r\n}", 310 | "options": { 311 | "raw": { 312 | "language": "json" 313 | } 314 | } 315 | }, 316 | "url": { 317 | "raw": "http://localhost:8080/user/role", 318 | "protocol": "http", 319 | "host": [ 320 | "localhost" 321 | ], 322 | "port": "8080", 323 | "path": [ 324 | "user", 325 | "role" 326 | ] 327 | } 328 | }, 329 | "response": [] 330 | }, 331 | { 332 | "name": "revokeRole", 333 | "request": { 334 | "auth": { 335 | "type": "bearer", 336 | "bearer": [ 337 | { 338 | "key": "token", 339 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndXJrYW4iLCJyb2xlcyI6WyJBRE1JTiJdLCJpc3MiOiJndWNhcmRldiIsImV4cCI6MTY0OTc2NzgxNCwiaWF0IjoxNjQ5NzEwODAwfQ.nCAOMI0INcLKC1A0KREbKfXFEaW5-IRlAz-mfnA6pnc", 340 | "type": "string" 341 | } 342 | ] 343 | }, 344 | "method": "DELETE", 345 | "header": [], 346 | "body": { 347 | "mode": "raw", 348 | "raw": "{\r\n \"username\":\"gurkan\",\r\n \"role\":\"SUPERADMIN\"\r\n}", 349 | "options": { 350 | "raw": { 351 | "language": "json" 352 | } 353 | } 354 | }, 355 | "url": { 356 | "raw": "http://localhost:8080/user/role", 357 | "protocol": "http", 358 | "host": [ 359 | "localhost" 360 | ], 361 | "port": "8080", 362 | "path": [ 363 | "user", 364 | "role" 365 | ] 366 | } 367 | }, 368 | "response": [] 369 | }, 370 | { 371 | "name": "update user", 372 | "request": { 373 | "auth": { 374 | "type": "bearer", 375 | "bearer": [ 376 | { 377 | "key": "token", 378 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtZXRpbiIsInJvbGVzIjpbIlVTRVIiXSwiaXNzIjoiZ3VjYXJkZXYiLCJleHAiOjE2NDk3NzE3NjgsImlhdCI6MTY0OTcxMDgwMH0.sZjsEbj0mpTDX7fcllVEcWIEH1u_1bSMRq1V3KDWqGM", 379 | "type": "string" 380 | } 381 | ] 382 | }, 383 | "method": "PUT", 384 | "header": [], 385 | "body": { 386 | "mode": "raw", 387 | "raw": "{\r\n \"username\": \"metin\",\r\n \"email\": \"mm@mail.com\",\r\n \"password\":\"passwordddd123\",\r\n \"name\":\"metin\",\r\n \"surname\":\"sezai\"\r\n \r\n}", 388 | "options": { 389 | "raw": { 390 | "language": "json" 391 | } 392 | } 393 | }, 394 | "url": { 395 | "raw": "http://localhost:8080/user", 396 | "protocol": "http", 397 | "host": [ 398 | "localhost" 399 | ], 400 | "port": "8080", 401 | "path": [ 402 | "user" 403 | ] 404 | } 405 | }, 406 | "response": [] 407 | } 408 | ] 409 | }, 410 | { 411 | "name": "role controller", 412 | "item": [ 413 | { 414 | "name": "get all roles", 415 | "request": { 416 | "auth": { 417 | "type": "bearer", 418 | "bearer": [ 419 | { 420 | "key": "token", 421 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndXJrYW4iLCJyb2xlcyI6WyJTVVBFUkFETUlOIl0sImlzcyI6Imd1Y2FyZGV2IiwiZXhwIjoxNjQ5NzcwNTQyLCJpYXQiOjE2NDk3MTA4MDB9.D_Rw-m-zxzzF6qIly-Heqw8Ua5j4kMhtr3nMY-OrUnI", 422 | "type": "string" 423 | } 424 | ] 425 | }, 426 | "method": "GET", 427 | "header": [], 428 | "url": { 429 | "raw": "http://localhost:8080/role/all", 430 | "protocol": "http", 431 | "host": [ 432 | "localhost" 433 | ], 434 | "port": "8080", 435 | "path": [ 436 | "role", 437 | "all" 438 | ] 439 | } 440 | }, 441 | "response": [] 442 | }, 443 | { 444 | "name": "save role", 445 | "request": { 446 | "auth": { 447 | "type": "bearer", 448 | "bearer": [ 449 | { 450 | "key": "token", 451 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndXJrYW4iLCJyb2xlcyI6WyJTVVBFUkFETUlOIl0sImlzcyI6Imd1Y2FyZGV2IiwiZXhwIjoxNjQ5NzcwNTQyLCJpYXQiOjE2NDk3MTA4MDB9.D_Rw-m-zxzzF6qIly-Heqw8Ua5j4kMhtr3nMY-OrUnI", 452 | "type": "string" 453 | } 454 | ] 455 | }, 456 | "method": "POST", 457 | "header": [], 458 | "body": { 459 | "mode": "raw", 460 | "raw": "{\r\n \"name\":\"TEST\",\r\n \"detail\":\"test role\"\r\n}", 461 | "options": { 462 | "raw": { 463 | "language": "json" 464 | } 465 | } 466 | }, 467 | "url": { 468 | "raw": "http://localhost:8080/role", 469 | "protocol": "http", 470 | "host": [ 471 | "localhost" 472 | ], 473 | "port": "8080", 474 | "path": [ 475 | "role" 476 | ] 477 | } 478 | }, 479 | "response": [] 480 | } 481 | ] 482 | }, 483 | { 484 | "name": "hello test", 485 | "request": { 486 | "auth": { 487 | "type": "bearer", 488 | "bearer": [ 489 | { 490 | "key": "token", 491 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndXJrYW4iLCJyb2xlcyI6WyJST0xFX1VTRVIiXSwiaXNzIjoiZ3VjYXJkZXYiLCJleHAiOjE2NDk3NTkxNDksImlhdCI6MTY0OTcxMDgwMH0.BiE6U0XV7uNnal9I9RrGuaOG2TweymJyeRNHX9l5IN8", 492 | "type": "string" 493 | } 494 | ] 495 | }, 496 | "method": "GET", 497 | "header": [], 498 | "url": { 499 | "raw": "http://localhost:8080/test", 500 | "protocol": "http", 501 | "host": [ 502 | "localhost" 503 | ], 504 | "port": "8080", 505 | "path": [ 506 | "test" 507 | ] 508 | } 509 | }, 510 | "response": [] 511 | }, 512 | { 513 | "name": "admin test", 514 | "request": { 515 | "auth": { 516 | "type": "bearer", 517 | "bearer": [ 518 | { 519 | "key": "token", 520 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJndXJrYW4iLCJyb2xlcyI6WyJBRE1JTiJdLCJpc3MiOiJndWNhcmRldiIsImV4cCI6MTY0OTc2MDE5MywiaWF0IjoxNjQ5NzEwODAwfQ.goqMztlhTv7l8Wni7pSpeZZMseG82g9GFDmxvwJ_3xQ", 521 | "type": "string" 522 | } 523 | ] 524 | }, 525 | "method": "GET", 526 | "header": [], 527 | "url": { 528 | "raw": "http://localhost:8080/test/admin", 529 | "protocol": "http", 530 | "host": [ 531 | "localhost" 532 | ], 533 | "port": "8080", 534 | "path": [ 535 | "test", 536 | "admin" 537 | ] 538 | } 539 | }, 540 | "response": [] 541 | } 542 | ] 543 | } --------------------------------------------------------------------------------