From 3ae568ef4cc608fb9002306981a1eaca5e50ad3c Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 14:05:43 +0300 Subject: [PATCH 01/15] Add authentication, security, and JWT functionality Implement foundational authentication features, including user and role management, JWT-based authentication, and role-based security configurations. Add REST endpoints for login, signup, and logout, along with a Dockerized development setup, CI/CD workflows, and logging configurations. --- .github/workflows/ci-cd.yml | 14 +++ .github/workflows/linter.yml | 12 +++ docker-compose.yml | 46 ++++++++++ promtail-config.yml | 18 ++++ .../controller/AuthenticationController.java | 72 +++++++++++++++ .../com/podzilla/auth/dto/LoginRequest.java | 9 ++ .../com/podzilla/auth/dto/SignupRequest.java | 10 +++ .../java/com/podzilla/auth/model/ERole.java | 6 ++ .../java/com/podzilla/auth/model/Role.java | 29 ++++++ .../java/com/podzilla/auth/model/User.java | 58 ++++++++++++ .../auth/repository/RoleRepository.java | 13 +++ .../auth/repository/UserRepository.java | 13 +++ .../security/JWTAuthenticationFilter.java | 71 +++++++++++++++ .../RestAuthenticationEntryPoint.java | 22 +++++ .../auth/security/SecurityConfig.java | 75 ++++++++++++++++ .../auth/service/AuthenticationService.java | 80 +++++++++++++++++ .../service/CustomUserDetailsService.java | 47 ++++++++++ .../com/podzilla/auth/service/JWTService.java | 90 +++++++++++++++++++ src/main/resources/logback-spring.xml | 15 ++++ 19 files changed, 700 insertions(+) create mode 100644 .github/workflows/ci-cd.yml create mode 100644 .github/workflows/linter.yml create mode 100644 docker-compose.yml create mode 100644 promtail-config.yml create mode 100644 src/main/java/com/podzilla/auth/controller/AuthenticationController.java create mode 100644 src/main/java/com/podzilla/auth/dto/LoginRequest.java create mode 100644 src/main/java/com/podzilla/auth/dto/SignupRequest.java create mode 100644 src/main/java/com/podzilla/auth/model/ERole.java create mode 100644 src/main/java/com/podzilla/auth/model/Role.java create mode 100644 src/main/java/com/podzilla/auth/model/User.java create mode 100644 src/main/java/com/podzilla/auth/repository/RoleRepository.java create mode 100644 src/main/java/com/podzilla/auth/repository/UserRepository.java create mode 100644 src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java create mode 100644 src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java create mode 100644 src/main/java/com/podzilla/auth/security/SecurityConfig.java create mode 100644 src/main/java/com/podzilla/auth/service/AuthenticationService.java create mode 100644 src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java create mode 100644 src/main/java/com/podzilla/auth/service/JWTService.java create mode 100644 src/main/resources/logback-spring.xml diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml new file mode 100644 index 0000000..9dbaf62 --- /dev/null +++ b/.github/workflows/ci-cd.yml @@ -0,0 +1,14 @@ +name: Use Template Java CI/CD + +on: + push: + branches: [ "main", "dev" ] + pull_request: + branches: [ "**" ] + +jobs: + call-ci: + uses: Podzilla/templates/.github/workflows/ci.yml@main + with: + branch: 'refs/head/main' # <<< Passes the branch name dynamically + secrets: inherit \ No newline at end of file diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml new file mode 100644 index 0000000..c9ed1da --- /dev/null +++ b/.github/workflows/linter.yml @@ -0,0 +1,12 @@ +name: Use Template Linter + +on: + pull_request: + branches: [ "**" ] + +jobs: + call-linter: + uses: Podzilla/templates/.github/workflows/super-linter.yml@main + with: + branch: 'dev' + secrets: inherit \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ccc55e4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,46 @@ +services: + backend: + image: openjdk:25-ea-4-jdk-oraclelinux9 + ports: + - "8080:8080" + env_file: + - secret.env + depends_on: + - auth_db + environment: + - SPRING_DATASOURCE_URL=jdbc:postgresql://auth_db:5432/authDB + volumes: + - ./target:/app + - ./logs:/logs + command: [ "java", "-jar", "/app/auth-0.0.1-SNAPSHOT.jar" ] + + auth_db: + image: postgres:latest + environment: + POSTGRES_PASSWORD: 1234 + POSTGRES_USER: postgres + POSTGRES_DB: authDB + ports: + - "5432:5432" + + loki: + image: grafana/loki:latest + ports: + - "3100:3100" + command: -config.file=/etc/loki/local-config.yaml + + promtail: + image: grafana/promtail:latest + volumes: + - ./promtail-config.yml:/etc/promtail/promtail-config.yaml + - ./logs:/logs + command: -config.file=/etc/promtail/promtail-config.yaml + depends_on: + - loki + + grafana: + image: grafana/grafana:latest + ports: + - "3000:3000" + depends_on: + - loki diff --git a/promtail-config.yml b/promtail-config.yml new file mode 100644 index 0000000..5503c33 --- /dev/null +++ b/promtail-config.yml @@ -0,0 +1,18 @@ +server: + http_listen_port: 9080 + grpc_listen_port: 0 + +positions: + filename: /tmp/positions.yaml + +clients: + - url: http://loki:3100/loki/api/v1/push + +scrape_configs: + - job_name: spring-boot + static_configs: + - targets: + - localhost + labels: + job: spring-boot + __path__: ./logs/*.log diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java new file mode 100644 index 0000000..980f310 --- /dev/null +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -0,0 +1,72 @@ +package com.podzilla.auth.controller; + +import com.podzilla.auth.dto.LoginRequest; +import com.podzilla.auth.dto.SignupRequest; +import com.podzilla.auth.service.AuthenticationService; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/auth") +public class AuthenticationController { + + private final AuthenticationService authenticationService; + + private final SecurityContextLogoutHandler logoutHandler = + new SecurityContextLogoutHandler(); + + private static final Logger LOGGER = + LoggerFactory.getLogger(AuthenticationController.class); + + @Autowired + public AuthenticationController( + final AuthenticationService authenticationService) { + this.authenticationService = authenticationService; + } + + @PostMapping("/login") + public ResponseEntity login(@RequestBody final LoginRequest loginRequest, + final HttpServletResponse response) { + try { + String email = authenticationService.login(loginRequest, response); + LOGGER.info("User {} logged in", email); + return new ResponseEntity<>(email + " signed in", HttpStatus.OK); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + return new ResponseEntity<>(e.getMessage(), + HttpStatus.UNAUTHORIZED); + } + } + + @PostMapping("/signup") + public ResponseEntity registerUser( + @RequestBody final SignupRequest signupRequest, + final HttpServletRequest request) { + try { + authenticationService.registerAccount(signupRequest); + LOGGER.info("User {} registered", signupRequest.getEmail()); + return new ResponseEntity<>("Account registered.", + HttpStatus.CREATED); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + return new ResponseEntity<>(e.getMessage(), + HttpStatus.UNAUTHORIZED); + } + } + + @PostMapping("/signout") + public ResponseEntity logoutUser(final HttpServletResponse response) { + authenticationService.logoutUser(response); + return new ResponseEntity<>("You've been signed out!", HttpStatus.OK); + } +} diff --git a/src/main/java/com/podzilla/auth/dto/LoginRequest.java b/src/main/java/com/podzilla/auth/dto/LoginRequest.java new file mode 100644 index 0000000..dce141e --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/LoginRequest.java @@ -0,0 +1,9 @@ +package com.podzilla.auth.dto; + +import lombok.Data; + +@Data +public class LoginRequest { + private String email; + private String password; +} diff --git a/src/main/java/com/podzilla/auth/dto/SignupRequest.java b/src/main/java/com/podzilla/auth/dto/SignupRequest.java new file mode 100644 index 0000000..5749166 --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/SignupRequest.java @@ -0,0 +1,10 @@ +package com.podzilla.auth.dto; + +import lombok.Data; + +@Data +public class SignupRequest { + private String name; + private String email; + private String password; +} diff --git a/src/main/java/com/podzilla/auth/model/ERole.java b/src/main/java/com/podzilla/auth/model/ERole.java new file mode 100644 index 0000000..e877932 --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/ERole.java @@ -0,0 +1,6 @@ +package com.podzilla.auth.model; + +public enum ERole { + ROLE_USER, + ROLE_ADMIN +} diff --git a/src/main/java/com/podzilla/auth/model/Role.java b/src/main/java/com/podzilla/auth/model/Role.java new file mode 100644 index 0000000..4a52c5d --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/Role.java @@ -0,0 +1,29 @@ +package com.podzilla.auth.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Data +@NoArgsConstructor +@Table(name = "roles") +public class Role { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + private ERole erole = ERole.ROLE_USER; + + public Role(final ERole erole) { + this.erole = erole; + } +} diff --git a/src/main/java/com/podzilla/auth/model/User.java b/src/main/java/com/podzilla/auth/model/User.java new file mode 100644 index 0000000..35de90b --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/User.java @@ -0,0 +1,58 @@ +package com.podzilla.auth.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; + +import java.util.HashSet; +import java.util.Set; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "users") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @NotBlank(message = "Name is required") + private String name; + + @NotBlank(message = "email is required") + @Email + @Column(unique = true) + private String email; + + @NotBlank(message = "Password is required") + private String password; + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "users_roles", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id")) + private Set roles = new HashSet<>(); + + public User(final String name, final String email, + final String password) { + this.name = name; + this.email = email; + this.password = password; + } +} diff --git a/src/main/java/com/podzilla/auth/repository/RoleRepository.java b/src/main/java/com/podzilla/auth/repository/RoleRepository.java new file mode 100644 index 0000000..5a09f21 --- /dev/null +++ b/src/main/java/com/podzilla/auth/repository/RoleRepository.java @@ -0,0 +1,13 @@ +package com.podzilla.auth.repository; + +import com.podzilla.auth.model.ERole; +import com.podzilla.auth.model.Role; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface RoleRepository extends JpaRepository { + Optional findByErole(ERole eRole); +} diff --git a/src/main/java/com/podzilla/auth/repository/UserRepository.java b/src/main/java/com/podzilla/auth/repository/UserRepository.java new file mode 100644 index 0000000..93626e6 --- /dev/null +++ b/src/main/java/com/podzilla/auth/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.podzilla.auth.repository; + +import com.podzilla.auth.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserRepository extends JpaRepository { + Optional findByEmail(String email); + Boolean existsByEmail(String email); +} diff --git a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java new file mode 100644 index 0000000..b81e7e2 --- /dev/null +++ b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java @@ -0,0 +1,71 @@ +package com.podzilla.auth.security; + +import com.podzilla.auth.service.CustomUserDetailsService; +import com.podzilla.auth.service.JWTService; +import io.micrometer.common.lang.NonNullApi; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@NonNullApi +@Component +public class JWTAuthenticationFilter extends OncePerRequestFilter { + private final JWTService jwtService; + private final CustomUserDetailsService customUserDetailsService; + + public JWTAuthenticationFilter( + final JWTService jwtService, + final CustomUserDetailsService customUserDetailsService) { + this.jwtService = jwtService; + this.customUserDetailsService = customUserDetailsService; + } + + private static final Logger LOGGER = + LoggerFactory.getLogger(JWTAuthenticationFilter.class); + + @Override + protected void doFilterInternal(final HttpServletRequest request, + final HttpServletResponse response, + final FilterChain filterChain) + throws ServletException, IOException { + + try { + String jwt = jwtService.getJwtFromCookie(request); + jwtService.validateToken(jwt); + String userEmail = jwtService.extractEmail(); + + UserDetails userDetails = + customUserDetailsService.loadUserByUsername(userEmail); + + UsernamePasswordAuthenticationToken authToken = + new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities()); + authToken.setDetails( + new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContext context = + SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authToken); + SecurityContextHolder.setContext(context); + + + } catch (Exception e) { + LOGGER.error("Invalid JWT token: {}", e.getMessage()); + } + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java b/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000..2351372 --- /dev/null +++ b/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,22 @@ +package com.podzilla.auth.security; + +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 RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(final HttpServletRequest request, + final HttpServletResponse response, + final AuthenticationException authException) + throws IOException { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, + "Authentication Failed"); + } +} diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java new file mode 100644 index 0000000..7d88405 --- /dev/null +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -0,0 +1,75 @@ +package com.podzilla.auth.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +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.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + private final JWTAuthenticationFilter jwtAuthenticationFilter; + + public SecurityConfig( + final JWTAuthenticationFilter jwtAuthenticationFilter) { + this.jwtAuthenticationFilter = jwtAuthenticationFilter; + } + + @Bean + SecurityFilterChain securityFilterChain(final HttpSecurity http) + throws Exception { + + http + .csrf(AbstractHttpConfigurer::disable) + .addFilterBefore(jwtAuthenticationFilter, + UsernamePasswordAuthenticationFilter.class) + .exceptionHandling(exceptionHandling -> + exceptionHandling + .authenticationEntryPoint( + new RestAuthenticationEntryPoint()) + ) + .authorizeHttpRequests((auth) -> + auth.requestMatchers( + HttpMethod.GET, "public_resource") + .permitAll() + .requestMatchers("/api/auth/**").permitAll() + .anyRequest().authenticated() + + ) + .sessionManagement(s -> s + .sessionCreationPolicy( + SessionCreationPolicy.STATELESS) + ); + + return http.build(); + } + + @Bean + public AuthenticationManager authenticationManager( + final UserDetailsService userDetailsService, + final PasswordEncoder passwordEncoder) { + DaoAuthenticationProvider authenticationProvider = + new DaoAuthenticationProvider(); + authenticationProvider.setUserDetailsService(userDetailsService); + authenticationProvider.setPasswordEncoder(passwordEncoder); + + return new ProviderManager(authenticationProvider); + } + + @Bean + public static PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java new file mode 100644 index 0000000..fca31e0 --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -0,0 +1,80 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.dto.LoginRequest; +import com.podzilla.auth.dto.SignupRequest; +import com.podzilla.auth.model.ERole; +import com.podzilla.auth.model.Role; +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.RoleRepository; +import com.podzilla.auth.repository.UserRepository; +import jakarta.persistence.EntityExistsException; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.Collections; + +@Service +public class AuthenticationService { + + private final AuthenticationManager authenticationManager; + private final PasswordEncoder passwordEncoder; + private final UserRepository userRepository; + private final JWTService jwtService; + private final RoleRepository roleRepository; + + public AuthenticationService( + final AuthenticationManager authenticationManager, + final PasswordEncoder passwordEncoder, + final UserRepository userRepository, + final JWTService jwtService, + final RoleRepository roleRepository) { + this.authenticationManager = authenticationManager; + this.passwordEncoder = passwordEncoder; + this.userRepository = userRepository; + this.jwtService = jwtService; + this.roleRepository = roleRepository; + } + + public String login(final LoginRequest loginRequest, + final HttpServletResponse response) { + + Authentication authenticationRequest = + UsernamePasswordAuthenticationToken. + unauthenticated( + loginRequest.getEmail(), + loginRequest.getPassword()); + Authentication authenticationResponse = + this.authenticationManager.authenticate(authenticationRequest); + + SecurityContextHolder.getContext(). + setAuthentication(authenticationResponse); + jwtService.generateToken(loginRequest.getEmail(), response); + UserDetails userDetails = + (UserDetails) authenticationResponse.getPrincipal(); + return userDetails.getUsername(); + } + + public void registerAccount(final SignupRequest signupRequest) { + if (userRepository.existsByEmail(signupRequest.getEmail())) { + throw new EntityExistsException("Email already used"); + } + + User account = new User( + signupRequest.getName(), + signupRequest.getEmail(), + passwordEncoder.encode(signupRequest.getPassword())); + Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); + account.setRoles(Collections.singleton(role)); + userRepository.save(account); + } + + public void logoutUser(final HttpServletResponse response) { + jwtService.removeTokenFromCookie(response); + } +} diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java new file mode 100644 index 0000000..5e6da6e --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -0,0 +1,47 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class CustomUserDetailsService implements UserDetailsService { + + private final UserRepository userRepository; + + @Autowired + public CustomUserDetailsService(final UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + public UserDetails loadUserByUsername(final String email) + throws UsernameNotFoundException { + User user = userRepository.findByEmail(email) + .orElseThrow(() -> + new UsernameNotFoundException( + email + " not found.")); + + Set authorities = user + .getRoles() + .stream() + .map((role) -> new SimpleGrantedAuthority( + role.getErole().name())) + .collect(Collectors.toSet()); + + return new org.springframework.security.core.userdetails.User( + user.getEmail(), + user.getPassword(), + authorities + ); + } +} diff --git a/src/main/java/com/podzilla/auth/service/JWTService.java b/src/main/java/com/podzilla/auth/service/JWTService.java new file mode 100644 index 0000000..8efd941 --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/JWTService.java @@ -0,0 +1,90 @@ +package com.podzilla.auth.service; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.util.WebUtils; + +import javax.crypto.SecretKey; +import java.util.Date; + +@Service +public class JWTService { + + // set in .env + @Value("${jwt.token.secret}") + private String secret; + + @Value("${jwt.token.expires}") + private Long jwtExpiresMinutes; + + private Claims claims; + + private static final Integer EXPIRATION_TIME = 60 * 1000; + private static final Integer MAX_AGE = 24 * 60 * 60; + + public void generateToken(final String email, + final HttpServletResponse response) { + String jwt = Jwts.builder() + .subject(email) + .issuedAt(new Date(System.currentTimeMillis())) + .expiration(new Date(System.currentTimeMillis() + + jwtExpiresMinutes * EXPIRATION_TIME)) + .signWith(getSignInKey()) + .compact(); + + Cookie cookie = new Cookie("JWT", jwt); + cookie.setHttpOnly(true); + cookie.setSecure(true); + cookie.setPath("/"); + cookie.setMaxAge(MAX_AGE); + response.addCookie(cookie); + } + + public String getJwtFromCookie(final HttpServletRequest request) { + Cookie cookie = WebUtils.getCookie(request, "JWT"); + if (cookie != null) { + return cookie.getValue(); + } + return null; + + } + + public void validateToken(final String token) throws JwtException { + try { + claims = Jwts.parser() + .verifyWith(getSignInKey()) + .build() + .parseSignedClaims(token) + .getPayload(); + + + } catch (JwtException e) { + throw new JwtException(e.getMessage()); + } + } + + public void removeTokenFromCookie(final HttpServletResponse response) { + Cookie cookie = new Cookie("JWT", null); + cookie.setPath("/"); + + response.addCookie(cookie); + } + + private SecretKey getSignInKey() { + byte[] keyBytes = Decoders.BASE64.decode(this.secret); + return Keys.hmacShaKeyFor(keyBytes); + } + + public String extractEmail() { + return claims.getSubject(); + } + +} diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..39be967 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,15 @@ + + + + logs/app.log + + + + + + + + + + + \ No newline at end of file From 86d51d2fe08f37a2a9d0b2340576b1c9b57bfe67 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 14:08:24 +0300 Subject: [PATCH 02/15] Add authentication, security, and JWT functionality Implement foundational authentication features, including user and role management, JWT-based authentication, and role-based security configurations. Add REST endpoints for login, signup, and logout, along with a Dockerized development setup, CI/CD workflows, and logging configurations. --- .gitattributes | 2 + .gitignore | 33 +++ mvnw | 259 ++++++++++++++++++ mvnw.cmd | 149 ++++++++++ pom.xml | 150 ++++++++++ .../com/podzilla/auth/AuthApplication.java | 13 + src/main/resources/application.properties | 25 ++ .../podzilla/auth/AuthApplicationTests.java | 13 + 8 files changed, 644 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/com/podzilla/auth/AuthApplication.java create mode 100644 src/main/resources/application.properties create mode 100644 src/test/java/com/podzilla/auth/AuthApplicationTests.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..cbf6b9d --- /dev/null +++ b/pom.xml @@ -0,0 +1,150 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.5 + + + com.podzilla + auth + 0.0.1-SNAPSHOT + auth + This is the authentication service for Podzilla + + + + + + + + + + + + + + + 23 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.8.5 + + + net.logstash.logback + logstash-logback-encoder + 7.4 + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-devtools + runtime + + + jakarta.servlet + jakarta.servlet-api + 6.1.0 + provided + + + jakarta.validation + jakarta.validation-api + 3.0.2 + + + + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + runtime + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/com/podzilla/auth/AuthApplication.java b/src/main/java/com/podzilla/auth/AuthApplication.java new file mode 100644 index 0000000..b003a58 --- /dev/null +++ b/src/main/java/com/podzilla/auth/AuthApplication.java @@ -0,0 +1,13 @@ +package com.podzilla.auth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AuthApplication { + + public static void main(final String[] args) { + SpringApplication.run(AuthApplication.class, args); + } + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..3be705a --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,25 @@ +spring.application.name=auth + +logging.file.name=./logs/app.log +logging.level.root=info +logging.level.com.podzilla.auth=debug + +spring.datasource.url=jdbc:postgresql://localhost:5432/authDB +spring.datasource.username=postgres +spring.datasource.password=1234 +spring.datasource.driver-class-name=org.postgresql.Driver + +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.generate-ddl=true +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.use_sql_comments=true + +logging.level.org.springframework.security=DEBUG + + +#jwt.token.secret + +jwt.token.secret=${SECRET_KEY} +jwt.token.expires=30 \ No newline at end of file diff --git a/src/test/java/com/podzilla/auth/AuthApplicationTests.java b/src/test/java/com/podzilla/auth/AuthApplicationTests.java new file mode 100644 index 0000000..b09061f --- /dev/null +++ b/src/test/java/com/podzilla/auth/AuthApplicationTests.java @@ -0,0 +1,13 @@ +package com.podzilla.auth; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AuthApplicationTests { + + @Test + void contextLoads() { + } + +} From c7a67724439a40c66010f75a7b16b3804c9404e3 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman <49641430+NourAlPha@users.noreply.github.com> Date: Sun, 27 Apr 2025 14:12:21 +0300 Subject: [PATCH 03/15] Update src/main/java/com/podzilla/auth/model/User.java Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/main/java/com/podzilla/auth/model/User.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/podzilla/auth/model/User.java b/src/main/java/com/podzilla/auth/model/User.java index 35de90b..9686c5c 100644 --- a/src/main/java/com/podzilla/auth/model/User.java +++ b/src/main/java/com/podzilla/auth/model/User.java @@ -35,7 +35,7 @@ public class User { @NotBlank(message = "Name is required") private String name; - @NotBlank(message = "email is required") + @NotBlank(message = "Email is required") @Email @Column(unique = true) private String email; From 96bcc51ff393606ada5b04a3758204fa18a761d8 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 14:21:58 +0300 Subject: [PATCH 04/15] fix test error --- pom.xml | 5 +++++ src/test/resources/application.properties | 10 ++++++++++ 2 files changed, 15 insertions(+) create mode 100644 src/test/resources/application.properties diff --git a/pom.xml b/pom.xml index cbf6b9d..d6c6bf7 100644 --- a/pom.xml +++ b/pom.xml @@ -116,6 +116,11 @@ 0.12.6 runtime + + com.h2database + h2 + test + diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 0000000..6ac6fdd --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,10 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=h2 +spring.datasource.password=1234 +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=create-drop +logging.level.org.hibernate.SQL=debug + +jwt.token.secret=${SECRET_KEY:12345678901234567890123456789012} +jwt.token.expires=30 \ No newline at end of file From 920aad0f14d1c38355d103abd00091e0614681ba Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 16:06:43 +0300 Subject: [PATCH 05/15] Create tmp --- tmp | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 tmp diff --git a/tmp b/tmp new file mode 100644 index 0000000..e69de29 From aeb7cf11785f831328595848a764b62951ceb515 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 16:20:00 +0300 Subject: [PATCH 06/15] Fix authApplication --- src/main/java/com/podzilla/auth/AuthApplication.java | 6 +++--- tmp | 0 2 files changed, 3 insertions(+), 3 deletions(-) delete mode 100644 tmp diff --git a/src/main/java/com/podzilla/auth/AuthApplication.java b/src/main/java/com/podzilla/auth/AuthApplication.java index b003a58..cb6eb42 100644 --- a/src/main/java/com/podzilla/auth/AuthApplication.java +++ b/src/main/java/com/podzilla/auth/AuthApplication.java @@ -6,8 +6,8 @@ @SpringBootApplication public class AuthApplication { - public static void main(final String[] args) { - SpringApplication.run(AuthApplication.class, args); - } + public static void main(final String[] args) { + SpringApplication.run(AuthApplication.class, args); + } } diff --git a/tmp b/tmp deleted file mode 100644 index e69de29..0000000 From 71785a1f6768a9a45fd7185c7150d532c49aacf3 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 18:39:32 +0300 Subject: [PATCH 07/15] Add refresh token --- .../controller/AuthenticationController.java | 40 ++++++++++--- .../auth/dto/AuthenticationResponse.java | 6 ++ .../com/podzilla/auth/model/RefreshToken.java | 44 ++++++++++++++ .../java/com/podzilla/auth/model/User.java | 8 ++- .../repository/RefreshTokenRepository.java | 15 +++++ .../auth/service/AuthenticationService.java | 59 +++++++++++++++++-- 6 files changed, 158 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java create mode 100644 src/main/java/com/podzilla/auth/model/RefreshToken.java create mode 100644 src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index 980f310..0de346b 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -1,5 +1,6 @@ package com.podzilla.auth.controller; +import com.podzilla.auth.dto.AuthenticationResponse; import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; import com.podzilla.auth.service.AuthenticationService; @@ -15,6 +16,9 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.UUID; @RestController @RequestMapping("/api/auth") @@ -35,12 +39,14 @@ public AuthenticationController( } @PostMapping("/login") - public ResponseEntity login(@RequestBody final LoginRequest loginRequest, - final HttpServletResponse response) { + public ResponseEntity login( + @RequestBody final LoginRequest loginRequest, + final HttpServletResponse response) { try { - String email = authenticationService.login(loginRequest, response); - LOGGER.info("User {} logged in", email); - return new ResponseEntity<>(email + " signed in", HttpStatus.OK); + AuthenticationResponse authResponse = + authenticationService.login(loginRequest, response); + LOGGER.info("User {} logged in", authResponse.email()); + return new ResponseEntity<>(authResponse, HttpStatus.OK); } catch (Exception e) { LOGGER.error(e.getMessage()); return new ResponseEntity<>(e.getMessage(), @@ -64,9 +70,27 @@ public ResponseEntity registerUser( } } - @PostMapping("/signout") - public ResponseEntity logoutUser(final HttpServletResponse response) { - authenticationService.logoutUser(response); + @PostMapping("/logout") + public ResponseEntity logoutUser( + @RequestParam final UUID refreshToken, + final HttpServletResponse response) { + authenticationService.logoutUser(refreshToken, response); return new ResponseEntity<>("You've been signed out!", HttpStatus.OK); } + + @PostMapping("/refresh-token") + public ResponseEntity refreshToken( + @RequestParam final UUID refreshToken, + final HttpServletResponse response) { + try { + AuthenticationResponse authResponse = + authenticationService.refreshToken(refreshToken, response); + LOGGER.info("User {} refreshed token", authResponse.email()); + return ResponseEntity.ok(authResponse); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + return new ResponseEntity<>(e.getMessage(), + HttpStatus.UNAUTHORIZED); + } + } } diff --git a/src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java b/src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java new file mode 100644 index 0000000..6d45a2d --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java @@ -0,0 +1,6 @@ +package com.podzilla.auth.dto; + +import java.util.UUID; + +public record AuthenticationResponse(String email, UUID refreshToken) { +} diff --git a/src/main/java/com/podzilla/auth/model/RefreshToken.java b/src/main/java/com/podzilla/auth/model/RefreshToken.java new file mode 100644 index 0000000..7f7da62 --- /dev/null +++ b/src/main/java/com/podzilla/auth/model/RefreshToken.java @@ -0,0 +1,44 @@ +package com.podzilla.auth.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.Id; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Column; +import jakarta.persistence.Table; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "refresh_tokens") +@Getter +@Setter +@NoArgsConstructor +@EntityListeners(AuditingEntityListener.class) +public class RefreshToken { + + @Id + @GeneratedValue(strategy = GenerationType.UUID) + @Column(updatable = false, nullable = false) + private UUID id; + + @ManyToOne(optional = false) + @JoinColumn(name = "user_id") + private User user; + + @Column(nullable = false, updatable = false) + @CreatedDate + private Instant createdAt; + + @Column(nullable = false) + private Instant expiresAt; +} diff --git a/src/main/java/com/podzilla/auth/model/User.java b/src/main/java/com/podzilla/auth/model/User.java index 9686c5c..c412bc6 100644 --- a/src/main/java/com/podzilla/auth/model/User.java +++ b/src/main/java/com/podzilla/auth/model/User.java @@ -1,15 +1,17 @@ package com.podzilla.auth.model; +import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import jakarta.persistence.FetchType; import java.util.HashSet; import java.util.Set; @@ -49,6 +51,10 @@ public class User { inverseJoinColumns = @JoinColumn(name = "role_id")) private Set roles = new HashSet<>(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, + orphanRemoval = true) + private Set refreshTokens = new HashSet<>(); + public User(final String name, final String email, final String password) { this.name = name; diff --git a/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java b/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java new file mode 100644 index 0000000..7a3cb58 --- /dev/null +++ b/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java @@ -0,0 +1,15 @@ +package com.podzilla.auth.repository; + +import com.podzilla.auth.model.RefreshToken; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface RefreshTokenRepository extends + JpaRepository { + Optional findByIdAndExpiresAtAfter(UUID id, Instant date); +} diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index fca31e0..789ad60 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -1,14 +1,18 @@ package com.podzilla.auth.service; +import com.podzilla.auth.dto.AuthenticationResponse; import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; import com.podzilla.auth.model.ERole; +import com.podzilla.auth.model.RefreshToken; import com.podzilla.auth.model.Role; import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.RefreshTokenRepository; import com.podzilla.auth.repository.RoleRepository; import com.podzilla.auth.repository.UserRepository; import jakarta.persistence.EntityExistsException; import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.ValidationException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -17,7 +21,11 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +import java.time.Instant; +import java.time.temporal.TemporalAmount; import java.util.Collections; +import java.util.UUID; + @Service public class AuthenticationService { @@ -27,22 +35,28 @@ public class AuthenticationService { private final UserRepository userRepository; private final JWTService jwtService; private final RoleRepository roleRepository; + private final RefreshTokenRepository refreshTokenRepository; + + private static final TemporalAmount EXPIRES_IN = + java.time.Duration.ofDays(10); public AuthenticationService( final AuthenticationManager authenticationManager, final PasswordEncoder passwordEncoder, final UserRepository userRepository, final JWTService jwtService, - final RoleRepository roleRepository) { + final RoleRepository roleRepository, + final RefreshTokenRepository refreshTokenRepository) { this.authenticationManager = authenticationManager; this.passwordEncoder = passwordEncoder; this.userRepository = userRepository; this.jwtService = jwtService; this.roleRepository = roleRepository; + this.refreshTokenRepository = refreshTokenRepository; } - public String login(final LoginRequest loginRequest, - final HttpServletResponse response) { + public AuthenticationResponse login(final LoginRequest loginRequest, + final HttpServletResponse response) { Authentication authenticationRequest = UsernamePasswordAuthenticationToken. @@ -57,7 +71,17 @@ public String login(final LoginRequest loginRequest, jwtService.generateToken(loginRequest.getEmail(), response); UserDetails userDetails = (UserDetails) authenticationResponse.getPrincipal(); - return userDetails.getUsername(); + + User user = userRepository.findByEmail(userDetails.getUsername()) + .orElseThrow(() -> new EntityExistsException("User not found")); + + RefreshToken refreshToken = new RefreshToken(); + refreshToken.setUser(user); + refreshToken.setExpiresAt(Instant.now().plus(EXPIRES_IN)); + refreshTokenRepository.save(refreshToken); + + return new AuthenticationResponse(userDetails.getUsername(), + refreshToken.getId()); } public void registerAccount(final SignupRequest signupRequest) { @@ -74,7 +98,32 @@ public void registerAccount(final SignupRequest signupRequest) { userRepository.save(account); } - public void logoutUser(final HttpServletResponse response) { + public void logoutUser(final UUID refreshToken, + final HttpServletResponse response) { jwtService.removeTokenFromCookie(response); + refreshTokenRepository.deleteById(refreshToken); + } + + public AuthenticationResponse refreshToken( + final UUID refreshToken, + final HttpServletResponse response) { + final var refreshTokenEntity = refreshTokenRepository + .findByIdAndExpiresAtAfter(refreshToken, Instant.now()) + .orElseThrow(() -> + new ValidationException("Invalid refresh token")); + + refreshTokenEntity.setExpiresAt(Instant.now()); + refreshTokenRepository.save(refreshTokenEntity); + + final RefreshToken newRefreshToken = new RefreshToken(); + newRefreshToken.setUser(refreshTokenEntity.getUser()); + newRefreshToken.setExpiresAt(Instant.now().plus(EXPIRES_IN)); + refreshTokenRepository.save(newRefreshToken); + + jwtService.generateToken( + refreshTokenEntity.getUser().getEmail(), response); + return new AuthenticationResponse( + refreshTokenEntity.getUser().getEmail(), + newRefreshToken.getId()); } } From c4f7560d13001bcdeb294848a6da80f23e8e3513 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 22:37:46 +0300 Subject: [PATCH 08/15] Add refresh token to the cookie instead of returning it back to the frontend. --- .../controller/AuthenticationController.java | 31 +++-- .../auth/dto/AuthenticationResponse.java | 6 - .../security/JWTAuthenticationFilter.java | 4 +- .../auth/service/AuthenticationService.java | 72 ++++-------- .../com/podzilla/auth/service/JWTService.java | 111 ++++++++++++++++-- 5 files changed, 136 insertions(+), 88 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index 0de346b..bc8bfc6 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -1,6 +1,5 @@ package com.podzilla.auth.controller; -import com.podzilla.auth.dto.AuthenticationResponse; import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; import com.podzilla.auth.service.AuthenticationService; @@ -16,9 +15,6 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.bind.annotation.RequestParam; - -import java.util.UUID; @RestController @RequestMapping("/api/auth") @@ -43,10 +39,11 @@ public ResponseEntity login( @RequestBody final LoginRequest loginRequest, final HttpServletResponse response) { try { - AuthenticationResponse authResponse = - authenticationService.login(loginRequest, response); - LOGGER.info("User {} logged in", authResponse.email()); - return new ResponseEntity<>(authResponse, HttpStatus.OK); + String email = authenticationService.login(loginRequest, response); + LOGGER.info("User {} logged in", email); + return new ResponseEntity<>( + "User " + email + "logged in successfully", + HttpStatus.OK); } catch (Exception e) { LOGGER.error(e.getMessage()); return new ResponseEntity<>(e.getMessage(), @@ -71,22 +68,22 @@ public ResponseEntity registerUser( } @PostMapping("/logout") - public ResponseEntity logoutUser( - @RequestParam final UUID refreshToken, - final HttpServletResponse response) { - authenticationService.logoutUser(refreshToken, response); + public ResponseEntity logoutUser(final HttpServletResponse response) { + authenticationService.logoutUser(response); return new ResponseEntity<>("You've been signed out!", HttpStatus.OK); } @PostMapping("/refresh-token") public ResponseEntity refreshToken( - @RequestParam final UUID refreshToken, + final HttpServletRequest request, final HttpServletResponse response) { try { - AuthenticationResponse authResponse = - authenticationService.refreshToken(refreshToken, response); - LOGGER.info("User {} refreshed token", authResponse.email()); - return ResponseEntity.ok(authResponse); + String email = authenticationService.refreshToken( + request, response); + LOGGER.info("User {} refreshed token", email); + return new ResponseEntity<>( + "User " + email + "refreshed token successfully", + HttpStatus.OK); } catch (Exception e) { LOGGER.error(e.getMessage()); return new ResponseEntity<>(e.getMessage(), diff --git a/src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java b/src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java deleted file mode 100644 index 6d45a2d..0000000 --- a/src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.podzilla.auth.dto; - -import java.util.UUID; - -public record AuthenticationResponse(String email, UUID refreshToken) { -} diff --git a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java index b81e7e2..e6e230f 100644 --- a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java +++ b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java @@ -42,8 +42,8 @@ protected void doFilterInternal(final HttpServletRequest request, throws ServletException, IOException { try { - String jwt = jwtService.getJwtFromCookie(request); - jwtService.validateToken(jwt); + String jwt = jwtService.getAccessTokenFromCookie(request); + jwtService.validateAccessToken(jwt); String userEmail = jwtService.extractEmail(); UserDetails userDetails = diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 789ad60..7c8250d 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -1,18 +1,15 @@ package com.podzilla.auth.service; -import com.podzilla.auth.dto.AuthenticationResponse; import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; import com.podzilla.auth.model.ERole; -import com.podzilla.auth.model.RefreshToken; import com.podzilla.auth.model.Role; import com.podzilla.auth.model.User; -import com.podzilla.auth.repository.RefreshTokenRepository; import com.podzilla.auth.repository.RoleRepository; import com.podzilla.auth.repository.UserRepository; import jakarta.persistence.EntityExistsException; +import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import jakarta.validation.ValidationException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -21,10 +18,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; -import java.time.Instant; -import java.time.temporal.TemporalAmount; import java.util.Collections; -import java.util.UUID; @Service @@ -35,28 +29,22 @@ public class AuthenticationService { private final UserRepository userRepository; private final JWTService jwtService; private final RoleRepository roleRepository; - private final RefreshTokenRepository refreshTokenRepository; - - private static final TemporalAmount EXPIRES_IN = - java.time.Duration.ofDays(10); public AuthenticationService( final AuthenticationManager authenticationManager, final PasswordEncoder passwordEncoder, final UserRepository userRepository, final JWTService jwtService, - final RoleRepository roleRepository, - final RefreshTokenRepository refreshTokenRepository) { + final RoleRepository roleRepository) { this.authenticationManager = authenticationManager; this.passwordEncoder = passwordEncoder; this.userRepository = userRepository; this.jwtService = jwtService; this.roleRepository = roleRepository; - this.refreshTokenRepository = refreshTokenRepository; } - public AuthenticationResponse login(final LoginRequest loginRequest, - final HttpServletResponse response) { + public String login(final LoginRequest loginRequest, + final HttpServletResponse response) { Authentication authenticationRequest = UsernamePasswordAuthenticationToken. @@ -68,20 +56,12 @@ public AuthenticationResponse login(final LoginRequest loginRequest, SecurityContextHolder.getContext(). setAuthentication(authenticationResponse); - jwtService.generateToken(loginRequest.getEmail(), response); + jwtService.generateAccessToken(loginRequest.getEmail(), response); + jwtService.generateRefreshToken(loginRequest.getEmail(), response); UserDetails userDetails = (UserDetails) authenticationResponse.getPrincipal(); - User user = userRepository.findByEmail(userDetails.getUsername()) - .orElseThrow(() -> new EntityExistsException("User not found")); - - RefreshToken refreshToken = new RefreshToken(); - refreshToken.setUser(user); - refreshToken.setExpiresAt(Instant.now().plus(EXPIRES_IN)); - refreshTokenRepository.save(refreshToken); - - return new AuthenticationResponse(userDetails.getUsername(), - refreshToken.getId()); + return userDetails.getUsername(); } public void registerAccount(final SignupRequest signupRequest) { @@ -98,32 +78,20 @@ public void registerAccount(final SignupRequest signupRequest) { userRepository.save(account); } - public void logoutUser(final UUID refreshToken, - final HttpServletResponse response) { - jwtService.removeTokenFromCookie(response); - refreshTokenRepository.deleteById(refreshToken); + public void logoutUser(final HttpServletResponse response) { + jwtService.removeAccessTokenFromCookie(response); + jwtService.removeRefreshTokenFromCookie(response); } - public AuthenticationResponse refreshToken( - final UUID refreshToken, - final HttpServletResponse response) { - final var refreshTokenEntity = refreshTokenRepository - .findByIdAndExpiresAtAfter(refreshToken, Instant.now()) - .orElseThrow(() -> - new ValidationException("Invalid refresh token")); - - refreshTokenEntity.setExpiresAt(Instant.now()); - refreshTokenRepository.save(refreshTokenEntity); - - final RefreshToken newRefreshToken = new RefreshToken(); - newRefreshToken.setUser(refreshTokenEntity.getUser()); - newRefreshToken.setExpiresAt(Instant.now().plus(EXPIRES_IN)); - refreshTokenRepository.save(newRefreshToken); - - jwtService.generateToken( - refreshTokenEntity.getUser().getEmail(), response); - return new AuthenticationResponse( - refreshTokenEntity.getUser().getEmail(), - newRefreshToken.getId()); + public String refreshToken(final HttpServletRequest request, + final HttpServletResponse response) { + String refreshToken = jwtService.getRefreshTokenFromCookie(request); + try { + String email = jwtService.renewRefreshToken(refreshToken, response); + jwtService.generateAccessToken(email, response); + return email; + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Invalid refresh token"); + } } } diff --git a/src/main/java/com/podzilla/auth/service/JWTService.java b/src/main/java/com/podzilla/auth/service/JWTService.java index 8efd941..86623ce 100644 --- a/src/main/java/com/podzilla/auth/service/JWTService.java +++ b/src/main/java/com/podzilla/auth/service/JWTService.java @@ -1,19 +1,28 @@ package com.podzilla.auth.service; +import com.podzilla.auth.model.RefreshToken; +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.RefreshTokenRepository; +import com.podzilla.auth.repository.UserRepository; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; +import jakarta.persistence.EntityExistsException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.ValidationException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.util.WebUtils; import javax.crypto.SecretKey; +import java.time.Instant; +import java.time.temporal.TemporalAmount; import java.util.Date; +import java.util.UUID; @Service public class JWTService { @@ -27,29 +36,92 @@ public class JWTService { private Claims claims; - private static final Integer EXPIRATION_TIME = 60 * 1000; - private static final Integer MAX_AGE = 24 * 60 * 60; + private static final Integer ACCESS_TOKEN_EXPIRATION_TIME = 60 * 1000; + private static final Integer ACCESS_TOKEN_COOKIE_EXPIRATION_TIME = 60 * 30; + private static final TemporalAmount REFRESH_TOKEN_EXPIRATION_TIME = + java.time.Duration.ofDays(10); + private static final Integer REFRESH_TOKEN_COOKIE_EXPIRATION_TIME = + 60 * 60 * 24 * 10; - public void generateToken(final String email, - final HttpServletResponse response) { + private final UserRepository userRepository; + private final RefreshTokenRepository refreshTokenRepository; + + public JWTService(final UserRepository userRepository, + final RefreshTokenRepository refreshTokenRepository) { + this.userRepository = userRepository; + this.refreshTokenRepository = refreshTokenRepository; + } + + public void generateAccessToken(final String email, + final HttpServletResponse response) { String jwt = Jwts.builder() .subject(email) .issuedAt(new Date(System.currentTimeMillis())) .expiration(new Date(System.currentTimeMillis() - + jwtExpiresMinutes * EXPIRATION_TIME)) + + jwtExpiresMinutes * ACCESS_TOKEN_EXPIRATION_TIME)) .signWith(getSignInKey()) .compact(); - Cookie cookie = new Cookie("JWT", jwt); + Cookie cookie = new Cookie("accessToken", jwt); cookie.setHttpOnly(true); cookie.setSecure(true); cookie.setPath("/"); - cookie.setMaxAge(MAX_AGE); + cookie.setMaxAge(ACCESS_TOKEN_COOKIE_EXPIRATION_TIME); + response.addCookie(cookie); + } + + public void generateRefreshToken(final String email, + final HttpServletResponse response) { + User user = userRepository.findByEmail(email) + .orElseThrow(() -> new EntityExistsException("User not found")); + + RefreshToken refreshToken = new RefreshToken(); + refreshToken.setUser(user); + refreshToken.setExpiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)); + refreshTokenRepository.save(refreshToken); + + String refreshTokenString = refreshToken.getId().toString(); + addRefreshTokenToCookie(refreshTokenString, response); + } + + public String renewRefreshToken(final String refreshToken, + final HttpServletResponse response) { + RefreshToken token = + refreshTokenRepository + .findByIdAndExpiresAtAfter( + UUID.fromString(refreshToken), Instant.now()) + .orElseThrow(() -> + new ValidationException( + "Invalid refresh token")); + + token.setExpiresAt(Instant.now()); + refreshTokenRepository.save(token); + + RefreshToken newRefreshToken = new RefreshToken(); + newRefreshToken.setUser(token.getUser()); + newRefreshToken.setExpiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)); + refreshTokenRepository.save(newRefreshToken); + + String newRefreshTokenString = newRefreshToken.getId().toString(); + addRefreshTokenToCookie(newRefreshTokenString, response); + + return token.getUser().getEmail(); + } + + private void addRefreshTokenToCookie(final String refreshToken, + final HttpServletResponse response) { + Cookie cookie = new Cookie("refreshToken", refreshToken); + cookie.setHttpOnly(true); + cookie.setSecure(true); + cookie.setPath("/api/auth/refresh-token"); + cookie.setMaxAge(REFRESH_TOKEN_COOKIE_EXPIRATION_TIME); response.addCookie(cookie); } - public String getJwtFromCookie(final HttpServletRequest request) { - Cookie cookie = WebUtils.getCookie(request, "JWT"); + public String getAccessTokenFromCookie(final HttpServletRequest request) { + Cookie cookie = WebUtils.getCookie(request, "accessToken"); if (cookie != null) { return cookie.getValue(); } @@ -57,7 +129,15 @@ public String getJwtFromCookie(final HttpServletRequest request) { } - public void validateToken(final String token) throws JwtException { + public String getRefreshTokenFromCookie(final HttpServletRequest request) { + Cookie cookie = WebUtils.getCookie(request, "refreshToken"); + if (cookie != null) { + return cookie.getValue(); + } + return null; + } + + public void validateAccessToken(final String token) throws JwtException { try { claims = Jwts.parser() .verifyWith(getSignInKey()) @@ -71,13 +151,22 @@ public void validateToken(final String token) throws JwtException { } } - public void removeTokenFromCookie(final HttpServletResponse response) { + public void removeAccessTokenFromCookie( + final HttpServletResponse response) { Cookie cookie = new Cookie("JWT", null); cookie.setPath("/"); response.addCookie(cookie); } + public void removeRefreshTokenFromCookie( + final HttpServletResponse response) { + Cookie cookie = new Cookie("refreshToken", null); + cookie.setPath("/api/auth/refresh-token"); + + response.addCookie(cookie); + } + private SecretKey getSignInKey() { byte[] keyBytes = Decoders.BASE64.decode(this.secret); return Keys.hmacShaKeyFor(keyBytes); From 8f9f175b5a86575606f68a2402014a19e7e53751 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Mon, 28 Apr 2025 19:06:12 +0300 Subject: [PATCH 09/15] Add admin role get all users api --- .../auth/controller/AdminController.java | 26 +++++++++++++++++++ .../auth/security/SecurityConfig.java | 2 ++ .../podzilla/auth/service/AdminService.java | 21 +++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 src/main/java/com/podzilla/auth/controller/AdminController.java create mode 100644 src/main/java/com/podzilla/auth/service/AdminService.java diff --git a/src/main/java/com/podzilla/auth/controller/AdminController.java b/src/main/java/com/podzilla/auth/controller/AdminController.java new file mode 100644 index 0000000..4dc5f32 --- /dev/null +++ b/src/main/java/com/podzilla/auth/controller/AdminController.java @@ -0,0 +1,26 @@ +package com.podzilla.auth.controller; + +import com.podzilla.auth.model.User; +import com.podzilla.auth.service.AdminService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin") +public class AdminController { + + private final AdminService adminService; + + public AdminController(final AdminService adminService) { + this.adminService = adminService; + } + + @GetMapping("/users") + public List getUsers() { + return adminService.getUsers(); + } + +} diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index 7d88405..f28794c 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -45,6 +45,8 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) HttpMethod.GET, "public_resource") .permitAll() .requestMatchers("/api/auth/**").permitAll() + .requestMatchers("/api/admin/**") + .hasRole("ADMIN") .anyRequest().authenticated() ) diff --git a/src/main/java/com/podzilla/auth/service/AdminService.java b/src/main/java/com/podzilla/auth/service/AdminService.java new file mode 100644 index 0000000..b84b214 --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/AdminService.java @@ -0,0 +1,21 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.UserRepository; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class AdminService { + + private final UserRepository userRepository; + + public AdminService(final UserRepository userRepository) { + this.userRepository = userRepository; + } + + public List getUsers() { + return userRepository.findAll(); + } +} From f8f9b211ad1786d15e44101c355f328ce77ced2c Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman <49641430+NourAlPha@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:15:15 +0300 Subject: [PATCH 10/15] Update src/main/java/com/podzilla/auth/controller/AuthenticationController.java Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../com/podzilla/auth/controller/AuthenticationController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index bc8bfc6..4533143 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -42,7 +42,7 @@ public ResponseEntity login( String email = authenticationService.login(loginRequest, response); LOGGER.info("User {} logged in", email); return new ResponseEntity<>( - "User " + email + "logged in successfully", + "User " + email + " logged in successfully", HttpStatus.OK); } catch (Exception e) { LOGGER.error(e.getMessage()); From 0ce8b9cde16a30c61b111110d0ef368737c2ae40 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman <49641430+NourAlPha@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:15:23 +0300 Subject: [PATCH 11/15] Update src/main/java/com/podzilla/auth/controller/AuthenticationController.java Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../com/podzilla/auth/controller/AuthenticationController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index 4533143..842cb1d 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -82,7 +82,7 @@ public ResponseEntity refreshToken( request, response); LOGGER.info("User {} refreshed token", email); return new ResponseEntity<>( - "User " + email + "refreshed token successfully", + "User " + email + " refreshed token successfully", HttpStatus.OK); } catch (Exception e) { LOGGER.error(e.getMessage()); From 837add8c902d642f585227e03f559e7eaade306b Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman <49641430+NourAlPha@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:16:22 +0300 Subject: [PATCH 12/15] Update .github/workflows/ci-cd.yml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/workflows/ci-cd.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 9dbaf62..ca05840 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -10,5 +10,5 @@ jobs: call-ci: uses: Podzilla/templates/.github/workflows/ci.yml@main with: - branch: 'refs/head/main' # <<< Passes the branch name dynamically + branch: 'refs/heads/main' # <<< Passes the branch name dynamically secrets: inherit \ No newline at end of file From 7235218ee8ecc5ae58bf80957f2368c73d562e97 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Mon, 28 Apr 2025 20:22:52 +0300 Subject: [PATCH 13/15] Rename signup endpoint to register and enhance refresh token management --- .../controller/AuthenticationController.java | 2 +- .../auth/controller/ResourceController.java | 23 +++++++++++++++++++ .../repository/RefreshTokenRepository.java | 2 ++ .../com/podzilla/auth/service/JWTService.java | 23 ++++++++++++------- 4 files changed, 41 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/podzilla/auth/controller/ResourceController.java diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index 842cb1d..ee7739d 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -51,7 +51,7 @@ public ResponseEntity login( } } - @PostMapping("/signup") + @PostMapping("/register") public ResponseEntity registerUser( @RequestBody final SignupRequest signupRequest, final HttpServletRequest request) { diff --git a/src/main/java/com/podzilla/auth/controller/ResourceController.java b/src/main/java/com/podzilla/auth/controller/ResourceController.java new file mode 100644 index 0000000..62c464a --- /dev/null +++ b/src/main/java/com/podzilla/auth/controller/ResourceController.java @@ -0,0 +1,23 @@ +package com.podzilla.auth.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ResourceController { + + @GetMapping("/secret_resource") + public ResponseEntity secret() { + return new ResponseEntity<>( + "You are viewing my secret", HttpStatus.OK); + } + + @GetMapping("/public_resource") + public ResponseEntity noSecret() { + // assuming no existing user + + return new ResponseEntity<>("You are in public area", HttpStatus.OK); + } +} diff --git a/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java b/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java index 7a3cb58..89494fc 100644 --- a/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java +++ b/src/main/java/com/podzilla/auth/repository/RefreshTokenRepository.java @@ -12,4 +12,6 @@ public interface RefreshTokenRepository extends JpaRepository { Optional findByIdAndExpiresAtAfter(UUID id, Instant date); + Optional findByUserIdAndExpiresAtAfter(Long userId, + Instant date); } diff --git a/src/main/java/com/podzilla/auth/service/JWTService.java b/src/main/java/com/podzilla/auth/service/JWTService.java index 86623ce..8be6c33 100644 --- a/src/main/java/com/podzilla/auth/service/JWTService.java +++ b/src/main/java/com/podzilla/auth/service/JWTService.java @@ -74,19 +74,25 @@ public void generateRefreshToken(final String email, final HttpServletResponse response) { User user = userRepository.findByEmail(email) .orElseThrow(() -> new EntityExistsException("User not found")); + RefreshToken userRefreshToken = + refreshTokenRepository.findByUserIdAndExpiresAtAfter( + user.getId(), Instant.now()).orElse(null); + + if (userRefreshToken == null) { + userRefreshToken = new RefreshToken(); + userRefreshToken.setUser(user); + userRefreshToken.setCreatedAt(Instant.now()); + userRefreshToken.setExpiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)); + refreshTokenRepository.save(userRefreshToken); + } - RefreshToken refreshToken = new RefreshToken(); - refreshToken.setUser(user); - refreshToken.setExpiresAt(Instant.now().plus( - REFRESH_TOKEN_EXPIRATION_TIME)); - refreshTokenRepository.save(refreshToken); - - String refreshTokenString = refreshToken.getId().toString(); + String refreshTokenString = userRefreshToken.getId().toString(); addRefreshTokenToCookie(refreshTokenString, response); } public String renewRefreshToken(final String refreshToken, - final HttpServletResponse response) { + final HttpServletResponse response) { RefreshToken token = refreshTokenRepository .findByIdAndExpiresAtAfter( @@ -100,6 +106,7 @@ public String renewRefreshToken(final String refreshToken, RefreshToken newRefreshToken = new RefreshToken(); newRefreshToken.setUser(token.getUser()); + newRefreshToken.setCreatedAt(Instant.now()); newRefreshToken.setExpiresAt(Instant.now().plus( REFRESH_TOKEN_EXPIRATION_TIME)); refreshTokenRepository.save(newRefreshToken); From 251dc5b554aeb77568ed1d67e3768ddf1b872065 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:44:04 +0300 Subject: [PATCH 14/15] Refactor API endpoints and rename JWTService to TokenService --- .../auth/controller/AdminController.java | 2 +- .../controller/AuthenticationController.java | 2 +- .../security/JWTAuthenticationFilter.java | 14 ++++++------- .../auth/security/SecurityConfig.java | 4 ++-- .../auth/service/AuthenticationService.java | 21 ++++++++++--------- .../{JWTService.java => TokenService.java} | 19 ++++++++++------- 6 files changed, 33 insertions(+), 29 deletions(-) rename src/main/java/com/podzilla/auth/service/{JWTService.java => TokenService.java} (91%) diff --git a/src/main/java/com/podzilla/auth/controller/AdminController.java b/src/main/java/com/podzilla/auth/controller/AdminController.java index 4dc5f32..2f91bff 100644 --- a/src/main/java/com/podzilla/auth/controller/AdminController.java +++ b/src/main/java/com/podzilla/auth/controller/AdminController.java @@ -9,7 +9,7 @@ import java.util.List; @RestController -@RequestMapping("/api/admin") +@RequestMapping("/admin") public class AdminController { private final AdminService adminService; diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index ee7739d..7f23f24 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -17,7 +17,7 @@ import org.springframework.web.bind.annotation.RestController; @RestController -@RequestMapping("/api/auth") +@RequestMapping("/auth") public class AuthenticationController { private final AuthenticationService authenticationService; diff --git a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java index e6e230f..34d1297 100644 --- a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java +++ b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java @@ -1,7 +1,7 @@ package com.podzilla.auth.security; import com.podzilla.auth.service.CustomUserDetailsService; -import com.podzilla.auth.service.JWTService; +import com.podzilla.auth.service.TokenService; import io.micrometer.common.lang.NonNullApi; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -22,13 +22,13 @@ @NonNullApi @Component public class JWTAuthenticationFilter extends OncePerRequestFilter { - private final JWTService jwtService; + private final TokenService tokenService; private final CustomUserDetailsService customUserDetailsService; public JWTAuthenticationFilter( - final JWTService jwtService, + final TokenService tokenService, final CustomUserDetailsService customUserDetailsService) { - this.jwtService = jwtService; + this.tokenService = tokenService; this.customUserDetailsService = customUserDetailsService; } @@ -42,9 +42,9 @@ protected void doFilterInternal(final HttpServletRequest request, throws ServletException, IOException { try { - String jwt = jwtService.getAccessTokenFromCookie(request); - jwtService.validateAccessToken(jwt); - String userEmail = jwtService.extractEmail(); + String jwt = tokenService.getAccessTokenFromCookie(request); + tokenService.validateAccessToken(jwt); + String userEmail = tokenService.extractEmail(); UserDetails userDetails = customUserDetailsService.loadUserByUsername(userEmail); diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index f28794c..11e868e 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -44,8 +44,8 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) auth.requestMatchers( HttpMethod.GET, "public_resource") .permitAll() - .requestMatchers("/api/auth/**").permitAll() - .requestMatchers("/api/admin/**") + .requestMatchers("/auth/**").permitAll() + .requestMatchers("/admin/**") .hasRole("ADMIN") .anyRequest().authenticated() diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 7c8250d..db361b5 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -27,19 +27,19 @@ public class AuthenticationService { private final AuthenticationManager authenticationManager; private final PasswordEncoder passwordEncoder; private final UserRepository userRepository; - private final JWTService jwtService; + private final TokenService tokenService; private final RoleRepository roleRepository; public AuthenticationService( final AuthenticationManager authenticationManager, final PasswordEncoder passwordEncoder, final UserRepository userRepository, - final JWTService jwtService, + final TokenService tokenService, final RoleRepository roleRepository) { this.authenticationManager = authenticationManager; this.passwordEncoder = passwordEncoder; this.userRepository = userRepository; - this.jwtService = jwtService; + this.tokenService = tokenService; this.roleRepository = roleRepository; } @@ -56,8 +56,8 @@ public String login(final LoginRequest loginRequest, SecurityContextHolder.getContext(). setAuthentication(authenticationResponse); - jwtService.generateAccessToken(loginRequest.getEmail(), response); - jwtService.generateRefreshToken(loginRequest.getEmail(), response); + tokenService.generateAccessToken(loginRequest.getEmail(), response); + tokenService.generateRefreshToken(loginRequest.getEmail(), response); UserDetails userDetails = (UserDetails) authenticationResponse.getPrincipal(); @@ -79,16 +79,17 @@ public void registerAccount(final SignupRequest signupRequest) { } public void logoutUser(final HttpServletResponse response) { - jwtService.removeAccessTokenFromCookie(response); - jwtService.removeRefreshTokenFromCookie(response); + tokenService.removeAccessTokenFromCookie(response); + tokenService.removeRefreshTokenFromCookie(response); } public String refreshToken(final HttpServletRequest request, final HttpServletResponse response) { - String refreshToken = jwtService.getRefreshTokenFromCookie(request); + String refreshToken = tokenService.getRefreshTokenFromCookie(request); try { - String email = jwtService.renewRefreshToken(refreshToken, response); - jwtService.generateAccessToken(email, response); + String email = + tokenService.renewRefreshToken(refreshToken, response); + tokenService.generateAccessToken(email, response); return email; } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid refresh token"); diff --git a/src/main/java/com/podzilla/auth/service/JWTService.java b/src/main/java/com/podzilla/auth/service/TokenService.java similarity index 91% rename from src/main/java/com/podzilla/auth/service/JWTService.java rename to src/main/java/com/podzilla/auth/service/TokenService.java index 8be6c33..9fb564c 100644 --- a/src/main/java/com/podzilla/auth/service/JWTService.java +++ b/src/main/java/com/podzilla/auth/service/TokenService.java @@ -25,7 +25,7 @@ import java.util.UUID; @Service -public class JWTService { +public class TokenService { // set in .env @Value("${jwt.token.secret}") @@ -42,12 +42,15 @@ public class JWTService { java.time.Duration.ofDays(10); private static final Integer REFRESH_TOKEN_COOKIE_EXPIRATION_TIME = 60 * 60 * 24 * 10; + private static final String REFRESH_TOKEN_COOKIE_PATH = + "/api/auth/refresh-token"; + private static final String ACCESS_TOKEN_COOKIE_PATH = "/"; private final UserRepository userRepository; private final RefreshTokenRepository refreshTokenRepository; - public JWTService(final UserRepository userRepository, - final RefreshTokenRepository refreshTokenRepository) { + public TokenService(final UserRepository userRepository, + final RefreshTokenRepository refreshTokenRepository) { this.userRepository = userRepository; this.refreshTokenRepository = refreshTokenRepository; } @@ -65,7 +68,7 @@ public void generateAccessToken(final String email, Cookie cookie = new Cookie("accessToken", jwt); cookie.setHttpOnly(true); cookie.setSecure(true); - cookie.setPath("/"); + cookie.setPath(ACCESS_TOKEN_COOKIE_PATH); cookie.setMaxAge(ACCESS_TOKEN_COOKIE_EXPIRATION_TIME); response.addCookie(cookie); } @@ -122,7 +125,7 @@ private void addRefreshTokenToCookie(final String refreshToken, Cookie cookie = new Cookie("refreshToken", refreshToken); cookie.setHttpOnly(true); cookie.setSecure(true); - cookie.setPath("/api/auth/refresh-token"); + cookie.setPath(REFRESH_TOKEN_COOKIE_PATH); cookie.setMaxAge(REFRESH_TOKEN_COOKIE_EXPIRATION_TIME); response.addCookie(cookie); } @@ -160,8 +163,8 @@ public void validateAccessToken(final String token) throws JwtException { public void removeAccessTokenFromCookie( final HttpServletResponse response) { - Cookie cookie = new Cookie("JWT", null); - cookie.setPath("/"); + Cookie cookie = new Cookie("accessToken", null); + cookie.setPath(ACCESS_TOKEN_COOKIE_PATH); response.addCookie(cookie); } @@ -169,7 +172,7 @@ public void removeAccessTokenFromCookie( public void removeRefreshTokenFromCookie( final HttpServletResponse response) { Cookie cookie = new Cookie("refreshToken", null); - cookie.setPath("/api/auth/refresh-token"); + cookie.setPath(REFRESH_TOKEN_COOKIE_PATH); response.addCookie(cookie); } From fa225f692f90f77c20e99787b49d6b0b52fe1908 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:45:17 +0300 Subject: [PATCH 15/15] Set server context path to /api in application properties --- src/main/resources/application.properties | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3be705a..e9d1807 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -16,6 +16,8 @@ spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.use_sql_comments=true +server.servlet.context-path=/api + logging.level.org.springframework.security=DEBUG