mirror of
https://gitea.gofwd.group/Forward_Group/ballistic-builder-spring.git
synced 2025-12-06 02:56:44 -05:00
Compare commits
4 Commits
7e1b33efdf
...
d344b372d1
| Author | SHA1 | Date | |
|---|---|---|---|
| d344b372d1 | |||
| 31815d3145 | |||
| 4138edf45d | |||
| 85b00e9d99 |
34
docker/backend/Dockerfile
Normal file
34
docker/backend/Dockerfile
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# Stage 1: Build the application (The Build Stage)
|
||||||
|
# Use a Java SDK image with Maven pre-installed
|
||||||
|
FROM maven:3.9-jdk-17-slim AS build
|
||||||
|
|
||||||
|
# Set the working directory inside the container
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy the Maven project files (pom.xml) first to leverage Docker layer caching
|
||||||
|
COPY pom.xml .
|
||||||
|
|
||||||
|
# Copy the source code
|
||||||
|
COPY src ./src
|
||||||
|
|
||||||
|
# Build the Spring Boot application, skipping tests to speed up the Docker build
|
||||||
|
# This creates the executable JAR file in the 'target' directory
|
||||||
|
RUN mvn clean package -DskipTests
|
||||||
|
|
||||||
|
# Stage 2: Create the final lightweight image (The Runtime Stage)
|
||||||
|
# Use a smaller Java Runtime Environment (JRE) image for a smaller footprint
|
||||||
|
FROM openjdk:17-jre-slim
|
||||||
|
|
||||||
|
# Set the working directory in the final image
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy the built JAR file from the 'build' stage into the final image
|
||||||
|
# The JAR file is typically named 'target/<your-app-name>-<version>.jar'
|
||||||
|
# You may need to adjust the name if you have a non-standard pom.xml
|
||||||
|
COPY --from=build /app/target/*.jar app.jar
|
||||||
|
|
||||||
|
# Expose the default Spring Boot port
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
# Define the command to run the application
|
||||||
|
ENTRYPOINT ["java", "-jar", "app.jar"]
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
# Stage 1: Build the application
|
|
||||||
FROM openjdk:17-jdk-slim as build
|
|
||||||
WORKDIR /app
|
|
||||||
COPY gradlew .
|
|
||||||
COPY settings.gradle .
|
|
||||||
COPY build.gradle .
|
|
||||||
COPY src ./src
|
|
||||||
# Adjust the build command for Maven: ./mvnw package -DskipTests
|
|
||||||
RUN ./gradlew bootJar
|
|
||||||
|
|
||||||
# Stage 2: Create the final lightweight image
|
|
||||||
FROM openjdk:17-jre-slim
|
|
||||||
WORKDIR /app
|
|
||||||
# Get the built JAR from the build stage
|
|
||||||
COPY --from=build /app/build/libs/*.jar app.jar
|
|
||||||
EXPOSE 8080
|
|
||||||
ENTRYPOINT ["java", "-jar", "app.jar"]
|
|
||||||
@@ -2,20 +2,18 @@ version: '3.8'
|
|||||||
|
|
||||||
services:
|
services:
|
||||||
# --- 1. Spring API Service (Backend) ---
|
# --- 1. Spring API Service (Backend) ---
|
||||||
spring-api:
|
ss_builder-api:
|
||||||
build:
|
build:
|
||||||
context: ./backend # Path to your Spring project's root folder
|
context: ./backend # Path to your Spring project's root folder
|
||||||
dockerfile: Dockerfile # Assumes you have a Dockerfile in ./backend
|
dockerfile: Dockerfile # Assumes you have a Dockerfile in ./backend
|
||||||
container_name: spring-api
|
container_name: ss_builder-api
|
||||||
ports:
|
ports:
|
||||||
- "8080:8080" # Map host port 8080 to container port 8080
|
- "8080:8080" # Map host port 8080 to container port 8080
|
||||||
environment:
|
environment:
|
||||||
# These environment variables link the API to the database service defined below
|
# These environment variables link the API to the database service defined below
|
||||||
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/mydatabase
|
- SPRING_DATASOURCE_URL=jdbc:postgresql://r710.dev.gofwd.group:5433/ss_builder
|
||||||
- SPRING_DATASOURCE_USERNAME=myuser
|
- SPRING_DATASOURCE_USERNAME=dba
|
||||||
- SPRING_DATASOURCE_PASSWORD=mypassword
|
- SPRING_DATASOURCE_PASSWORD=!@#Qwerty
|
||||||
depends_on:
|
|
||||||
- db
|
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
|
|
||||||
@@ -24,38 +22,20 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: ./frontend # Path to your Next.js project's root folder
|
context: ./frontend # Path to your Next.js project's root folder
|
||||||
dockerfile: Dockerfile # Assumes you have a Dockerfile in ./frontend
|
dockerfile: Dockerfile # Assumes you have a Dockerfile in ./frontend
|
||||||
container_name: nextjs-app
|
container_name: ss_builder-app
|
||||||
ports:
|
ports:
|
||||||
- "3000:3000" # Map host port 3000 to container port 3000
|
- "3000:3000" # Map host port 3000 to container port 3000
|
||||||
environment:
|
environment:
|
||||||
# This variable is crucial: Next.js needs the URL for the Spring API
|
# This variable is crucial: Next.js needs the URL for the Spring API
|
||||||
# Use the Docker internal service name 'spring-api' and its port 8080
|
# Use the Docker internal service name 'spring-api' and its port 8080
|
||||||
- NEXT_PUBLIC_API_URL=http://spring-api:8080
|
- NEXT_PUBLIC_API_URL=http://ss_builder-api:8080
|
||||||
# For local testing, you might need the host IP for Next.js to call back
|
# For local testing, you might need the host IP for Next.js to call back
|
||||||
# - NEXT_PUBLIC_API_URL_LOCAL=http://localhost:8080
|
# - NEXT_PUBLIC_API_URL_LOCAL=http://localhost:8080
|
||||||
depends_on:
|
depends_on:
|
||||||
- spring-api
|
- ss_builder-api
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
|
|
||||||
# --- 3. PostgreSQL Database Service (Example Dependency) ---
|
|
||||||
db:
|
|
||||||
image: postgres:15-alpine # Lightweight and stable PostgreSQL image
|
|
||||||
container_name: postgres-db
|
|
||||||
environment:
|
|
||||||
- POSTGRES_DB=mydatabase
|
|
||||||
- POSTGRES_USER=myuser
|
|
||||||
- POSTGRES_PASSWORD=mypassword
|
|
||||||
volumes:
|
|
||||||
- postgres_data:/var/lib/postgresql/data # Persist the database data
|
|
||||||
ports:
|
|
||||||
- "5432:5432" # Optional: Map DB port for external access (e.g., DBeaver)
|
|
||||||
networks:
|
|
||||||
- app-network
|
|
||||||
|
|
||||||
# --- Docker Volume for Persistent Data ---
|
|
||||||
volumes:
|
|
||||||
postgres_data:
|
|
||||||
|
|
||||||
# --- Docker Network for Inter-Container Communication ---
|
# --- Docker Network for Inter-Container Communication ---
|
||||||
networks:
|
networks:
|
||||||
|
|||||||
61
pom.xml
61
pom.xml
@@ -1,22 +1,28 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>3.4.3</version>
|
<version>3.4.3</version>
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
<relativePath/>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<groupId>group.goforward</groupId>
|
<groupId>group.goforward</groupId>
|
||||||
<artifactId>ballistic</artifactId>
|
<artifactId>ballistic</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<name>ballistic</name>
|
<name>ballistic</name>
|
||||||
<description>Ballistic Builder API</description>
|
<description>Ballistic Builder API</description>
|
||||||
|
|
||||||
<url/>
|
<url/>
|
||||||
|
|
||||||
<licenses>
|
<licenses>
|
||||||
<license/>
|
<license/>
|
||||||
</licenses>
|
</licenses>
|
||||||
|
|
||||||
<developers>
|
<developers>
|
||||||
<developer>
|
<developer>
|
||||||
<name>Don Strawsburg</name>
|
<name>Don Strawsburg</name>
|
||||||
@@ -29,69 +35,101 @@
|
|||||||
<organization>Forward Group, LLC</organization>
|
<organization>Forward Group, LLC</organization>
|
||||||
</developer>
|
</developer>
|
||||||
</developers>
|
</developers>
|
||||||
|
|
||||||
<scm>
|
<scm>
|
||||||
<connection></connection>
|
<connection></connection>
|
||||||
<developerConnection>scm:git:https://gitea.gofwd.group/Forward_Group/ballistic-builder-spring.git</developerConnection>
|
<developerConnection>scm:git:https://gitea.gofwd.group/Forward_Group/ballistic-builder-spring.git</developerConnection>
|
||||||
<tag/>
|
<tag/>
|
||||||
<url/>
|
<url/>
|
||||||
</scm>
|
</scm>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
<maven.compiler.source>${java.version}</maven.compiler.source>
|
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||||
<maven.compiler.target>${java.version}</maven.compiler.target>
|
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- <dependency>
|
|
||||||
|
<!--
|
||||||
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-data-rest</artifactId>
|
<artifactId>spring-boot-starter-data-rest</artifactId>
|
||||||
</dependency>-->
|
</dependency>
|
||||||
|
-->
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-devtools</artifactId>
|
<artifactId>spring-boot-devtools</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
<optional>true</optional>
|
<optional>true</optional>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springdoc</groupId>
|
<groupId>org.springdoc</groupId>
|
||||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||||
<version>2.8.5</version>
|
<version>2.8.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!--<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
<!-- Jakarta persistence API (optional, JPA starter already brings it transitively) -->
|
||||||
<artifactId>spring-boot-docker-compose</artifactId>
|
|
||||||
<scope>runtime</scope>
|
|
||||||
<optional>true</optional>
|
|
||||||
</dependency>-->
|
|
||||||
<!-- Jakarta / validation API is pulled by starters; explicit jakarta persistence if needed -->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>jakarta.persistence</groupId>
|
<groupId>jakarta.persistence</groupId>
|
||||||
<artifactId>jakarta.persistence-api</artifactId>
|
<artifactId>jakarta.persistence-api</artifactId>
|
||||||
<version>3.1.0</version>
|
<version>3.1.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.postgresql</groupId>
|
<groupId>org.postgresql</groupId>
|
||||||
<artifactId>postgresql</artifactId>
|
<artifactId>postgresql</artifactId>
|
||||||
<version>42.7.7</version>
|
<version>42.7.7</version>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-csv</artifactId>
|
<artifactId>commons-csv</artifactId>
|
||||||
<version>1.11.0</version>
|
<version>1.11.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Spring Security -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- JSON Web Tokens (JJWT) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-api</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-impl</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-jackson</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@@ -105,6 +143,7 @@
|
|||||||
<target>${maven.compiler.target}</target>
|
<target>${maven.compiler.target}</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
|||||||
@@ -3,15 +3,11 @@ package group.goforward.ballistic;
|
|||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||||
import org.springframework.context.annotation.ComponentScan;
|
|
||||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
|
||||||
import org.springframework.cache.annotation.EnableCaching;
|
import org.springframework.cache.annotation.EnableCaching;
|
||||||
|
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableCaching
|
@EnableCaching
|
||||||
@ComponentScan("group.goforward.ballistic.controllers")
|
|
||||||
@ComponentScan("group.goforward.ballistic.repos")
|
|
||||||
@ComponentScan("group.goforward.ballistic.services")
|
|
||||||
@EntityScan(basePackages = "group.goforward.ballistic.model")
|
@EntityScan(basePackages = "group.goforward.ballistic.model")
|
||||||
@EnableJpaRepositories(basePackages = "group.goforward.ballistic.repos")
|
@EnableJpaRepositories(basePackages = "group.goforward.ballistic.repos")
|
||||||
public class BallisticApplication {
|
public class BallisticApplication {
|
||||||
|
|||||||
@@ -30,13 +30,8 @@ public class CorsConfig {
|
|||||||
"https://localhost:8080",
|
"https://localhost:8080",
|
||||||
"http://localhost:3000",
|
"http://localhost:3000",
|
||||||
"https://localhost:3000",
|
"https://localhost:3000",
|
||||||
"http://192.168.11.210:8070",
|
"https://localhost:3000/gunbuilder",
|
||||||
"https://192.168.11.210:8070",
|
"http://localhost:3000/gunbuilder"
|
||||||
"http://citysites.gofwd.group",
|
|
||||||
"https://citysites.gofwd.group",
|
|
||||||
"http://citysites.gofwd.group:8070",
|
|
||||||
"https://citysites.gofwd.group:8070"
|
|
||||||
|
|
||||||
));
|
));
|
||||||
|
|
||||||
// Allow all headers
|
// Allow all headers
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package group.goforward.ballistic.configuration;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
// @Configuration
|
||||||
|
// public class PasswordConfig {
|
||||||
|
|
||||||
|
// @Bean
|
||||||
|
// public PasswordEncoder passwordEncoder() {
|
||||||
|
// // BCrypt default password
|
||||||
|
// return new BCryptPasswordEncoder();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package group.goforward.ballistic.configuration;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
public class SecurityConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.csrf(AbstractHttpConfigurer::disable)
|
||||||
|
.sessionManagement(sm ->
|
||||||
|
sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||||
|
)
|
||||||
|
.authorizeHttpRequests(auth -> auth
|
||||||
|
// Auth endpoints always open
|
||||||
|
.requestMatchers("/api/auth/**").permitAll()
|
||||||
|
// Swagger / docs
|
||||||
|
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
|
||||||
|
// Health
|
||||||
|
.requestMatchers("/actuator/health", "/actuator/info").permitAll()
|
||||||
|
// Public product endpoints
|
||||||
|
.requestMatchers("/api/products/gunbuilder/**").permitAll()
|
||||||
|
// Everything else (for now) also open – we can tighten later
|
||||||
|
.anyRequest().permitAll()
|
||||||
|
);
|
||||||
|
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
// BCrypt is a solid default for user passwords
|
||||||
|
return new BCryptPasswordEncoder();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AuthenticationManager authenticationManager(
|
||||||
|
AuthenticationConfiguration configuration
|
||||||
|
) throws Exception {
|
||||||
|
return configuration.getAuthenticationManager();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package group.goforward.ballistic.controllers;
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.User;
|
||||||
|
import group.goforward.ballistic.repos.UserRepository;
|
||||||
|
import group.goforward.ballistic.security.JwtService;
|
||||||
|
import group.goforward.ballistic.web.dto.auth.AuthResponse;
|
||||||
|
import group.goforward.ballistic.web.dto.auth.LoginRequest;
|
||||||
|
import group.goforward.ballistic.web.dto.auth.RegisterRequest;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/auth")
|
||||||
|
@CrossOrigin
|
||||||
|
public class AuthController {
|
||||||
|
|
||||||
|
private final UserRepository users;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final JwtService jwtService;
|
||||||
|
|
||||||
|
public AuthController(
|
||||||
|
UserRepository users,
|
||||||
|
PasswordEncoder passwordEncoder,
|
||||||
|
JwtService jwtService
|
||||||
|
) {
|
||||||
|
this.users = users;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/register")
|
||||||
|
public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
|
||||||
|
String email = request.getEmail().trim().toLowerCase();
|
||||||
|
|
||||||
|
if (users.existsByEmailIgnoreCaseAndDeletedAtIsNull(email)) {
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.CONFLICT)
|
||||||
|
.body("Email is already registered");
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
// Let DB generate id
|
||||||
|
user.setUuid(UUID.randomUUID());
|
||||||
|
user.setEmail(email);
|
||||||
|
user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
|
||||||
|
user.setDisplayName(request.getDisplayName());
|
||||||
|
user.setRole("USER");
|
||||||
|
user.setIsActive(true);
|
||||||
|
user.setCreatedAt(OffsetDateTime.now());
|
||||||
|
user.setUpdatedAt(OffsetDateTime.now());
|
||||||
|
|
||||||
|
users.save(user);
|
||||||
|
|
||||||
|
String token = jwtService.generateToken(user);
|
||||||
|
|
||||||
|
AuthResponse response = new AuthResponse(
|
||||||
|
token,
|
||||||
|
user.getEmail(),
|
||||||
|
user.getDisplayName(),
|
||||||
|
user.getRole()
|
||||||
|
);
|
||||||
|
|
||||||
|
return ResponseEntity.status(HttpStatus.CREATED).body(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/login")
|
||||||
|
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
|
||||||
|
String email = request.getEmail().trim().toLowerCase();
|
||||||
|
|
||||||
|
User user = users.findByEmailIgnoreCaseAndDeletedAtIsNull(email)
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (user == null || !user.getIsActive()) {
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
user.setLastLoginAt(OffsetDateTime.now());
|
||||||
|
user.incrementLoginCount();
|
||||||
|
user.setUpdatedAt(OffsetDateTime.now());
|
||||||
|
users.save(user);
|
||||||
|
|
||||||
|
String token = jwtService.generateToken(user);
|
||||||
|
|
||||||
|
AuthResponse response = new AuthResponse(
|
||||||
|
token,
|
||||||
|
user.getEmail(),
|
||||||
|
user.getDisplayName(),
|
||||||
|
user.getRole()
|
||||||
|
);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package group.goforward.ballistic.controllers;
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.Brand;
|
||||||
|
import group.goforward.ballistic.model.State;
|
||||||
|
import group.goforward.ballistic.repos.BrandRepository;
|
||||||
|
import group.goforward.ballistic.services.BrandService;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/brands")
|
||||||
|
public class BrandController {
|
||||||
|
@Autowired
|
||||||
|
private BrandRepository repo;
|
||||||
|
@Autowired
|
||||||
|
private BrandService brandService;
|
||||||
|
//@Cacheable(value="getAllStates")
|
||||||
|
@GetMapping("/all")
|
||||||
|
public ResponseEntity<List<Brand>> getAllBrands() {
|
||||||
|
List<Brand> brand = repo.findAll();
|
||||||
|
return ResponseEntity.ok(brand);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ResponseEntity<Brand> getAllBrandsById(@PathVariable Integer id) {
|
||||||
|
return repo.findById(id)
|
||||||
|
.map(ResponseEntity::ok)
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/add")
|
||||||
|
public ResponseEntity<Brand> createbrand(@RequestBody Brand item) {
|
||||||
|
Brand created = brandService.save(item);
|
||||||
|
return ResponseEntity.status(HttpStatus.CREATED).body(created);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/delete/{id}")
|
||||||
|
public ResponseEntity<Void> deleteItem(@PathVariable Integer id) {
|
||||||
|
return brandService.findById(id)
|
||||||
|
.map(item -> {
|
||||||
|
brandService.deleteById(id);
|
||||||
|
return ResponseEntity.noContent().<Void>build();
|
||||||
|
})
|
||||||
|
.orElse(ResponseEntity.notFound().build());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import group.goforward.ballistic.model.State;
|
|||||||
import group.goforward.ballistic.repos.StateRepository;
|
import group.goforward.ballistic.repos.StateRepository;
|
||||||
import group.goforward.ballistic.services.StatesService;
|
import group.goforward.ballistic.services.StatesService;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.cache.annotation.Cacheable;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
@@ -13,44 +14,38 @@ import java.util.List;
|
|||||||
|
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping()
|
@RequestMapping("/api/states")
|
||||||
public class StateController {
|
public class StateController {
|
||||||
@Autowired
|
@Autowired
|
||||||
private StateRepository repo;
|
private StateRepository repo;
|
||||||
@Autowired
|
@Autowired
|
||||||
private StatesService statesService;
|
private StatesService statesService;
|
||||||
|
//@Cacheable(value="getAllStates")
|
||||||
@GetMapping("/api/getAllStates")
|
@GetMapping("/all")
|
||||||
public ResponseEntity<List<State>> getAllStates() {
|
public ResponseEntity<List<State>> getAllStates() {
|
||||||
List<State> state = repo.findAll();
|
List<State> state = repo.findAll();
|
||||||
return ResponseEntity.ok(state);
|
return ResponseEntity.ok(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/api/getAllStatesTest")
|
@GetMapping("/{id}")
|
||||||
public ApiResponse<List<State>> getAllStatesTest() {
|
|
||||||
List<State> state = repo.findAll();
|
|
||||||
return ApiResponse.success(state);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/api/getAllStatesById/{id}")
|
|
||||||
public ResponseEntity<State> getAllStatesById(@PathVariable Integer id) {
|
public ResponseEntity<State> getAllStatesById(@PathVariable Integer id) {
|
||||||
return repo.findById(id)
|
return repo.findById(id)
|
||||||
.map(ResponseEntity::ok)
|
.map(ResponseEntity::ok)
|
||||||
.orElse(ResponseEntity.notFound().build());
|
.orElse(ResponseEntity.notFound().build());
|
||||||
}
|
}
|
||||||
@GetMapping("/api/getAllStatesByAbbreviation/{abbreviation}")
|
@GetMapping("/byAbbrev/{abbreviation}")
|
||||||
public ResponseEntity<State> getAllStatesByAbbreviation(@PathVariable String abbreviation) {
|
public ResponseEntity<State> getAllStatesByAbbreviation(@PathVariable String abbreviation) {
|
||||||
return repo.findByAbbreviation(abbreviation)
|
return repo.findByAbbreviation(abbreviation)
|
||||||
.map(ResponseEntity::ok)
|
.map(ResponseEntity::ok)
|
||||||
.orElse(ResponseEntity.notFound().build());
|
.orElse(ResponseEntity.notFound().build());
|
||||||
}
|
}
|
||||||
@PostMapping("/api/addState")
|
@PostMapping("/addState")
|
||||||
public ResponseEntity<State> createState(@RequestBody State item) {
|
public ResponseEntity<State> createState(@RequestBody State item) {
|
||||||
State created = statesService.save(item);
|
State created = statesService.save(item);
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(created);
|
return ResponseEntity.status(HttpStatus.CREATED).body(created);
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/api/deleteState/{id}")
|
@DeleteMapping("/deleteState/{id}")
|
||||||
public ResponseEntity<Void> deleteItem(@PathVariable Integer id) {
|
public ResponseEntity<Void> deleteItem(@PathVariable Integer id) {
|
||||||
return statesService.findById(id)
|
return statesService.findById(id)
|
||||||
.map(item -> {
|
.map(item -> {
|
||||||
|
|||||||
@@ -12,33 +12,36 @@ import java.util.List;
|
|||||||
|
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping()
|
@RequestMapping("/api/user")
|
||||||
public class UserController {
|
public class UserController {
|
||||||
@Autowired
|
private final UserRepository repo;
|
||||||
private UserRepository repo;
|
private final UsersService usersService;
|
||||||
@Autowired
|
|
||||||
private UsersService usersService;
|
|
||||||
|
|
||||||
@GetMapping("/api/getAllUsers")
|
public UserController(UserRepository repo, UsersService usersService) {
|
||||||
|
this.repo = repo;
|
||||||
|
this.usersService = usersService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/all")
|
||||||
public ResponseEntity<List<User>> getAllUsers() {
|
public ResponseEntity<List<User>> getAllUsers() {
|
||||||
List<User> data = repo.findAll();
|
List<User> data = repo.findAll();
|
||||||
return ResponseEntity.ok(data);
|
return ResponseEntity.ok(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@GetMapping("/api/getAllUsersById/{id}")
|
@GetMapping("/byId/{id}")
|
||||||
public ResponseEntity<User> getAllStatesById(@PathVariable Integer id) {
|
public ResponseEntity<User> getAllStatesById(@PathVariable Integer id) {
|
||||||
return repo.findById(id)
|
return repo.findById(id)
|
||||||
.map(ResponseEntity::ok)
|
.map(ResponseEntity::ok)
|
||||||
.orElse(ResponseEntity.notFound().build());
|
.orElse(ResponseEntity.notFound().build());
|
||||||
}
|
}
|
||||||
@PostMapping("/api/addUser")
|
@PostMapping("/addUser")
|
||||||
public ResponseEntity<User> createUser(@RequestBody User item) {
|
public ResponseEntity<User> createUser(@RequestBody User item) {
|
||||||
User created = usersService.save(item);
|
User created = usersService.save(item);
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(created);
|
return ResponseEntity.status(HttpStatus.CREATED).body(created);
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/api/deleteUser/{id}")
|
@DeleteMapping("/deleteUser/{id}")
|
||||||
public ResponseEntity<Void> deleteItem(@PathVariable Integer id) {
|
public ResponseEntity<Void> deleteItem(@PathVariable Integer id) {
|
||||||
return usersService.findById(id)
|
return usersService.findById(id)
|
||||||
.map(item -> {
|
.map(item -> {
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package group.goforward.ballistic.model;
|
package group.goforward.ballistic.model;
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.*;
|
||||||
import jakarta.persistence.Entity;
|
|
||||||
import jakarta.persistence.Id;
|
|
||||||
import jakarta.persistence.Table;
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
import org.hibernate.annotations.ColumnDefault;
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
|
|
||||||
@@ -13,8 +10,9 @@ import java.util.UUID;
|
|||||||
@Entity
|
@Entity
|
||||||
@Table(name = "users")
|
@Table(name = "users")
|
||||||
public class User {
|
public class User {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@NotNull
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(name = "id", nullable = false)
|
@Column(name = "id", nullable = false)
|
||||||
private Integer id;
|
private Integer id;
|
||||||
|
|
||||||
@@ -42,7 +40,7 @@ public class User {
|
|||||||
@NotNull
|
@NotNull
|
||||||
@ColumnDefault("true")
|
@ColumnDefault("true")
|
||||||
@Column(name = "is_active", nullable = false)
|
@Column(name = "is_active", nullable = false)
|
||||||
private Boolean isActive = false;
|
private boolean isActive = true;
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@ColumnDefault("now()")
|
@ColumnDefault("now()")
|
||||||
@@ -57,6 +55,29 @@ public class User {
|
|||||||
@Column(name = "deleted_at")
|
@Column(name = "deleted_at")
|
||||||
private OffsetDateTime deletedAt;
|
private OffsetDateTime deletedAt;
|
||||||
|
|
||||||
|
// NEW FIELDS
|
||||||
|
|
||||||
|
@Column(name = "email_verified_at")
|
||||||
|
private OffsetDateTime emailVerifiedAt;
|
||||||
|
|
||||||
|
@Column(name = "verification_token", length = Integer.MAX_VALUE)
|
||||||
|
private String verificationToken;
|
||||||
|
|
||||||
|
@Column(name = "reset_password_token", length = Integer.MAX_VALUE)
|
||||||
|
private String resetPasswordToken;
|
||||||
|
|
||||||
|
@Column(name = "reset_password_expires_at")
|
||||||
|
private OffsetDateTime resetPasswordExpiresAt;
|
||||||
|
|
||||||
|
@Column(name = "last_login_at")
|
||||||
|
private OffsetDateTime lastLoginAt;
|
||||||
|
|
||||||
|
@ColumnDefault("0")
|
||||||
|
@Column(name = "login_count", nullable = false)
|
||||||
|
private Integer loginCount = 0;
|
||||||
|
|
||||||
|
// --- Getters / setters ---
|
||||||
|
|
||||||
public Integer getId() {
|
public Integer getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
@@ -105,12 +126,12 @@ public class User {
|
|||||||
this.role = role;
|
this.role = role;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Boolean getIsActive() {
|
public boolean getIsActive() {
|
||||||
return isActive;
|
return isActive;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setIsActive(Boolean isActive) {
|
public void setIsActive(boolean active) {
|
||||||
this.isActive = isActive;
|
isActive = active;
|
||||||
}
|
}
|
||||||
|
|
||||||
public OffsetDateTime getCreatedAt() {
|
public OffsetDateTime getCreatedAt() {
|
||||||
@@ -137,4 +158,65 @@ public class User {
|
|||||||
this.deletedAt = deletedAt;
|
this.deletedAt = deletedAt;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public OffsetDateTime getEmailVerifiedAt() {
|
||||||
|
return emailVerifiedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmailVerifiedAt(OffsetDateTime emailVerifiedAt) {
|
||||||
|
this.emailVerifiedAt = emailVerifiedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getVerificationToken() {
|
||||||
|
return verificationToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setVerificationToken(String verificationToken) {
|
||||||
|
this.verificationToken = verificationToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getResetPasswordToken() {
|
||||||
|
return resetPasswordToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setResetPasswordToken(String resetPasswordToken) {
|
||||||
|
this.resetPasswordToken = resetPasswordToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public OffsetDateTime getResetPasswordExpiresAt() {
|
||||||
|
return resetPasswordExpiresAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setResetPasswordExpiresAt(OffsetDateTime resetPasswordExpiresAt) {
|
||||||
|
this.resetPasswordExpiresAt = resetPasswordExpiresAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public OffsetDateTime getLastLoginAt() {
|
||||||
|
return lastLoginAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLastLoginAt(OffsetDateTime lastLoginAt) {
|
||||||
|
this.lastLoginAt = lastLoginAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getLoginCount() {
|
||||||
|
return loginCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLoginCount(Integer loginCount) {
|
||||||
|
this.loginCount = loginCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// convenience helpers
|
||||||
|
|
||||||
|
@Transient
|
||||||
|
public boolean isEmailVerified() {
|
||||||
|
return emailVerifiedAt != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void incrementLoginCount() {
|
||||||
|
if (loginCount == null) {
|
||||||
|
loginCount = 0;
|
||||||
|
}
|
||||||
|
loginCount++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,10 +2,15 @@ package group.goforward.ballistic.repos;
|
|||||||
|
|
||||||
import group.goforward.ballistic.model.User;
|
import group.goforward.ballistic.model.User;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface UserRepository extends JpaRepository<User, Integer> {
|
public interface UserRepository extends JpaRepository<User, Integer> {
|
||||||
Optional<User> findByEmail(String email);
|
|
||||||
|
Optional<User> findByEmailIgnoreCaseAndDeletedAtIsNull(String email);
|
||||||
|
|
||||||
|
boolean existsByEmailIgnoreCaseAndDeletedAtIsNull(String email);
|
||||||
|
|
||||||
Optional<User> findByUuid(UUID uuid);
|
Optional<User> findByUuid(UUID uuid);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package group.goforward.ballistic.security;
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.User;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class CustomUserDetails implements UserDetails {
|
||||||
|
|
||||||
|
private final User user;
|
||||||
|
private final List<GrantedAuthority> authorities;
|
||||||
|
|
||||||
|
public CustomUserDetails(User user) {
|
||||||
|
this.user = user;
|
||||||
|
this.authorities = List.of(new SimpleGrantedAuthority("ROLE_" + user.getRole()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public User getUser() {
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||||
|
return authorities;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getPassword() {
|
||||||
|
return user.getPasswordHash();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getUsername() {
|
||||||
|
return user.getEmail();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonExpired() {
|
||||||
|
return user.getDeletedAt() == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonLocked() {
|
||||||
|
return user.getIsActive();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isCredentialsNonExpired() {
|
||||||
|
return user.getDeletedAt() == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return user.getIsActive() && user.getDeletedAt() == null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package group.goforward.ballistic.security;
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.User;
|
||||||
|
import group.goforward.ballistic.repos.UserRepository;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CustomUserDetailsService implements UserDetailsService {
|
||||||
|
|
||||||
|
private final UserRepository users;
|
||||||
|
|
||||||
|
public CustomUserDetailsService(UserRepository users) {
|
||||||
|
this.users = users;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||||
|
User user = users.findByEmailIgnoreCaseAndDeletedAtIsNull(email)
|
||||||
|
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||||
|
return new CustomUserDetails(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package group.goforward.ballistic.security;
|
||||||
|
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void commence(
|
||||||
|
HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
AuthenticationException authException
|
||||||
|
) throws IOException, ServletException {
|
||||||
|
// Simple JSON 401 response
|
||||||
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
response.setContentType("application/json");
|
||||||
|
response.getWriter().write("{\"error\":\"Unauthorized\"}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package group.goforward.ballistic.security;
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.User;
|
||||||
|
import group.goforward.ballistic.repos.UserRepository;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private final JwtService jwtService;
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
public JwtAuthenticationFilter(JwtService jwtService, UserRepository userRepository) {
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(
|
||||||
|
HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
FilterChain filterChain
|
||||||
|
) throws ServletException, IOException {
|
||||||
|
|
||||||
|
String authHeader = request.getHeader("Authorization");
|
||||||
|
|
||||||
|
if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
|
||||||
|
if (!jwtService.isTokenValid(token)) {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
UUID userUuid = jwtService.extractUserUuid(token);
|
||||||
|
|
||||||
|
if (userUuid == null || SecurityContextHolder.getContext().getAuthentication() != null) {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = userRepository.findByUuid(userUuid)
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (user == null || !user.getIsActive()) {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
CustomUserDetails userDetails = new CustomUserDetails(user);
|
||||||
|
|
||||||
|
UsernamePasswordAuthenticationToken authToken =
|
||||||
|
new UsernamePasswordAuthenticationToken(
|
||||||
|
userDetails,
|
||||||
|
null,
|
||||||
|
userDetails.getAuthorities()
|
||||||
|
);
|
||||||
|
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||||
|
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||||
|
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package group.goforward.ballistic.security;
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.User;
|
||||||
|
import io.jsonwebtoken.Claims;
|
||||||
|
import io.jsonwebtoken.Jwts;
|
||||||
|
import io.jsonwebtoken.JwtException;
|
||||||
|
import io.jsonwebtoken.SignatureAlgorithm;
|
||||||
|
import io.jsonwebtoken.security.Keys;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.security.Key;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class JwtService {
|
||||||
|
|
||||||
|
private final Key key;
|
||||||
|
private final long accessTokenMinutes;
|
||||||
|
|
||||||
|
public JwtService(
|
||||||
|
@Value("${security.jwt.secret}") String secret,
|
||||||
|
@Value("${security.jwt.access-token-minutes:60}") long accessTokenMinutes
|
||||||
|
) {
|
||||||
|
this.key = Keys.hmacShaKeyFor(secret.getBytes());
|
||||||
|
this.accessTokenMinutes = accessTokenMinutes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String generateToken(User user) {
|
||||||
|
Instant now = Instant.now();
|
||||||
|
Instant expiry = now.plus(accessTokenMinutes, ChronoUnit.MINUTES);
|
||||||
|
|
||||||
|
return Jwts.builder()
|
||||||
|
.setSubject(user.getUuid().toString())
|
||||||
|
.setIssuedAt(Date.from(now))
|
||||||
|
.setExpiration(Date.from(expiry))
|
||||||
|
.addClaims(Map.of(
|
||||||
|
"email", user.getEmail(),
|
||||||
|
"role", user.getRole(),
|
||||||
|
"displayName", user.getDisplayName()
|
||||||
|
))
|
||||||
|
.signWith(key, SignatureAlgorithm.HS256)
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID extractUserUuid(String token) {
|
||||||
|
Claims claims = parseClaims(token);
|
||||||
|
return UUID.fromString(claims.getSubject());
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTokenValid(String token) {
|
||||||
|
try {
|
||||||
|
parseClaims(token);
|
||||||
|
return true;
|
||||||
|
} catch (JwtException | IllegalArgumentException ex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Claims parseClaims(String token) {
|
||||||
|
return Jwts.parserBuilder()
|
||||||
|
.setSigningKey(key)
|
||||||
|
.build()
|
||||||
|
.parseClaimsJws(token)
|
||||||
|
.getBody();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package group.goforward.ballistic.services;
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.Brand;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface BrandService {
|
||||||
|
|
||||||
|
List<Brand> findAll();
|
||||||
|
|
||||||
|
Optional<Brand> findById(Integer id);
|
||||||
|
|
||||||
|
Brand save(Brand item);
|
||||||
|
void deleteById(Integer id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package group.goforward.ballistic.services.impl;
|
||||||
|
|
||||||
|
|
||||||
|
import group.goforward.ballistic.model.Brand;
|
||||||
|
import group.goforward.ballistic.repos.BrandRepository;
|
||||||
|
import group.goforward.ballistic.services.BrandService;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class BrandServiceImpl implements BrandService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private BrandRepository repo;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Brand> findAll() {
|
||||||
|
return repo.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<Brand> findById(Integer id) {
|
||||||
|
return repo.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Brand save(Brand item) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteById(Integer id) {
|
||||||
|
deleteById(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package group.goforward.ballistic.web.dto.auth;
|
||||||
|
|
||||||
|
public class AuthResponse {
|
||||||
|
private String token;
|
||||||
|
private String email;
|
||||||
|
private String displayName;
|
||||||
|
private String role;
|
||||||
|
|
||||||
|
public AuthResponse() {}
|
||||||
|
|
||||||
|
public AuthResponse(String token, String email, String displayName, String role) {
|
||||||
|
this.token = token;
|
||||||
|
this.email = email;
|
||||||
|
this.displayName = displayName;
|
||||||
|
this.role = role;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getToken() {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setToken(String token) {
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDisplayName() {
|
||||||
|
return displayName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDisplayName(String displayName) {
|
||||||
|
this.displayName = displayName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRole() {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRole(String role) {
|
||||||
|
this.role = role;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package group.goforward.ballistic.web.dto.auth;
|
||||||
|
|
||||||
|
public class LoginRequest {
|
||||||
|
private String email;
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package group.goforward.ballistic.web.dto.auth;
|
||||||
|
|
||||||
|
public class RegisterRequest {
|
||||||
|
private String email;
|
||||||
|
private String password;
|
||||||
|
private String displayName;
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDisplayName() {
|
||||||
|
return displayName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDisplayName(String displayName) {
|
||||||
|
this.displayName = displayName;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,3 +9,6 @@ spring.datasource.driver-class-name=org.postgresql.Driver
|
|||||||
#spring.jpa.hibernate.ddl-auto=update
|
#spring.jpa.hibernate.ddl-auto=update
|
||||||
spring.jpa.show-sql=true
|
spring.jpa.show-sql=true
|
||||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||||
|
|
||||||
|
security.jwt.secret=ballistic-test-secret-key-1234567890-ABCDEFGHIJKLNMOPQRST
|
||||||
|
security.jwt.access-token-minutes=2880
|
||||||
@@ -3,7 +3,7 @@ package group.goforward.ballistic;
|
|||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
|
||||||
@SpringBootTest
|
// @SpringBootTest
|
||||||
class BallisticApplicationTests {
|
class BallisticApplicationTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
Reference in New Issue
Block a user