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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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 a702c8326a37f39fda21183c556bc1de7c9a3d1c Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Mon, 28 Apr 2025 22:37:19 +0300 Subject: [PATCH 14/60] Add Swagger annotations for API documentation and implement custom exception handling --- .../auth/controller/AdminController.java | 6 ++ .../controller/AuthenticationController.java | 82 +++++++++++-------- .../auth/controller/ResourceController.java | 23 ------ .../auth/exception/ErrorResponse.java | 19 +++++ .../exception/GlobalExceptionHandler.java | 42 ++++++++++ .../exception/InvalidActionException.java | 7 ++ .../auth/exception/NotFoundException.java | 7 ++ .../auth/exception/ValidationException.java | 7 ++ .../auth/service/AuthenticationService.java | 6 +- .../service/CustomUserDetailsService.java | 7 +- .../com/podzilla/auth/service/JWTService.java | 9 +- 11 files changed, 147 insertions(+), 68 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/controller/ResourceController.java create mode 100644 src/main/java/com/podzilla/auth/exception/ErrorResponse.java create mode 100644 src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/com/podzilla/auth/exception/InvalidActionException.java create mode 100644 src/main/java/com/podzilla/auth/exception/NotFoundException.java create mode 100644 src/main/java/com/podzilla/auth/exception/ValidationException.java diff --git a/src/main/java/com/podzilla/auth/controller/AdminController.java b/src/main/java/com/podzilla/auth/controller/AdminController.java index 4dc5f32..e671dbf 100644 --- a/src/main/java/com/podzilla/auth/controller/AdminController.java +++ b/src/main/java/com/podzilla/auth/controller/AdminController.java @@ -2,6 +2,8 @@ import com.podzilla.auth.model.User; import com.podzilla.auth.service.AdminService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -19,6 +21,10 @@ public AdminController(final AdminService adminService) { } @GetMapping("/users") + @Operation(summary = "Get all users", + description = "Fetches all users in the system.") + @ApiResponse(responseCode = "200", + description = "Users fetched successfully") public List getUsers() { return adminService.getUsers(); } diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index ee7739d..7908203 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -3,6 +3,8 @@ import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; import com.podzilla.auth.service.AuthenticationService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; @@ -35,59 +37,73 @@ public AuthenticationController( } @PostMapping("/login") + @Operation( + summary = "Login", + description = "Logs in a user and generates JWT tokens." + ) + @ApiResponse( + responseCode = "200", + description = "User logged in successfully" + ) 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<>( - "User " + email + " logged in successfully", - HttpStatus.OK); - } catch (Exception e) { - LOGGER.error(e.getMessage()); - return new ResponseEntity<>(e.getMessage(), - HttpStatus.UNAUTHORIZED); - } + String email = authenticationService.login(loginRequest, response); + LOGGER.info("User {} logged in", email); + return new ResponseEntity<>( + "User " + email + " logged in successfully", + HttpStatus.OK); } @PostMapping("/register") + @Operation( + summary = "Register", + description = "Registers a new user." + ) + @ApiResponse( + responseCode = "201", + description = "User registered successfully" + ) 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); - } + authenticationService.registerAccount(signupRequest); + LOGGER.info("User {} registered", signupRequest.getEmail()); + return new ResponseEntity<>("Account registered.", + HttpStatus.CREATED); } @PostMapping("/logout") + @Operation( + summary = "Logout", + description = "Logs out a user and invalidates JWT tokens." + ) + @ApiResponse( + responseCode = "200", + description = "User logged out successfully" + ) public ResponseEntity logoutUser(final HttpServletResponse response) { authenticationService.logoutUser(response); return new ResponseEntity<>("You've been signed out!", HttpStatus.OK); } @PostMapping("/refresh-token") + @Operation( + summary = "Refresh Token", + description = "Refreshes the JWT tokens for a logged-in user." + ) + @ApiResponse( + responseCode = "200", + description = "Token refreshed successfully" + ) public ResponseEntity refreshToken( final HttpServletRequest request, final HttpServletResponse response) { - try { - 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(), - HttpStatus.UNAUTHORIZED); - } + String email = authenticationService.refreshToken( + request, response); + LOGGER.info("User {} refreshed token", email); + return new ResponseEntity<>( + "User " + email + " refreshed tokens successfully", + HttpStatus.OK); } } diff --git a/src/main/java/com/podzilla/auth/controller/ResourceController.java b/src/main/java/com/podzilla/auth/controller/ResourceController.java deleted file mode 100644 index 62c464a..0000000 --- a/src/main/java/com/podzilla/auth/controller/ResourceController.java +++ /dev/null @@ -1,23 +0,0 @@ -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/exception/ErrorResponse.java b/src/main/java/com/podzilla/auth/exception/ErrorResponse.java new file mode 100644 index 0000000..f5fc0e8 --- /dev/null +++ b/src/main/java/com/podzilla/auth/exception/ErrorResponse.java @@ -0,0 +1,19 @@ +package com.podzilla.auth.exception; + +import lombok.Getter; +import org.springframework.http.HttpStatus; + +import java.time.LocalDateTime; + +@Getter +public class ErrorResponse { + private final String message; + private final HttpStatus status; + private final LocalDateTime timestamp; + + public ErrorResponse(final String message, final HttpStatus status) { + this.message = message; + this.status = status; + this.timestamp = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java b/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..527126e --- /dev/null +++ b/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java @@ -0,0 +1,42 @@ +package com.podzilla.auth.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity handleNotFoundException( + final NotFoundException exception) { + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.NOT_FOUND)); + } + + @ExceptionHandler(ValidationException.class) + public ResponseEntity handleValidationException( + final ValidationException exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.BAD_REQUEST)); + } + + @ExceptionHandler(InvalidActionException.class) + public ResponseEntity handleInvalidActionException( + final InvalidActionException exception) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.BAD_REQUEST)); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleException( + final Exception exception) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.INTERNAL_SERVER_ERROR)); + } +} diff --git a/src/main/java/com/podzilla/auth/exception/InvalidActionException.java b/src/main/java/com/podzilla/auth/exception/InvalidActionException.java new file mode 100644 index 0000000..b9ed654 --- /dev/null +++ b/src/main/java/com/podzilla/auth/exception/InvalidActionException.java @@ -0,0 +1,7 @@ +package com.podzilla.auth.exception; + +public class InvalidActionException extends RuntimeException { + public InvalidActionException(final String message) { + super("Invalid action: " + message); + } +} diff --git a/src/main/java/com/podzilla/auth/exception/NotFoundException.java b/src/main/java/com/podzilla/auth/exception/NotFoundException.java new file mode 100644 index 0000000..bd16723 --- /dev/null +++ b/src/main/java/com/podzilla/auth/exception/NotFoundException.java @@ -0,0 +1,7 @@ +package com.podzilla.auth.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException(final String message) { + super("Not Found: " + message); + } +} diff --git a/src/main/java/com/podzilla/auth/exception/ValidationException.java b/src/main/java/com/podzilla/auth/exception/ValidationException.java new file mode 100644 index 0000000..58df19a --- /dev/null +++ b/src/main/java/com/podzilla/auth/exception/ValidationException.java @@ -0,0 +1,7 @@ +package com.podzilla.auth.exception; + +public class ValidationException extends RuntimeException { + public ValidationException(final String message) { + super("Validation error: " + message); + } +} diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 7c8250d..22f70f5 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -2,12 +2,12 @@ import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; +import com.podzilla.auth.exception.ValidationException; 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.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; @@ -66,7 +66,7 @@ public String login(final LoginRequest loginRequest, public void registerAccount(final SignupRequest signupRequest) { if (userRepository.existsByEmail(signupRequest.getEmail())) { - throw new EntityExistsException("Email already used"); + throw new ValidationException("Email already in use."); } User account = new User( @@ -91,7 +91,7 @@ public String refreshToken(final HttpServletRequest request, jwtService.generateAccessToken(email, response); return email; } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Invalid refresh token"); + throw new ValidationException("Invalid refresh token."); } } } diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index 5e6da6e..aa23490 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -1,5 +1,6 @@ package com.podzilla.auth.service; +import com.podzilla.auth.exception.NotFoundException; import com.podzilla.auth.model.User; import com.podzilla.auth.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; @@ -7,7 +8,6 @@ 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; @@ -24,11 +24,10 @@ public CustomUserDetailsService(final UserRepository userRepository) { } @Override - public UserDetails loadUserByUsername(final String email) - throws UsernameNotFoundException { + public UserDetails loadUserByUsername(final String email) { User user = userRepository.findByEmail(email) .orElseThrow(() -> - new UsernameNotFoundException( + new NotFoundException( email + " not found.")); Set authorities = user diff --git a/src/main/java/com/podzilla/auth/service/JWTService.java b/src/main/java/com/podzilla/auth/service/JWTService.java index 8be6c33..e8577dc 100644 --- a/src/main/java/com/podzilla/auth/service/JWTService.java +++ b/src/main/java/com/podzilla/auth/service/JWTService.java @@ -1,5 +1,6 @@ package com.podzilla.auth.service; +import com.podzilla.auth.exception.ValidationException; import com.podzilla.auth.model.RefreshToken; import com.podzilla.auth.model.User; import com.podzilla.auth.repository.RefreshTokenRepository; @@ -9,11 +10,9 @@ 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; @@ -73,7 +72,7 @@ public void generateAccessToken(final String email, public void generateRefreshToken(final String email, final HttpServletResponse response) { User user = userRepository.findByEmail(email) - .orElseThrow(() -> new EntityExistsException("User not found")); + .orElseThrow(() -> new ValidationException("User not found")); RefreshToken userRefreshToken = refreshTokenRepository.findByUserIdAndExpiresAtAfter( user.getId(), Instant.now()).orElse(null); @@ -144,7 +143,7 @@ public String getRefreshTokenFromCookie(final HttpServletRequest request) { return null; } - public void validateAccessToken(final String token) throws JwtException { + public void validateAccessToken(final String token) { try { claims = Jwts.parser() .verifyWith(getSignInKey()) @@ -154,7 +153,7 @@ public void validateAccessToken(final String token) throws JwtException { } catch (JwtException e) { - throw new JwtException(e.getMessage()); + throw new ValidationException(e.getMessage()); } } From e86ada4309b3bb8e22f901cd978fab78ac95764e Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Mon, 28 Apr 2025 22:37:58 +0300 Subject: [PATCH 15/60] Add Swagger annotations for API documentation and implement custom exception handling --- .../podzilla/auth/controller/AuthenticationController.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index 7908203..78a9a31 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -12,7 +12,6 @@ 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; @@ -24,9 +23,6 @@ public class AuthenticationController { private final AuthenticationService authenticationService; - private final SecurityContextLogoutHandler logoutHandler = - new SecurityContextLogoutHandler(); - private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationController.class); @@ -65,8 +61,7 @@ public ResponseEntity login( description = "User registered successfully" ) public ResponseEntity registerUser( - @RequestBody final SignupRequest signupRequest, - final HttpServletRequest request) { + @RequestBody final SignupRequest signupRequest) { authenticationService.registerAccount(signupRequest); LOGGER.info("User {} registered", signupRequest.getEmail()); return new ResponseEntity<>("Account registered.", From cd51b0e7b937ed974e15e537078064b69b3d9188 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Mon, 28 Apr 2025 23:42:31 +0300 Subject: [PATCH 16/60] Configure SpringDoc OpenAPI settings and permit access to Swagger UI endpoints --- src/main/java/com/podzilla/auth/security/SecurityConfig.java | 2 ++ src/main/resources/application.properties | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index f28794c..5b6c710 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -47,6 +47,8 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) .requestMatchers("/api/auth/**").permitAll() .requestMatchers("/api/admin/**") .hasRole("ADMIN") + .requestMatchers("/swagger-ui/**", + "/v3/api-docs/**").permitAll() .anyRequest().authenticated() ) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3be705a..c2c1876 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,5 +1,9 @@ spring.application.name=auth +# SpringDoc OpenAPI configuration, uncomment on production +#springdoc.api-docs.enabled=false +#springdoc.swagger-ui.enabled=false + logging.file.name=./logs/app.log logging.level.root=info logging.level.com.podzilla.auth=debug From 251dc5b554aeb77568ed1d67e3768ddf1b872065 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:44:04 +0300 Subject: [PATCH 17/60] 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 18/60] 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 From deb3870e7620b9efe3d16a3f5e9f7b41575895fb Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:54:28 +0300 Subject: [PATCH 19/60] Add Redis caching support and update Docker configuration for Redis service --- docker-compose.yml | 20 +++++++++++++++++++ .../com/podzilla/auth/AuthApplication.java | 2 ++ .../service/CustomUserDetailsService.java | 2 ++ src/main/resources/application.properties | 5 +++++ 4 files changed, 29 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index ccc55e4..5139e23 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,7 @@ services: backend: image: openjdk:25-ea-4-jdk-oraclelinux9 + container_name: auth ports: - "8080:8080" env_file: @@ -9,6 +10,7 @@ services: - auth_db environment: - SPRING_DATASOURCE_URL=jdbc:postgresql://auth_db:5432/authDB + - SPRING_DATA_REDIS_HOST=redis_cache volumes: - ./target:/app - ./logs:/logs @@ -16,6 +18,7 @@ services: auth_db: image: postgres:latest + container_name: auth_db environment: POSTGRES_PASSWORD: 1234 POSTGRES_USER: postgres @@ -25,12 +28,14 @@ services: loki: image: grafana/loki:latest + container_name: loki ports: - "3100:3100" command: -config.file=/etc/loki/local-config.yaml promtail: image: grafana/promtail:latest + container_name: promtail volumes: - ./promtail-config.yml:/etc/promtail/promtail-config.yaml - ./logs:/logs @@ -40,7 +45,22 @@ services: grafana: image: grafana/grafana:latest + container_name: grafana ports: - "3000:3000" depends_on: - loki + + + redis_cache: + image: redis:latest + container_name: redisCache + ports: + - "6379:6379" + + redisinsight: + image: redis/redisinsight:latest + container_name: redisInsight + ports: + - "5540:5540" + restart: always \ No newline at end of file diff --git a/src/main/java/com/podzilla/auth/AuthApplication.java b/src/main/java/com/podzilla/auth/AuthApplication.java index cb6eb42..920bdd3 100644 --- a/src/main/java/com/podzilla/auth/AuthApplication.java +++ b/src/main/java/com/podzilla/auth/AuthApplication.java @@ -2,8 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication +@EnableCaching public class AuthApplication { public static void main(final String[] args) { diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index 5e6da6e..c2974c4 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -3,6 +3,7 @@ import com.podzilla.auth.model.User; import com.podzilla.auth.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -24,6 +25,7 @@ public CustomUserDetailsService(final UserRepository userRepository) { } @Override + @Cacheable(value = "userDetails", key = "#email") public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException { User user = userRepository.findByEmail(email) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e9d1807..135d881 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -4,6 +4,11 @@ logging.file.name=./logs/app.log logging.level.root=info logging.level.com.podzilla.auth=debug +spring.cache.type=redis + +spring.data.redis.host=localhost +spring.data.redis.port=6379 + spring.datasource.url=jdbc:postgresql://localhost:5432/authDB spring.datasource.username=postgres spring.datasource.password=1234 From 5068d722587fcd2ab8e086ad4d52d721345920a2 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 10:10:10 +0300 Subject: [PATCH 20/60] Update Docker images for PostgreSQL, Grafana, Loki, Promtail, Redis, and RedisInsight to specific versions --- docker-compose.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5139e23..a3d2810 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,7 +17,7 @@ services: command: [ "java", "-jar", "/app/auth-0.0.1-SNAPSHOT.jar" ] auth_db: - image: postgres:latest + image: postgres:14.17 container_name: auth_db environment: POSTGRES_PASSWORD: 1234 @@ -27,14 +27,14 @@ services: - "5432:5432" loki: - image: grafana/loki:latest + image: grafana/loki:3.5.0 container_name: loki ports: - "3100:3100" command: -config.file=/etc/loki/local-config.yaml promtail: - image: grafana/promtail:latest + image: grafana/promtail:3.5.0 container_name: promtail volumes: - ./promtail-config.yml:/etc/promtail/promtail-config.yaml @@ -44,7 +44,7 @@ services: - loki grafana: - image: grafana/grafana:latest + image: grafana/grafana:11.6.1 container_name: grafana ports: - "3000:3000" @@ -53,13 +53,13 @@ services: redis_cache: - image: redis:latest + image: redis:7.4.3 container_name: redisCache ports: - "6379:6379" redisinsight: - image: redis/redisinsight:latest + image: redis/redisinsight:2.68 container_name: redisInsight ports: - "5540:5540" From af4eecb8e26145f0ccc0aaaae124ea8d40158406 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:44:04 +0300 Subject: [PATCH 21/60] 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 e671dbf..29915ad 100644 --- a/src/main/java/com/podzilla/auth/controller/AdminController.java +++ b/src/main/java/com/podzilla/auth/controller/AdminController.java @@ -11,7 +11,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 78a9a31..f441f96 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -18,7 +18,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 5b6c710..d8b83f0 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") .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 22f70f5..406dd52 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 ValidationException("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 e8577dc..0cd086b 100644 --- a/src/main/java/com/podzilla/auth/service/JWTService.java +++ b/src/main/java/com/podzilla/auth/service/TokenService.java @@ -24,7 +24,7 @@ import java.util.UUID; @Service -public class JWTService { +public class TokenService { // set in .env @Value("${jwt.token.secret}") @@ -41,12 +41,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; } @@ -64,7 +67,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); } @@ -121,7 +124,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); } @@ -159,8 +162,8 @@ public void validateAccessToken(final String token) { 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); } @@ -168,7 +171,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 f5300fb0277ff59fc56fe5d715ae8a414935fe13 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:45:17 +0300 Subject: [PATCH 22/60] 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 c2c1876..be2b6ed 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -20,6 +20,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 From 4d13b4048585a759c400d2b4f06d5f79785b8e18 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:54:28 +0300 Subject: [PATCH 23/60] Add Redis caching support and update Docker configuration for Redis service # Conflicts: # src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java --- docker-compose.yml | 20 +++++++++++++++++++ .../com/podzilla/auth/AuthApplication.java | 2 ++ .../service/CustomUserDetailsService.java | 2 ++ src/main/resources/application.properties | 5 +++++ 4 files changed, 29 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index ccc55e4..5139e23 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,7 @@ services: backend: image: openjdk:25-ea-4-jdk-oraclelinux9 + container_name: auth ports: - "8080:8080" env_file: @@ -9,6 +10,7 @@ services: - auth_db environment: - SPRING_DATASOURCE_URL=jdbc:postgresql://auth_db:5432/authDB + - SPRING_DATA_REDIS_HOST=redis_cache volumes: - ./target:/app - ./logs:/logs @@ -16,6 +18,7 @@ services: auth_db: image: postgres:latest + container_name: auth_db environment: POSTGRES_PASSWORD: 1234 POSTGRES_USER: postgres @@ -25,12 +28,14 @@ services: loki: image: grafana/loki:latest + container_name: loki ports: - "3100:3100" command: -config.file=/etc/loki/local-config.yaml promtail: image: grafana/promtail:latest + container_name: promtail volumes: - ./promtail-config.yml:/etc/promtail/promtail-config.yaml - ./logs:/logs @@ -40,7 +45,22 @@ services: grafana: image: grafana/grafana:latest + container_name: grafana ports: - "3000:3000" depends_on: - loki + + + redis_cache: + image: redis:latest + container_name: redisCache + ports: + - "6379:6379" + + redisinsight: + image: redis/redisinsight:latest + container_name: redisInsight + ports: + - "5540:5540" + restart: always \ No newline at end of file diff --git a/src/main/java/com/podzilla/auth/AuthApplication.java b/src/main/java/com/podzilla/auth/AuthApplication.java index cb6eb42..920bdd3 100644 --- a/src/main/java/com/podzilla/auth/AuthApplication.java +++ b/src/main/java/com/podzilla/auth/AuthApplication.java @@ -2,8 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication +@EnableCaching public class AuthApplication { public static void main(final String[] args) { diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index aa23490..48b2c2c 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -4,6 +4,7 @@ import com.podzilla.auth.model.User; import com.podzilla.auth.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -24,6 +25,7 @@ public CustomUserDetailsService(final UserRepository userRepository) { } @Override + @Cacheable(value = "userDetails", key = "#email") public UserDetails loadUserByUsername(final String email) { User user = userRepository.findByEmail(email) .orElseThrow(() -> diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index be2b6ed..e7e6d89 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -8,6 +8,11 @@ logging.file.name=./logs/app.log logging.level.root=info logging.level.com.podzilla.auth=debug +spring.cache.type=redis + +spring.data.redis.host=localhost +spring.data.redis.port=6379 + spring.datasource.url=jdbc:postgresql://localhost:5432/authDB spring.datasource.username=postgres spring.datasource.password=1234 From 20c7ad4a96b42a4177aea36ed92eaf18622d44ca Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 10:10:10 +0300 Subject: [PATCH 24/60] Update Docker images for PostgreSQL, Grafana, Loki, Promtail, Redis, and RedisInsight to specific versions --- docker-compose.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5139e23..a3d2810 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,7 +17,7 @@ services: command: [ "java", "-jar", "/app/auth-0.0.1-SNAPSHOT.jar" ] auth_db: - image: postgres:latest + image: postgres:14.17 container_name: auth_db environment: POSTGRES_PASSWORD: 1234 @@ -27,14 +27,14 @@ services: - "5432:5432" loki: - image: grafana/loki:latest + image: grafana/loki:3.5.0 container_name: loki ports: - "3100:3100" command: -config.file=/etc/loki/local-config.yaml promtail: - image: grafana/promtail:latest + image: grafana/promtail:3.5.0 container_name: promtail volumes: - ./promtail-config.yml:/etc/promtail/promtail-config.yaml @@ -44,7 +44,7 @@ services: - loki grafana: - image: grafana/grafana:latest + image: grafana/grafana:11.6.1 container_name: grafana ports: - "3000:3000" @@ -53,13 +53,13 @@ services: redis_cache: - image: redis:latest + image: redis:7.4.3 container_name: redisCache ports: - "6379:6379" redisinsight: - image: redis/redisinsight:latest + image: redis/redisinsight:2.68 container_name: redisInsight ports: - "5540:5540" From 715f23510caa056403f02d26415e2d5d3ba7fb3b Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 12:08:30 +0300 Subject: [PATCH 25/60] Enhance global exception handling and logging for authentication errors; update .gitignore to exclude logs and sensitive files --- .gitignore | 3 +++ .../exception/GlobalExceptionHandler.java | 22 ++++++++++++++++++- .../security/JWTAuthenticationFilter.java | 2 +- .../RestAuthenticationEntryPoint.java | 22 ------------------- .../auth/security/SecurityConfig.java | 11 +--------- 5 files changed, 26 insertions(+), 34 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java diff --git a/.gitignore b/.gitignore index 549e00a..4e0b5cf 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/**/target/ !**/src/test/**/target/ +logs/ +*.log +secret.env ### STS ### .apt_generated diff --git a/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java b/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java index 527126e..19eb55d 100644 --- a/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java @@ -2,11 +2,31 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @RestControllerAdvice -public class GlobalExceptionHandler { +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + + + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity handleAccessDeniedException( + final AccessDeniedException exception) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.FORBIDDEN)); + } + + @ExceptionHandler(AuthenticationException.class) + public ResponseEntity handleAuthenticationException( + final AuthenticationException exception) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.UNAUTHORIZED)); + } @ExceptionHandler(NotFoundException.class) public ResponseEntity handleNotFoundException( diff --git a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java index 34d1297..a2d2855 100644 --- a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java +++ b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java @@ -62,7 +62,7 @@ protected void doFilterInternal(final HttpServletRequest request, context.setAuthentication(authToken); SecurityContextHolder.setContext(context); - + LOGGER.info("User {} authenticated", userEmail); } catch (Exception e) { LOGGER.error("Invalid JWT token: {}", e.getMessage()); } diff --git a/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java b/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java deleted file mode 100644 index 2351372..0000000 --- a/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java +++ /dev/null @@ -1,22 +0,0 @@ -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 index d8b83f0..0185922 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -2,7 +2,6 @@ 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; @@ -35,22 +34,14 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) .csrf(AbstractHttpConfigurer::disable) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) - .exceptionHandling(exceptionHandling -> - exceptionHandling - .authenticationEntryPoint( - new RestAuthenticationEntryPoint()) - ) .authorizeHttpRequests((auth) -> - auth.requestMatchers( - HttpMethod.GET, "public_resource") - .permitAll() + auth .requestMatchers("/auth/**").permitAll() .requestMatchers("/admin/**") .hasRole("ADMIN") .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() .anyRequest().authenticated() - ) .sessionManagement(s -> s .sessionCreationPolicy( From 27961565eea910d64774cbf8df3323b14d8f15d2 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 13:34:36 +0300 Subject: [PATCH 26/60] Refactor authentication and token management: use builder pattern for User and RefreshToken; enhance logout functionality to expire refresh tokens --- .../com/podzilla/auth/model/RefreshToken.java | 6 ++- .../auth/security/SecurityConfig.java | 3 +- .../auth/service/AuthenticationService.java | 17 +++++--- .../podzilla/auth/service/TokenService.java | 41 ++++++++++++++----- 4 files changed, 48 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/podzilla/auth/model/RefreshToken.java b/src/main/java/com/podzilla/auth/model/RefreshToken.java index 7f7da62..3405a08 100644 --- a/src/main/java/com/podzilla/auth/model/RefreshToken.java +++ b/src/main/java/com/podzilla/auth/model/RefreshToken.java @@ -9,9 +9,11 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Column; import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @@ -21,8 +23,10 @@ @Entity @Table(name = "refresh_tokens") @Getter +@Builder @Setter @NoArgsConstructor +@AllArgsConstructor @EntityListeners(AuditingEntityListener.class) public class RefreshToken { diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index 0185922..cec1dce 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -36,7 +36,8 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) UsernamePasswordAuthenticationFilter.class) .authorizeHttpRequests((auth) -> auth - .requestMatchers("/auth/**").permitAll() + .requestMatchers("/auth/login").permitAll() + .requestMatchers("/auth/register").permitAll() .requestMatchers("/admin/**") .hasRole("ADMIN") .requestMatchers("/swagger-ui/**", diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 406dd52..f8f942f 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -69,18 +69,23 @@ public void registerAccount(final SignupRequest signupRequest) { throw new ValidationException("Email already in use."); } - User account = new User( - signupRequest.getName(), - signupRequest.getEmail(), - passwordEncoder.encode(signupRequest.getPassword())); + User account = + User.builder() + .name(signupRequest.getName()) + .email(signupRequest.getEmail()) + .password( + passwordEncoder.encode( + signupRequest.getPassword())) + .build(); Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); account.setRoles(Collections.singleton(role)); userRepository.save(account); } - public void logoutUser(final HttpServletResponse response) { + public void logoutUser( + final HttpServletResponse response) { tokenService.removeAccessTokenFromCookie(response); - tokenService.removeRefreshTokenFromCookie(response); + tokenService.removeRefreshTokenFromCookieAndExpire(response); } public String refreshToken(final HttpServletRequest request, diff --git a/src/main/java/com/podzilla/auth/service/TokenService.java b/src/main/java/com/podzilla/auth/service/TokenService.java index 0cd086b..bd186ca 100644 --- a/src/main/java/com/podzilla/auth/service/TokenService.java +++ b/src/main/java/com/podzilla/auth/service/TokenService.java @@ -81,11 +81,12 @@ public void generateRefreshToken(final String email, 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)); + userRefreshToken = + RefreshToken.builder() + .user(user) + .createdAt(Instant.now()) + .expiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)).build(); refreshTokenRepository.save(userRefreshToken); } @@ -106,11 +107,12 @@ public String renewRefreshToken(final String refreshToken, token.setExpiresAt(Instant.now()); refreshTokenRepository.save(token); - RefreshToken newRefreshToken = new RefreshToken(); - newRefreshToken.setUser(token.getUser()); - newRefreshToken.setCreatedAt(Instant.now()); - newRefreshToken.setExpiresAt(Instant.now().plus( - REFRESH_TOKEN_EXPIRATION_TIME)); + RefreshToken newRefreshToken = + RefreshToken.builder() + .user(token.getUser()) + .createdAt(Instant.now()) + .expiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)).build(); refreshTokenRepository.save(newRefreshToken); String newRefreshTokenString = newRefreshToken.getId().toString(); @@ -168,14 +170,31 @@ public void removeAccessTokenFromCookie( response.addCookie(cookie); } - public void removeRefreshTokenFromCookie( + public void removeRefreshTokenFromCookieAndExpire( final HttpServletResponse response) { + String userEmail = extractEmail(); + User user = + userRepository.findByEmail(userEmail) + .orElseThrow(() -> new ValidationException( + "User not found")); + RefreshToken refreshToken = + refreshTokenRepository.findByUserIdAndExpiresAtAfter( + user.getId(), Instant.now()).orElseThrow( + () -> new ValidationException( + "Refresh token not found")); + expireRefreshToken(refreshToken); + Cookie cookie = new Cookie("refreshToken", null); cookie.setPath(REFRESH_TOKEN_COOKIE_PATH); response.addCookie(cookie); } + private void expireRefreshToken(final RefreshToken token) { + token.setExpiresAt(Instant.now()); + refreshTokenRepository.save(token); + } + private SecretKey getSignInKey() { byte[] keyBytes = Decoders.BASE64.decode(this.secret); return Keys.hmacShaKeyFor(keyBytes); From 6853011dff08c27529c10aee73d67609c5f97b13 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 13:45:20 +0300 Subject: [PATCH 27/60] Update security configuration to permit access to refresh token endpoint --- .../com/podzilla/auth/security/SecurityConfig.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index cec1dce..fef3d0c 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -36,12 +36,17 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) UsernamePasswordAuthenticationFilter.class) .authorizeHttpRequests((auth) -> auth - .requestMatchers("/auth/login").permitAll() - .requestMatchers("/auth/register").permitAll() + .requestMatchers("/auth/login") + .permitAll() + .requestMatchers("/auth/register") + .permitAll() + .requestMatchers("/auth/refresh-token") + .permitAll() .requestMatchers("/admin/**") .hasRole("ADMIN") .requestMatchers("/swagger-ui/**", - "/v3/api-docs/**").permitAll() + "/v3/api-docs/**") + .permitAll() .anyRequest().authenticated() ) .sessionManagement(s -> s From 0d6d7215fc2d3a813ae7d91298f8aab5406bb7b6 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 10:27:29 +0300 Subject: [PATCH 28/60] Implement custom user details and enhance authentication: add CustomUserDetails class, update login and registration logic, and configure Redis cache manager --- .../podzilla/auth/dto/CustomUserDetails.java | 42 +++++++++++++++++++ .../podzilla/auth/redis/RedisCacheConfig.java | 38 +++++++++++++++++ .../auth/service/AuthenticationService.java | 7 ++++ .../service/CustomUserDetailsService.java | 3 +- 4 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/podzilla/auth/dto/CustomUserDetails.java create mode 100644 src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java diff --git a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java new file mode 100644 index 0000000..e1db335 --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java @@ -0,0 +1,42 @@ +package com.podzilla.auth.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.Set; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CustomUserDetails implements UserDetails { + + private String username; + private String password; + private Set authorities; + + public CustomUserDetails() { + // No-arg constructor required by Jackson + } + + public CustomUserDetails(final String username, final String password, + final Set authorities) { + this.username = username; + this.password = password; + this.authorities = authorities; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public Collection getAuthorities() { + return authorities; + } +} diff --git a/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java b/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java new file mode 100644 index 0000000..93ed31a --- /dev/null +++ b/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java @@ -0,0 +1,38 @@ +package com.podzilla.auth.redis; + +import com.podzilla.auth.dto.CustomUserDetails; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; + +import java.time.Duration; + +@Configuration +public class RedisCacheConfig { + + private static final int CACHE_TTL = 60 * 60; + + @Bean + public RedisCacheManager cacheManager( + final RedisConnectionFactory redisConnectionFactory) { + + RedisCacheConfiguration defaultConfig = RedisCacheConfiguration + .defaultCacheConfig() + .entryTtl(Duration.ofMinutes(CACHE_TTL)) + .disableCachingNullValues() + .serializeValuesWith( + RedisSerializationContext. + SerializationPair. + fromSerializer( + new Jackson2JsonRedisSerializer<>( + CustomUserDetails.class))); + + return RedisCacheManager.builder(redisConnectionFactory) + .cacheDefaults(defaultConfig) + .build(); + } +} diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index f8f942f..708134e 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -46,6 +46,9 @@ public AuthenticationService( public String login(final LoginRequest loginRequest, final HttpServletResponse response) { + System.out.println("Login request: " + loginRequest.getEmail() + + " " + loginRequest.getPassword()); + Authentication authenticationRequest = UsernamePasswordAuthenticationToken. unauthenticated( @@ -65,6 +68,10 @@ public String login(final LoginRequest loginRequest, } public void registerAccount(final SignupRequest signupRequest) { + if (signupRequest.getPassword().isEmpty()) { + throw new ValidationException("Password cannot be empty."); + } + if (userRepository.existsByEmail(signupRequest.getEmail())) { throw new ValidationException("Email already in use."); } diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index 48b2c2c..5af441f 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -1,5 +1,6 @@ package com.podzilla.auth.service; +import com.podzilla.auth.dto.CustomUserDetails; import com.podzilla.auth.exception.NotFoundException; import com.podzilla.auth.model.User; import com.podzilla.auth.repository.UserRepository; @@ -39,7 +40,7 @@ public UserDetails loadUserByUsername(final String email) { role.getErole().name())) .collect(Collectors.toSet()); - return new org.springframework.security.core.userdetails.User( + return new CustomUserDetails( user.getEmail(), user.getPassword(), authorities From 274eb0606214ca21973fd5dcff1fc2d65ea39174 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 16:06:43 +0300 Subject: [PATCH 29/60] 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 8d93c55906b97dd69df71d9dae9ef849f6da8a62 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 16:20:00 +0300 Subject: [PATCH 30/60] Fix authApplication --- tmp | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 tmp diff --git a/tmp b/tmp deleted file mode 100644 index e69de29..0000000 From 9c942a08768b510ddad4e6e04ae49a924d0c285f Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 18:39:32 +0300 Subject: [PATCH 31/60] Add refresh token --- .../java/com/podzilla/auth/dto/AuthenticationResponse.java | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java 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) { +} From b177e81f845ac03995e1f55b6f9752e85c8dc788 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sun, 27 Apr 2025 22:37:46 +0300 Subject: [PATCH 32/60] Add refresh token to the cookie instead of returning it back to the frontend. --- .../java/com/podzilla/auth/dto/AuthenticationResponse.java | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/dto/AuthenticationResponse.java 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) { -} From 70e0cefacc2b2b1a4068d3d4dbdd36c719f17dbe Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Mon, 28 Apr 2025 20:22:52 +0300 Subject: [PATCH 33/60] Rename signup endpoint to register and enhance refresh token management --- .../auth/controller/ResourceController.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/main/java/com/podzilla/auth/controller/ResourceController.java 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); + } +} From 35b27e7019d3bfc9fa90dd2501a9db313c89c75c Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Mon, 28 Apr 2025 22:37:19 +0300 Subject: [PATCH 34/60] Add Swagger annotations for API documentation and implement custom exception handling --- .../auth/controller/ResourceController.java | 23 ------------------- 1 file changed, 23 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/controller/ResourceController.java diff --git a/src/main/java/com/podzilla/auth/controller/ResourceController.java b/src/main/java/com/podzilla/auth/controller/ResourceController.java deleted file mode 100644 index 62c464a..0000000 --- a/src/main/java/com/podzilla/auth/controller/ResourceController.java +++ /dev/null @@ -1,23 +0,0 @@ -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); - } -} From aa71af96944f7b2ebe529eead54c66cace418ab9 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:44:04 +0300 Subject: [PATCH 35/60] Refactor API endpoints and rename JWTService to TokenService --- .../com/podzilla/auth/service/JWTService.java | 185 ------------------ .../podzilla/auth/service/TokenService.java | 9 +- 2 files changed, 4 insertions(+), 190 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/service/JWTService.java diff --git a/src/main/java/com/podzilla/auth/service/JWTService.java b/src/main/java/com/podzilla/auth/service/JWTService.java deleted file mode 100644 index e8577dc..0000000 --- a/src/main/java/com/podzilla/auth/service/JWTService.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.podzilla.auth.service; - -import com.podzilla.auth.exception.ValidationException; -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.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.time.Instant; -import java.time.temporal.TemporalAmount; -import java.util.Date; -import java.util.UUID; - -@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 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; - - 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 * ACCESS_TOKEN_EXPIRATION_TIME)) - .signWith(getSignInKey()) - .compact(); - - Cookie cookie = new Cookie("accessToken", jwt); - cookie.setHttpOnly(true); - cookie.setSecure(true); - cookie.setPath("/"); - 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 ValidationException("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); - } - - String refreshTokenString = userRefreshToken.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.setCreatedAt(Instant.now()); - 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 getAccessTokenFromCookie(final HttpServletRequest request) { - Cookie cookie = WebUtils.getCookie(request, "accessToken"); - if (cookie != null) { - return cookie.getValue(); - } - return null; - - } - - 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) { - try { - claims = Jwts.parser() - .verifyWith(getSignInKey()) - .build() - .parseSignedClaims(token) - .getPayload(); - - - } catch (JwtException e) { - throw new ValidationException(e.getMessage()); - } - } - - 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); - } - - public String extractEmail() { - return claims.getSubject(); - } - -} diff --git a/src/main/java/com/podzilla/auth/service/TokenService.java b/src/main/java/com/podzilla/auth/service/TokenService.java index 9fb564c..0cd086b 100644 --- a/src/main/java/com/podzilla/auth/service/TokenService.java +++ b/src/main/java/com/podzilla/auth/service/TokenService.java @@ -1,5 +1,6 @@ package com.podzilla.auth.service; +import com.podzilla.auth.exception.ValidationException; import com.podzilla.auth.model.RefreshToken; import com.podzilla.auth.model.User; import com.podzilla.auth.repository.RefreshTokenRepository; @@ -9,11 +10,9 @@ 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; @@ -76,7 +75,7 @@ public void generateAccessToken(final String email, public void generateRefreshToken(final String email, final HttpServletResponse response) { User user = userRepository.findByEmail(email) - .orElseThrow(() -> new EntityExistsException("User not found")); + .orElseThrow(() -> new ValidationException("User not found")); RefreshToken userRefreshToken = refreshTokenRepository.findByUserIdAndExpiresAtAfter( user.getId(), Instant.now()).orElse(null); @@ -147,7 +146,7 @@ public String getRefreshTokenFromCookie(final HttpServletRequest request) { return null; } - public void validateAccessToken(final String token) throws JwtException { + public void validateAccessToken(final String token) { try { claims = Jwts.parser() .verifyWith(getSignInKey()) @@ -157,7 +156,7 @@ public void validateAccessToken(final String token) throws JwtException { } catch (JwtException e) { - throw new JwtException(e.getMessage()); + throw new ValidationException(e.getMessage()); } } From b4f97503067f7d6827cf68f79e639332fe31839d Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 09:54:28 +0300 Subject: [PATCH 36/60] Add Redis caching support and update Docker configuration for Redis service # Conflicts: # src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java --- docker-compose.yml | 20 +++++++++++++++++++ .../com/podzilla/auth/AuthApplication.java | 2 ++ .../service/CustomUserDetailsService.java | 2 ++ src/main/resources/application.properties | 5 +++++ 4 files changed, 29 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index ccc55e4..5139e23 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,7 @@ services: backend: image: openjdk:25-ea-4-jdk-oraclelinux9 + container_name: auth ports: - "8080:8080" env_file: @@ -9,6 +10,7 @@ services: - auth_db environment: - SPRING_DATASOURCE_URL=jdbc:postgresql://auth_db:5432/authDB + - SPRING_DATA_REDIS_HOST=redis_cache volumes: - ./target:/app - ./logs:/logs @@ -16,6 +18,7 @@ services: auth_db: image: postgres:latest + container_name: auth_db environment: POSTGRES_PASSWORD: 1234 POSTGRES_USER: postgres @@ -25,12 +28,14 @@ services: loki: image: grafana/loki:latest + container_name: loki ports: - "3100:3100" command: -config.file=/etc/loki/local-config.yaml promtail: image: grafana/promtail:latest + container_name: promtail volumes: - ./promtail-config.yml:/etc/promtail/promtail-config.yaml - ./logs:/logs @@ -40,7 +45,22 @@ services: grafana: image: grafana/grafana:latest + container_name: grafana ports: - "3000:3000" depends_on: - loki + + + redis_cache: + image: redis:latest + container_name: redisCache + ports: + - "6379:6379" + + redisinsight: + image: redis/redisinsight:latest + container_name: redisInsight + ports: + - "5540:5540" + restart: always \ No newline at end of file diff --git a/src/main/java/com/podzilla/auth/AuthApplication.java b/src/main/java/com/podzilla/auth/AuthApplication.java index cb6eb42..920bdd3 100644 --- a/src/main/java/com/podzilla/auth/AuthApplication.java +++ b/src/main/java/com/podzilla/auth/AuthApplication.java @@ -2,8 +2,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication +@EnableCaching public class AuthApplication { public static void main(final String[] args) { diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index aa23490..48b2c2c 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -4,6 +4,7 @@ import com.podzilla.auth.model.User; import com.podzilla.auth.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -24,6 +25,7 @@ public CustomUserDetailsService(final UserRepository userRepository) { } @Override + @Cacheable(value = "userDetails", key = "#email") public UserDetails loadUserByUsername(final String email) { User user = userRepository.findByEmail(email) .orElseThrow(() -> diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index be2b6ed..e7e6d89 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -8,6 +8,11 @@ logging.file.name=./logs/app.log logging.level.root=info logging.level.com.podzilla.auth=debug +spring.cache.type=redis + +spring.data.redis.host=localhost +spring.data.redis.port=6379 + spring.datasource.url=jdbc:postgresql://localhost:5432/authDB spring.datasource.username=postgres spring.datasource.password=1234 From 4efc87399c4236c5aadc9d3f0d0c1f664f52cb05 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 10:10:10 +0300 Subject: [PATCH 37/60] Update Docker images for PostgreSQL, Grafana, Loki, Promtail, Redis, and RedisInsight to specific versions --- docker-compose.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5139e23..a3d2810 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,7 +17,7 @@ services: command: [ "java", "-jar", "/app/auth-0.0.1-SNAPSHOT.jar" ] auth_db: - image: postgres:latest + image: postgres:14.17 container_name: auth_db environment: POSTGRES_PASSWORD: 1234 @@ -27,14 +27,14 @@ services: - "5432:5432" loki: - image: grafana/loki:latest + image: grafana/loki:3.5.0 container_name: loki ports: - "3100:3100" command: -config.file=/etc/loki/local-config.yaml promtail: - image: grafana/promtail:latest + image: grafana/promtail:3.5.0 container_name: promtail volumes: - ./promtail-config.yml:/etc/promtail/promtail-config.yaml @@ -44,7 +44,7 @@ services: - loki grafana: - image: grafana/grafana:latest + image: grafana/grafana:11.6.1 container_name: grafana ports: - "3000:3000" @@ -53,13 +53,13 @@ services: redis_cache: - image: redis:latest + image: redis:7.4.3 container_name: redisCache ports: - "6379:6379" redisinsight: - image: redis/redisinsight:latest + image: redis/redisinsight:2.68 container_name: redisInsight ports: - "5540:5540" From 2df2cb3b744ad89785e903b70b22108a1e8190f1 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 12:08:30 +0300 Subject: [PATCH 38/60] Enhance global exception handling and logging for authentication errors; update .gitignore to exclude logs and sensitive files --- .gitignore | 3 +++ .../exception/GlobalExceptionHandler.java | 22 ++++++++++++++++++- .../security/JWTAuthenticationFilter.java | 2 +- .../RestAuthenticationEntryPoint.java | 22 ------------------- .../auth/security/SecurityConfig.java | 11 +--------- 5 files changed, 26 insertions(+), 34 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java diff --git a/.gitignore b/.gitignore index 549e00a..4e0b5cf 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/**/target/ !**/src/test/**/target/ +logs/ +*.log +secret.env ### STS ### .apt_generated diff --git a/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java b/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java index 527126e..19eb55d 100644 --- a/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/podzilla/auth/exception/GlobalExceptionHandler.java @@ -2,11 +2,31 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @RestControllerAdvice -public class GlobalExceptionHandler { +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + + + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity handleAccessDeniedException( + final AccessDeniedException exception) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.FORBIDDEN)); + } + + @ExceptionHandler(AuthenticationException.class) + public ResponseEntity handleAuthenticationException( + final AuthenticationException exception) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(new ErrorResponse(exception.getMessage(), + HttpStatus.UNAUTHORIZED)); + } @ExceptionHandler(NotFoundException.class) public ResponseEntity handleNotFoundException( diff --git a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java index 34d1297..a2d2855 100644 --- a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java +++ b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java @@ -62,7 +62,7 @@ protected void doFilterInternal(final HttpServletRequest request, context.setAuthentication(authToken); SecurityContextHolder.setContext(context); - + LOGGER.info("User {} authenticated", userEmail); } catch (Exception e) { LOGGER.error("Invalid JWT token: {}", e.getMessage()); } diff --git a/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java b/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java deleted file mode 100644 index 2351372..0000000 --- a/src/main/java/com/podzilla/auth/security/RestAuthenticationEntryPoint.java +++ /dev/null @@ -1,22 +0,0 @@ -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 index d8b83f0..0185922 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -2,7 +2,6 @@ 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; @@ -35,22 +34,14 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) .csrf(AbstractHttpConfigurer::disable) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) - .exceptionHandling(exceptionHandling -> - exceptionHandling - .authenticationEntryPoint( - new RestAuthenticationEntryPoint()) - ) .authorizeHttpRequests((auth) -> - auth.requestMatchers( - HttpMethod.GET, "public_resource") - .permitAll() + auth .requestMatchers("/auth/**").permitAll() .requestMatchers("/admin/**") .hasRole("ADMIN") .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() .anyRequest().authenticated() - ) .sessionManagement(s -> s .sessionCreationPolicy( From 18b0a65cf2a586e9ead9aa36675823d4957bbf80 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 13:34:36 +0300 Subject: [PATCH 39/60] Refactor authentication and token management: use builder pattern for User and RefreshToken; enhance logout functionality to expire refresh tokens --- .../com/podzilla/auth/model/RefreshToken.java | 6 ++- .../auth/security/SecurityConfig.java | 3 +- .../auth/service/AuthenticationService.java | 17 +++++--- .../podzilla/auth/service/TokenService.java | 41 ++++++++++++++----- 4 files changed, 48 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/podzilla/auth/model/RefreshToken.java b/src/main/java/com/podzilla/auth/model/RefreshToken.java index 7f7da62..3405a08 100644 --- a/src/main/java/com/podzilla/auth/model/RefreshToken.java +++ b/src/main/java/com/podzilla/auth/model/RefreshToken.java @@ -9,9 +9,11 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Column; import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import lombok.Setter; +import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @@ -21,8 +23,10 @@ @Entity @Table(name = "refresh_tokens") @Getter +@Builder @Setter @NoArgsConstructor +@AllArgsConstructor @EntityListeners(AuditingEntityListener.class) public class RefreshToken { diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index 0185922..cec1dce 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -36,7 +36,8 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) UsernamePasswordAuthenticationFilter.class) .authorizeHttpRequests((auth) -> auth - .requestMatchers("/auth/**").permitAll() + .requestMatchers("/auth/login").permitAll() + .requestMatchers("/auth/register").permitAll() .requestMatchers("/admin/**") .hasRole("ADMIN") .requestMatchers("/swagger-ui/**", diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 406dd52..f8f942f 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -69,18 +69,23 @@ public void registerAccount(final SignupRequest signupRequest) { throw new ValidationException("Email already in use."); } - User account = new User( - signupRequest.getName(), - signupRequest.getEmail(), - passwordEncoder.encode(signupRequest.getPassword())); + User account = + User.builder() + .name(signupRequest.getName()) + .email(signupRequest.getEmail()) + .password( + passwordEncoder.encode( + signupRequest.getPassword())) + .build(); Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); account.setRoles(Collections.singleton(role)); userRepository.save(account); } - public void logoutUser(final HttpServletResponse response) { + public void logoutUser( + final HttpServletResponse response) { tokenService.removeAccessTokenFromCookie(response); - tokenService.removeRefreshTokenFromCookie(response); + tokenService.removeRefreshTokenFromCookieAndExpire(response); } public String refreshToken(final HttpServletRequest request, diff --git a/src/main/java/com/podzilla/auth/service/TokenService.java b/src/main/java/com/podzilla/auth/service/TokenService.java index 0cd086b..bd186ca 100644 --- a/src/main/java/com/podzilla/auth/service/TokenService.java +++ b/src/main/java/com/podzilla/auth/service/TokenService.java @@ -81,11 +81,12 @@ public void generateRefreshToken(final String email, 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)); + userRefreshToken = + RefreshToken.builder() + .user(user) + .createdAt(Instant.now()) + .expiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)).build(); refreshTokenRepository.save(userRefreshToken); } @@ -106,11 +107,12 @@ public String renewRefreshToken(final String refreshToken, token.setExpiresAt(Instant.now()); refreshTokenRepository.save(token); - RefreshToken newRefreshToken = new RefreshToken(); - newRefreshToken.setUser(token.getUser()); - newRefreshToken.setCreatedAt(Instant.now()); - newRefreshToken.setExpiresAt(Instant.now().plus( - REFRESH_TOKEN_EXPIRATION_TIME)); + RefreshToken newRefreshToken = + RefreshToken.builder() + .user(token.getUser()) + .createdAt(Instant.now()) + .expiresAt(Instant.now().plus( + REFRESH_TOKEN_EXPIRATION_TIME)).build(); refreshTokenRepository.save(newRefreshToken); String newRefreshTokenString = newRefreshToken.getId().toString(); @@ -168,14 +170,31 @@ public void removeAccessTokenFromCookie( response.addCookie(cookie); } - public void removeRefreshTokenFromCookie( + public void removeRefreshTokenFromCookieAndExpire( final HttpServletResponse response) { + String userEmail = extractEmail(); + User user = + userRepository.findByEmail(userEmail) + .orElseThrow(() -> new ValidationException( + "User not found")); + RefreshToken refreshToken = + refreshTokenRepository.findByUserIdAndExpiresAtAfter( + user.getId(), Instant.now()).orElseThrow( + () -> new ValidationException( + "Refresh token not found")); + expireRefreshToken(refreshToken); + Cookie cookie = new Cookie("refreshToken", null); cookie.setPath(REFRESH_TOKEN_COOKIE_PATH); response.addCookie(cookie); } + private void expireRefreshToken(final RefreshToken token) { + token.setExpiresAt(Instant.now()); + refreshTokenRepository.save(token); + } + private SecretKey getSignInKey() { byte[] keyBytes = Decoders.BASE64.decode(this.secret); return Keys.hmacShaKeyFor(keyBytes); From 6ca3a559837e37a0c6760af63dbc3f7e4718cbf7 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Wed, 30 Apr 2025 13:45:20 +0300 Subject: [PATCH 40/60] Update security configuration to permit access to refresh token endpoint --- .../com/podzilla/auth/security/SecurityConfig.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index cec1dce..fef3d0c 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -36,12 +36,17 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) UsernamePasswordAuthenticationFilter.class) .authorizeHttpRequests((auth) -> auth - .requestMatchers("/auth/login").permitAll() - .requestMatchers("/auth/register").permitAll() + .requestMatchers("/auth/login") + .permitAll() + .requestMatchers("/auth/register") + .permitAll() + .requestMatchers("/auth/refresh-token") + .permitAll() .requestMatchers("/admin/**") .hasRole("ADMIN") .requestMatchers("/swagger-ui/**", - "/v3/api-docs/**").permitAll() + "/v3/api-docs/**") + .permitAll() .anyRequest().authenticated() ) .sessionManagement(s -> s From 78f2eb6f7a98df6519795918827a107ed2fb562b Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 10:27:29 +0300 Subject: [PATCH 41/60] Implement custom user details and enhance authentication: add CustomUserDetails class, update login and registration logic, and configure Redis cache manager --- .../podzilla/auth/dto/CustomUserDetails.java | 42 +++++++++++++++++++ .../podzilla/auth/redis/RedisCacheConfig.java | 38 +++++++++++++++++ .../auth/service/AuthenticationService.java | 7 ++++ .../service/CustomUserDetailsService.java | 3 +- 4 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/podzilla/auth/dto/CustomUserDetails.java create mode 100644 src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java diff --git a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java new file mode 100644 index 0000000..e1db335 --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java @@ -0,0 +1,42 @@ +package com.podzilla.auth.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.Set; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CustomUserDetails implements UserDetails { + + private String username; + private String password; + private Set authorities; + + public CustomUserDetails() { + // No-arg constructor required by Jackson + } + + public CustomUserDetails(final String username, final String password, + final Set authorities) { + this.username = username; + this.password = password; + this.authorities = authorities; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public Collection getAuthorities() { + return authorities; + } +} diff --git a/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java b/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java new file mode 100644 index 0000000..93ed31a --- /dev/null +++ b/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java @@ -0,0 +1,38 @@ +package com.podzilla.auth.redis; + +import com.podzilla.auth.dto.CustomUserDetails; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; + +import java.time.Duration; + +@Configuration +public class RedisCacheConfig { + + private static final int CACHE_TTL = 60 * 60; + + @Bean + public RedisCacheManager cacheManager( + final RedisConnectionFactory redisConnectionFactory) { + + RedisCacheConfiguration defaultConfig = RedisCacheConfiguration + .defaultCacheConfig() + .entryTtl(Duration.ofMinutes(CACHE_TTL)) + .disableCachingNullValues() + .serializeValuesWith( + RedisSerializationContext. + SerializationPair. + fromSerializer( + new Jackson2JsonRedisSerializer<>( + CustomUserDetails.class))); + + return RedisCacheManager.builder(redisConnectionFactory) + .cacheDefaults(defaultConfig) + .build(); + } +} diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index f8f942f..708134e 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -46,6 +46,9 @@ public AuthenticationService( public String login(final LoginRequest loginRequest, final HttpServletResponse response) { + System.out.println("Login request: " + loginRequest.getEmail() + + " " + loginRequest.getPassword()); + Authentication authenticationRequest = UsernamePasswordAuthenticationToken. unauthenticated( @@ -65,6 +68,10 @@ public String login(final LoginRequest loginRequest, } public void registerAccount(final SignupRequest signupRequest) { + if (signupRequest.getPassword().isEmpty()) { + throw new ValidationException("Password cannot be empty."); + } + if (userRepository.existsByEmail(signupRequest.getEmail())) { throw new ValidationException("Email already in use."); } diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index 48b2c2c..5af441f 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -1,5 +1,6 @@ package com.podzilla.auth.service; +import com.podzilla.auth.dto.CustomUserDetails; import com.podzilla.auth.exception.NotFoundException; import com.podzilla.auth.model.User; import com.podzilla.auth.repository.UserRepository; @@ -39,7 +40,7 @@ public UserDetails loadUserByUsername(final String email) { role.getErole().name())) .collect(Collectors.toSet()); - return new org.springframework.security.core.userdetails.User( + return new CustomUserDetails( user.getEmail(), user.getPassword(), authorities From 8a08f1dca1e6c87c5deb804691ff666c245100e4 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 10:53:40 +0300 Subject: [PATCH 42/60] test --- src/main/java/com/podzilla/auth/service/JWTService.java | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 src/main/java/com/podzilla/auth/service/JWTService.java 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..96d043d --- /dev/null +++ b/src/main/java/com/podzilla/auth/service/JWTService.java @@ -0,0 +1,4 @@ +package com.podzilla.auth.service; + +public class JWTService { +} From 6a182ce4d083e83d39d4016a9cd5841acd87aaeb Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 10:55:04 +0300 Subject: [PATCH 43/60] tst2 --- src/main/java/com/podzilla/auth/service/JWTService.java | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 src/main/java/com/podzilla/auth/service/JWTService.java diff --git a/src/main/java/com/podzilla/auth/service/JWTService.java b/src/main/java/com/podzilla/auth/service/JWTService.java deleted file mode 100644 index 96d043d..0000000 --- a/src/main/java/com/podzilla/auth/service/JWTService.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.podzilla.auth.service; - -public class JWTService { -} From 5158aa4264507c56573fae36be4f5d71e08c725c Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 11:07:11 +0300 Subject: [PATCH 44/60] Remove debug logging from login method in AuthenticationService --- .../java/com/podzilla/auth/service/AuthenticationService.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 708134e..aa9f95d 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -46,9 +46,6 @@ public AuthenticationService( public String login(final LoginRequest loginRequest, final HttpServletResponse response) { - System.out.println("Login request: " + loginRequest.getEmail() - + " " + loginRequest.getPassword()); - Authentication authenticationRequest = UsernamePasswordAuthenticationToken. unauthenticated( From a3baaf14e9dd1e961e357e5b9005687ee67fdc14 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 12:58:13 +0300 Subject: [PATCH 45/60] Add unit tests for AdminService, AuthenticationService, CustomUserDetailsService, and TokenService --- .../auth/service/AuthenticationService.java | 15 +- .../service/CustomUserDetailsService.java | 5 + src/main/resources/application.properties | 2 +- .../auth/service/AdminServiceTest.java | 42 ++ .../service/AuthenticationServiceTest.java | 293 +++++++++++ .../service/CustomUserDetailsServiceTest.java | 149 ++++++ .../auth/service/TokenServiceTest.java | 487 ++++++++++++++++++ 7 files changed, 990 insertions(+), 3 deletions(-) create mode 100644 src/test/java/com/podzilla/auth/service/AdminServiceTest.java create mode 100644 src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java create mode 100644 src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java create mode 100644 src/test/java/com/podzilla/auth/service/TokenServiceTest.java diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index aa9f95d..504982f 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -65,10 +65,21 @@ public String login(final LoginRequest loginRequest, } public void registerAccount(final SignupRequest signupRequest) { - if (signupRequest.getPassword().isEmpty()) { + if (signupRequest.getPassword() == null + || signupRequest.getPassword().isEmpty()) { throw new ValidationException("Password cannot be empty."); } + if (signupRequest.getName() == null + || signupRequest.getName().isEmpty()) { + throw new ValidationException("Name cannot be empty."); + } + + if (signupRequest.getEmail() == null + || signupRequest.getEmail().isEmpty()) { + throw new ValidationException("Email cannot be empty."); + } + if (userRepository.existsByEmail(signupRequest.getEmail())) { throw new ValidationException("Email already in use."); } @@ -82,7 +93,7 @@ public void registerAccount(final SignupRequest signupRequest) { signupRequest.getPassword())) .build(); Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); - account.setRoles(Collections.singleton(role)); + account.setRoles(role != null ? Collections.singleton(role) : null); userRepository.save(account); } diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index 5af441f..1d2e2d4 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -2,6 +2,7 @@ import com.podzilla.auth.dto.CustomUserDetails; import com.podzilla.auth.exception.NotFoundException; +import com.podzilla.auth.exception.ValidationException; import com.podzilla.auth.model.User; import com.podzilla.auth.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; @@ -33,6 +34,10 @@ public UserDetails loadUserByUsername(final String email) { new NotFoundException( email + " not found.")); + if (user.getRoles() == null || user.getRoles().isEmpty()) { + throw new ValidationException("User has no roles assigned."); + } + Set authorities = user .getRoles() .stream() diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e7e6d89..6dcc38a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -19,7 +19,7 @@ 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.hibernate.ddl-auto=update spring.jpa.generate-ddl=true spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true diff --git a/src/test/java/com/podzilla/auth/service/AdminServiceTest.java b/src/test/java/com/podzilla/auth/service/AdminServiceTest.java new file mode 100644 index 0000000..f09023b --- /dev/null +++ b/src/test/java/com/podzilla/auth/service/AdminServiceTest.java @@ -0,0 +1,42 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.UserRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class AdminServiceTest { + + @Mock + private UserRepository userRepository; + + @InjectMocks + private AdminService adminService; + + @Test + void getUsers_shouldReturnListOfUsers() { + User user1 = User.builder().id(1L).email("user1@example.com").name("User One").build(); + User user2 = User.builder().id(2L).email("user2@example.com").name("User Two").build(); + List expectedUsers = Arrays.asList(user1, user2); + + when(userRepository.findAll()).thenReturn(expectedUsers); + + List actualUsers = adminService.getUsers(); + + assertEquals(expectedUsers.size(), actualUsers.size()); + assertEquals(expectedUsers, actualUsers); + + verify(userRepository).findAll(); + } +} \ No newline at end of file diff --git a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java new file mode 100644 index 0000000..d5b6da3 --- /dev/null +++ b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java @@ -0,0 +1,293 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.dto.LoginRequest; +import com.podzilla.auth.dto.SignupRequest; +import com.podzilla.auth.exception.ValidationException; +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.servlet.http.HttpServletRequest; // Added import +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.password.PasswordEncoder; + +import java.util.Collections; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class AuthenticationServiceTest { + + @Mock + private AuthenticationManager authenticationManager; + @Mock + private PasswordEncoder passwordEncoder; + @Mock + private UserRepository userRepository; + @Mock + private TokenService tokenService; + @Mock + private RoleRepository roleRepository; + @Mock + private HttpServletResponse httpServletResponse; + @Mock // Added mock for HttpServletRequest + private HttpServletRequest httpServletRequest; + + @InjectMocks + private AuthenticationService authenticationService; + + private SignupRequest signupRequest; + private LoginRequest loginRequest; + private User user; + private Role userRole; + + @BeforeEach + void setUp() { + signupRequest = new SignupRequest(); + signupRequest.setName("Test User"); + signupRequest.setEmail("test@example.com"); + signupRequest.setPassword("password123"); + + loginRequest = new LoginRequest(); + loginRequest.setEmail("test@example.com"); + loginRequest.setPassword("password123"); + + userRole = new Role(ERole.ROLE_USER); + user = User.builder() + .id(1L) + .name("Test User") + .email("test@example.com") + .password("encodedPassword") + .roles(Collections.singleton(userRole)) + .build(); + } + + // --- registerAccount Tests --- + + @Test + void registerAccount_shouldSaveUser_whenEmailNotExistsAndPasswordNotEmpty() { + // Arrange + when(userRepository.existsByEmail(signupRequest.getEmail())).thenReturn(false); + when(passwordEncoder.encode(signupRequest.getPassword())).thenReturn("encodedPassword"); + when(roleRepository.findByErole(ERole.ROLE_USER)).thenReturn(Optional.of(userRole)); + when(userRepository.save(any(User.class))).thenReturn(user); // Return the saved user + + // Act + authenticationService.registerAccount(signupRequest); + + // Assert + verify(userRepository).existsByEmail(signupRequest.getEmail()); + verify(passwordEncoder).encode(signupRequest.getPassword()); + verify(roleRepository).findByErole(ERole.ROLE_USER); + + // Capture the user argument passed to save + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(User.class); + verify(userRepository).save(userCaptor.capture()); + User savedUser = userCaptor.getValue(); + + assertEquals(signupRequest.getName(), savedUser.getName()); + assertEquals(signupRequest.getEmail(), savedUser.getEmail()); + assertEquals("encodedPassword", savedUser.getPassword()); + assertTrue(savedUser.getRoles().contains(userRole)); + } + + @Test + void registerAccount_shouldThrowValidationException_whenEmailExists() { + // Arrange + when(userRepository.existsByEmail(signupRequest.getEmail())).thenReturn(true); + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + authenticationService.registerAccount(signupRequest); + }); + + assertEquals("Validation error: Email already in use.", + exception.getMessage()); + verify(userRepository).existsByEmail(signupRequest.getEmail()); + verify(passwordEncoder, never()).encode(anyString()); + verify(roleRepository, never()).findByErole(any()); + verify(userRepository, never()).save(any(User.class)); + } + + @Test + void registerAccount_shouldThrowValidationException_whenPasswordIsEmpty() { + // Arrange + signupRequest.setPassword(""); // Empty password + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + authenticationService.registerAccount(signupRequest); + }); + + assertEquals("Validation error: Password cannot be empty.", + exception.getMessage()); + verify(userRepository, never()).existsByEmail(anyString()); + verify(passwordEncoder, never()).encode(anyString()); + verify(roleRepository, never()).findByErole(any()); + verify(userRepository, never()).save(any(User.class)); + } + + @Test + void registerAccount_shouldHandleRoleNotFoundGracefully() { + // Arrange - Simulate role not found in DB + when(userRepository.existsByEmail(signupRequest.getEmail())).thenReturn(false); + when(passwordEncoder.encode(signupRequest.getPassword())).thenReturn("encodedPassword"); + when(roleRepository.findByErole(ERole.ROLE_USER)).thenReturn(Optional.empty()); // Role not found + when(userRepository.save(any(User.class))).thenReturn(user); + + // Act + authenticationService.registerAccount(signupRequest); + + // Assert + verify(userRepository).existsByEmail(signupRequest.getEmail()); + verify(passwordEncoder).encode(signupRequest.getPassword()); + verify(roleRepository).findByErole(ERole.ROLE_USER); + + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(User.class); + verify(userRepository).save(userCaptor.capture()); + User savedUser = userCaptor.getValue(); + + // Check that roles are empty or null as expected when role isn't found + assertTrue(savedUser.getRoles() == null || savedUser.getRoles().isEmpty()); + assertEquals(signupRequest.getName(), savedUser.getName()); + assertEquals(signupRequest.getEmail(), savedUser.getEmail()); + assertEquals("encodedPassword", savedUser.getPassword()); + } + + + // --- login Tests --- + + @Test + void login_shouldReturnUsernameAndSetTokens_whenCredentialsAreValid() { + // Arrange + UserDetails userDetails = new org.springframework.security.core.userdetails.User( + loginRequest.getEmail(), + "encodedPassword", // Password doesn't matter much here as AuthenticationManager handles it + Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) + ); + Authentication successfulAuth = new UsernamePasswordAuthenticationToken( + userDetails, // Principal + loginRequest.getPassword(), // Credentials + userDetails.getAuthorities() // Authorities + ); + + // Mock AuthenticationManager behavior + when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) + .thenReturn(successfulAuth); + + // Mocks for token generation (void methods, no 'when' needed unless checking args) + // doNothing().when(tokenService).generateAccessToken(anyString(), any(HttpServletResponse.class)); + // doNothing().when(tokenService).generateRefreshToken(anyString(), any(HttpServletResponse.class)); + + // Act + String loggedInUsername = authenticationService.login(loginRequest, httpServletResponse); + + // Assert + assertEquals(loginRequest.getEmail(), loggedInUsername); + + // Verify AuthenticationManager was called with unauthenticated token + ArgumentCaptor authCaptor = + ArgumentCaptor.forClass(UsernamePasswordAuthenticationToken.class); + verify(authenticationManager).authenticate(authCaptor.capture()); + UsernamePasswordAuthenticationToken capturedAuthRequest = authCaptor.getValue(); + assertEquals(loginRequest.getEmail(), capturedAuthRequest.getName()); + assertEquals(loginRequest.getPassword(), capturedAuthRequest.getCredentials()); + assertFalse(capturedAuthRequest.isAuthenticated()); // Ensure it was unauthenticated initially + + // Verify token generation methods were called + verify(tokenService).generateAccessToken(loginRequest.getEmail(), httpServletResponse); + verify(tokenService).generateRefreshToken(loginRequest.getEmail(), httpServletResponse); + } + + @Test + void login_shouldThrowException_whenCredentialsAreInvalid() { + // Arrange + // Mock AuthenticationManager to throw an exception for bad credentials + when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) + .thenThrow(new BadCredentialsException("Invalid credentials")); + + // Act & Assert + assertThrows(BadCredentialsException.class, () -> { + authenticationService.login(loginRequest, httpServletResponse); + }); + + // Verify token generation methods were NOT called + verify(tokenService, never()).generateAccessToken(anyString(), any(HttpServletResponse.class)); + verify(tokenService, never()).generateRefreshToken(anyString(), any(HttpServletResponse.class)); + } + + // --- logoutUser Tests --- + @Test + void logoutUser_shouldCallTokenServiceToRemoveTokens() { + // Arrange (no specific arrangement needed as methods are void) + + // Act + authenticationService.logoutUser(httpServletResponse); + + // Assert + verify(tokenService).removeAccessTokenFromCookie(httpServletResponse); + verify(tokenService).removeRefreshTokenFromCookieAndExpire(httpServletResponse); + } + + // --- refreshToken Tests --- + @Test + void refreshToken_shouldReturnEmailAndGenerateAccessToken_whenTokenIsValid() { + // Arrange + String expectedEmail = "test@example.com"; + String validRefreshToken = "valid-refresh-token"; + + when(tokenService.getRefreshTokenFromCookie(httpServletRequest)).thenReturn(validRefreshToken); + when(tokenService.renewRefreshToken(validRefreshToken, httpServletResponse)).thenReturn(expectedEmail); + // No need to mock generateAccessToken as it's void, we just verify it + + // Act + String actualEmail = authenticationService.refreshToken(httpServletRequest, httpServletResponse); + + // Assert + assertEquals(expectedEmail, actualEmail); + verify(tokenService).getRefreshTokenFromCookie(httpServletRequest); + verify(tokenService).renewRefreshToken(validRefreshToken, httpServletResponse); + verify(tokenService).generateAccessToken(expectedEmail, httpServletResponse); + } + + @Test + void refreshToken_shouldThrowValidationException_whenTokenIsInvalid() { + // Arrange + String invalidRefreshToken = "invalid-refresh-token"; + + when(tokenService.getRefreshTokenFromCookie(httpServletRequest)).thenReturn(invalidRefreshToken); + // Mock renewRefreshToken to throw the exception caught in the service method + when(tokenService.renewRefreshToken(invalidRefreshToken, httpServletResponse)) + .thenThrow(new IllegalArgumentException("Token invalid")); + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + authenticationService.refreshToken(httpServletRequest, httpServletResponse); + }); + + assertEquals("Validation error: Invalid refresh token.", + exception.getMessage()); + verify(tokenService).getRefreshTokenFromCookie(httpServletRequest); + verify(tokenService).renewRefreshToken(invalidRefreshToken, httpServletResponse); + // Verify generateAccessToken was NOT called in the failure case + verify(tokenService, never()).generateAccessToken(anyString(), any(HttpServletResponse.class)); + } +} \ No newline at end of file diff --git a/src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java b/src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java new file mode 100644 index 0000000..c411ed8 --- /dev/null +++ b/src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java @@ -0,0 +1,149 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.dto.CustomUserDetails; +import com.podzilla.auth.exception.NotFoundException; +import com.podzilla.auth.exception.ValidationException; // Added import +import com.podzilla.auth.model.ERole; +import com.podzilla.auth.model.Role; +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class CustomUserDetailsServiceTest { + + @Mock + private UserRepository userRepository; + + @InjectMocks + private CustomUserDetailsService customUserDetailsService; + + private User user; + private String userEmail; + private String userPassword; + + @BeforeEach + void setUp() { + userEmail = "test@example.com"; + userPassword = "encodedPassword"; + Role userRole = new Role(ERole.ROLE_USER); + Role adminRole = new Role(ERole.ROLE_ADMIN); + + Set roles = new HashSet<>(); + roles.add(userRole); + roles.add(adminRole); + + user = User.builder() + .id(1L) + .name("Test User") + .email(userEmail) + .password(userPassword) + .roles(roles) + .build(); + } + + @Test + void loadUserByUsername_shouldReturnUserDetails_whenUserExistsAndHasRoles() { + // Arrange + when(userRepository.findByEmail(userEmail)).thenReturn(Optional.of(user)); + + // Act + UserDetails userDetails = customUserDetailsService.loadUserByUsername(userEmail); + + // Assert + assertNotNull(userDetails); + assertEquals(userEmail, userDetails.getUsername()); + assertEquals(userPassword, userDetails.getPassword()); + assertNotNull(userDetails.getAuthorities()); + assertEquals(2, userDetails.getAuthorities().size()); // ROLE_USER and ROLE_ADMIN + + // Check specific authorities + Set expectedAuthorities = Set.of(ERole.ROLE_USER.name(), ERole.ROLE_ADMIN.name()); + Set actualAuthorities = userDetails.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.toSet()); + assertEquals(expectedAuthorities, actualAuthorities); + + assertInstanceOf(CustomUserDetails.class, userDetails, "Should return an instance of CustomUserDetails"); + + verify(userRepository).findByEmail(userEmail); + } + + @Test + void loadUserByUsername_shouldThrowNotFoundException_whenUserDoesNotExist() { + // Arrange + String nonExistentEmail = "notfound@example.com"; + when(userRepository.findByEmail(nonExistentEmail)).thenReturn(Optional.empty()); + + // Act & Assert + NotFoundException exception = assertThrows(NotFoundException.class, () -> { + customUserDetailsService.loadUserByUsername(nonExistentEmail); + }); + + assertEquals("Not Found: " + nonExistentEmail + " not found.", + exception.getMessage()); + verify(userRepository).findByEmail(nonExistentEmail); + } + + @Test + void loadUserByUsername_shouldThrowValidationException_whenUserHasEmptyRoles() { + // Arrange + String emailWithNoRoles = "norole@example.com"; + User userWithNoRoles = User.builder() + .id(2L) + .name("No Role User") + .email(emailWithNoRoles) + .password("password123") + .roles(Collections.emptySet()) // Empty roles set + .build(); + when(userRepository.findByEmail(emailWithNoRoles)).thenReturn(Optional.of(userWithNoRoles)); + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + customUserDetailsService.loadUserByUsername(emailWithNoRoles); + }); + + assertEquals("Validation error: User has no roles assigned.", + exception.getMessage()); + verify(userRepository).findByEmail(emailWithNoRoles); + } + + @Test + void loadUserByUsername_shouldThrowValidationException_whenUserHasNullRoles() { + // Arrange + String emailWithNullRoles = "nullrole@example.com"; + User userWithNullRoles = User.builder() + .id(3L) + .name("Null Role User") + .email(emailWithNullRoles) + .password("password456") + .roles(null) // Null roles set + .build(); + when(userRepository.findByEmail(emailWithNullRoles)).thenReturn(Optional.of(userWithNullRoles)); + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + customUserDetailsService.loadUserByUsername(emailWithNullRoles); + }); + + assertEquals("Validation error: User has no roles assigned.", + exception.getMessage()); + verify(userRepository).findByEmail(emailWithNullRoles); + } +} \ No newline at end of file diff --git a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java new file mode 100644 index 0000000..c67c256 --- /dev/null +++ b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java @@ -0,0 +1,487 @@ +package com.podzilla.auth.service; + +import com.podzilla.auth.exception.ValidationException; +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.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.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.util.WebUtils; + + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class TokenServiceTest { + + @Mock + private UserRepository userRepository; + + @Mock + private RefreshTokenRepository refreshTokenRepository; + + @Mock + private HttpServletResponse response; + + @Mock + private HttpServletRequest request; + + // Use InjectMocks to automatically inject the mocked dependencies + @InjectMocks + private TokenService tokenService; + + // Test data + private final String testEmail = "test@example.com"; + private final String testSecret = "testSecretKeyForJwtTokenGenerationWhichIsVeryLongAndSecure"; // Use a valid Base64 encoded key if possible + private final Long testUserId = 115642L; + private final UUID testRefreshTokenId = UUID.randomUUID(); + + @BeforeEach + void setUp() { + // Use ReflectionTestUtils to set the private @Value fields + ReflectionTestUtils.setField(tokenService, "secret", testSecret); + Long testJwtExpiresMinutes = 30L; + ReflectionTestUtils.setField(tokenService, "jwtExpiresMinutes", testJwtExpiresMinutes); + // Reset claims if needed between tests (though it's mostly set during validation) + ReflectionTestUtils.setField(tokenService, "claims", null); + } + + @Test + @DisplayName("Should generate access token and add cookie") + void generateAccessToken_ShouldAddCookie() { + // Arrange + ArgumentCaptor cookieCaptor = ArgumentCaptor.forClass(Cookie.class); + + // Act + tokenService.generateAccessToken(testEmail, response); + + // Assert + verify(response).addCookie(cookieCaptor.capture()); + Cookie addedCookie = cookieCaptor.getValue(); + + assertNotNull(addedCookie); + assertEquals("accessToken", addedCookie.getName()); + assertTrue(addedCookie.isHttpOnly()); + assertTrue(addedCookie.getSecure()); + assertEquals("/", addedCookie.getPath()); // Check path + assertEquals(60 * 30, addedCookie.getMaxAge()); // Check expiration + + // Optionally, validate the JWT content (requires parsing logic similar to validateAccessToken) + assertNotNull(addedCookie.getValue()); + // You could add more detailed JWT validation if needed + } + + @Test + @DisplayName("Should generate new refresh token if none exists") + void generateRefreshToken_WhenNoneExists_ShouldCreateNewAndAddCookie() { + // Arrange + User user = User.builder().id(testUserId).email(testEmail).build(); + when(userRepository.findByEmail(testEmail)).thenReturn(Optional.of(user)); + when(refreshTokenRepository.findByUserIdAndExpiresAtAfter(eq(testUserId), any(Instant.class))) + .thenReturn(Optional.empty()); // No existing valid token + when(refreshTokenRepository.save(any(RefreshToken.class))) + .thenAnswer(invocation -> { + RefreshToken token = invocation.getArgument(0); + token.setId(testRefreshTokenId); + return token; + }); // Mock save to return the + // token itself + + ArgumentCaptor refreshTokenCaptor = ArgumentCaptor.forClass(RefreshToken.class); + ArgumentCaptor cookieCaptor = ArgumentCaptor.forClass(Cookie.class); + + // Act + tokenService.generateRefreshToken(testEmail, response); + + // Assert + verify(refreshTokenRepository).save(refreshTokenCaptor.capture()); + RefreshToken savedToken = refreshTokenCaptor.getValue(); + assertNotNull(savedToken); + assertEquals(user, savedToken.getUser()); + assertNotNull(savedToken.getCreatedAt()); + assertNotNull(savedToken.getExpiresAt()); + assertTrue(savedToken.getExpiresAt().isAfter(Instant.now())); + + verify(response).addCookie(cookieCaptor.capture()); + Cookie addedCookie = cookieCaptor.getValue(); + assertNotNull(addedCookie); + assertEquals("refreshToken", addedCookie.getName()); + assertEquals(savedToken.getId().toString(), addedCookie.getValue()); // Verify token value in cookie + assertTrue(addedCookie.isHttpOnly()); + assertTrue(addedCookie.getSecure()); + assertEquals("/api/auth/refresh-token", addedCookie.getPath()); // Check specific path + assertTrue(addedCookie.getMaxAge() > 0); // Check expiration + } + + @Test + @DisplayName("Should use existing refresh token if valid one exists") + void generateRefreshToken_WhenValidExists_ShouldUseExistingAndAddCookie() { + // Arrange + User user = User.builder().id(testUserId).email(testEmail).build(); + RefreshToken existingToken = RefreshToken.builder() + .id(testRefreshTokenId) + .user(user) + .createdAt(Instant.now().minus(1, ChronoUnit.DAYS)) + .expiresAt(Instant.now().plus(5, ChronoUnit.DAYS)) // Still valid + .build(); + + when(userRepository.findByEmail(testEmail)).thenReturn(Optional.of(user)); + when(refreshTokenRepository.findByUserIdAndExpiresAtAfter(eq(testUserId), any(Instant.class))) + .thenReturn(Optional.of(existingToken)); + + ArgumentCaptor cookieCaptor = ArgumentCaptor.forClass(Cookie.class); + + // Act + tokenService.generateRefreshToken(testEmail, response); + + // Assert + verify(refreshTokenRepository, never()).save(any(RefreshToken.class)); // Should not save a new one + + verify(response).addCookie(cookieCaptor.capture()); + Cookie addedCookie = cookieCaptor.getValue(); + assertNotNull(addedCookie); + assertEquals("refreshToken", addedCookie.getName()); + assertEquals(existingToken.getId().toString(), addedCookie.getValue()); // Uses existing token ID + assertTrue(addedCookie.isHttpOnly()); + assertTrue(addedCookie.getSecure()); + assertEquals("/api/auth/refresh-token", addedCookie.getPath()); + } + + + @Test + @DisplayName("Should throw ValidationException if user not found during refresh token generation") + void generateRefreshToken_WhenUserNotFound_ShouldThrowValidationException() { + // Arrange + when(userRepository.findByEmail(testEmail)).thenReturn(Optional.empty()); + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + tokenService.generateRefreshToken(testEmail, response); + }); + assertEquals("Validation error: User not found", + exception.getMessage()); + verify(refreshTokenRepository, never()).save(any()); + verify(response, never()).addCookie(any()); + } + + + @Test + @DisplayName("Should renew refresh token successfully") + void renewRefreshToken_ValidToken_ShouldExpireOldCreateNewAddCookieAndReturnEmail() { + // Arrange + User user = User.builder().id(testUserId).email(testEmail).build(); + RefreshToken oldToken = RefreshToken.builder() + .id(testRefreshTokenId) + .user(user) + .createdAt(Instant.now().minus(1, ChronoUnit.DAYS)) + .expiresAt(Instant.now().plus(5, ChronoUnit.DAYS)) + .build(); + String oldTokenString = oldToken.getId().toString(); + + when(refreshTokenRepository.findByIdAndExpiresAtAfter(eq(testRefreshTokenId), any(Instant.class))) + .thenReturn(Optional.of(oldToken)); + when(refreshTokenRepository.save(any(RefreshToken.class))) + .thenAnswer(invocation -> { + RefreshToken token = invocation.getArgument(0); + token.setId(UUID.randomUUID()); + return token; + }); // Mock save to return the token itself + + ArgumentCaptor refreshTokenCaptor = ArgumentCaptor.forClass(RefreshToken.class); + ArgumentCaptor cookieCaptor = ArgumentCaptor.forClass(Cookie.class); + + // Act + String resultEmail = tokenService.renewRefreshToken(oldTokenString, response); + + // Assert + assertEquals(testEmail, resultEmail); + + verify(refreshTokenRepository, times(2)).save(refreshTokenCaptor.capture()); + RefreshToken expiredToken = refreshTokenCaptor.getAllValues().get(0); + RefreshToken newToken = refreshTokenCaptor.getAllValues().get(1); + + // Verify old token was expired (or set to expire immediately) + assertTrue(expiredToken.getExpiresAt().isBefore(Instant.now().plusSeconds(1))); // Check if expiration is set to now or very close + + // Verify new token details + assertNotEquals(oldToken.getId(), newToken.getId()); + assertEquals(user, newToken.getUser()); + assertTrue(newToken.getExpiresAt().isAfter(Instant.now())); + + // Verify cookie for the new token + verify(response).addCookie(cookieCaptor.capture()); + Cookie addedCookie = cookieCaptor.getValue(); + assertEquals("refreshToken", addedCookie.getName()); + assertEquals(newToken.getId().toString(), addedCookie.getValue()); + assertTrue(addedCookie.isHttpOnly()); + assertTrue(addedCookie.getSecure()); + assertEquals("/api/auth/refresh-token", addedCookie.getPath()); + } + + @Test + @DisplayName("Should throw ValidationException when renewing invalid refresh token") + void renewRefreshToken_InvalidToken_ShouldThrowValidationException() { + // Arrange + String invalidTokenString = UUID.randomUUID().toString(); + when(refreshTokenRepository.findByIdAndExpiresAtAfter(eq(UUID.fromString(invalidTokenString)), any(Instant.class))) + .thenReturn(Optional.empty()); + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + tokenService.renewRefreshToken(invalidTokenString, response); + }); + assertEquals("Validation error: Invalid refresh token", + exception.getMessage()); + verify(refreshTokenRepository, never()).save(any()); + verify(response, never()).addCookie(any()); + } + + @Test + @DisplayName("Should return access token from cookie") + void getAccessTokenFromCookie_WhenCookieExists_ShouldReturnTokenValue() { + // Arrange + String tokenValue = "dummyAccessToken"; + Cookie accessTokenCookie = new Cookie("accessToken", tokenValue); + // Static mocking for WebUtils (alternative: inject a mock WebUtils if preferred) + // Use a try-with-resources block for mocking static methods if using mockito-inline + try (var mockedStatic = mockStatic(WebUtils.class)) { + mockedStatic.when(() -> WebUtils.getCookie(request, "accessToken")).thenReturn(accessTokenCookie); + + // Act + String retrievedToken = tokenService.getAccessTokenFromCookie(request); + + // Assert + assertEquals(tokenValue, retrievedToken); + } + } + + @Test + @DisplayName("Should return null if access token cookie does not exist") + void getAccessTokenFromCookie_WhenCookieMissing_ShouldReturnNull() { + // Arrange + try (var mockedStatic = mockStatic(WebUtils.class)) { + mockedStatic.when(() -> WebUtils.getCookie(request, "accessToken")).thenReturn(null); + // Act + String retrievedToken = tokenService.getAccessTokenFromCookie(request); + + // Assert + assertNull(retrievedToken); + } + } + + // Similar tests for getRefreshTokenFromCookie... + + @Test + @DisplayName("Should validate a valid access token") + void validateAccessToken_ValidToken_ShouldNotThrow() { + // Arrange: Generate a valid token first + // Note: This relies on the internal generation logic using the test secret. + byte[] keyBytes = Decoders.BASE64.decode(testSecret); + SecretKey key = Keys.hmacShaKeyFor(keyBytes); + String validToken = Jwts.builder() + .subject(testEmail) + .issuedAt(new Date()) + .expiration(new Date(System.currentTimeMillis() + 1000 * 60 * 5)) // Expires in 5 mins + .signWith(key) + .compact(); + + // Act & Assert: Should not throw any exception + assertDoesNotThrow(() -> tokenService.validateAccessToken(validToken)); + + // Also assert that claims are set + Claims claims = (Claims) ReflectionTestUtils.getField(tokenService, "claims"); + assertNotNull(claims); + assertEquals(testEmail, claims.getSubject()); + } + + @Test + @DisplayName("Should throw ValidationException for invalid access token (expired)") + void validateAccessToken_ExpiredToken_ShouldThrowValidationException() { + // Arrange: Generate an expired token + SecretKey key = Keys.hmacShaKeyFor(testSecret.getBytes()); + String expiredToken = Jwts.builder() + .subject(testEmail) + .issuedAt(new Date(System.currentTimeMillis() - 1000 * 60 * 10)) // Issued 10 mins ago + .expiration(new Date(System.currentTimeMillis() - 1000 * 60 * 5)) // Expired 5 mins ago + .signWith(key) + .compact(); + + // Act & Assert + assertThrows(ValidationException.class, () -> { + tokenService.validateAccessToken(expiredToken); + }); + } + + @Test + @DisplayName("Should throw ValidationException for malformed access token") + void validateAccessToken_MalformedToken_ShouldThrowValidationException() { + // Arrange + String malformedToken = "this.is.not.a.valid.jwt"; + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + tokenService.validateAccessToken(malformedToken); + }); + // Check if the message indicates a JWT format issue + assertTrue(exception.getMessage().toLowerCase().contains("jwt")); + } + + @Test + @DisplayName("Should remove access token cookie") + void removeAccessTokenFromCookie_ShouldAddNullCookie() { + // Arrange + ArgumentCaptor cookieCaptor = ArgumentCaptor.forClass(Cookie.class); + + // Act + tokenService.removeAccessTokenFromCookie(response); + + // Assert + verify(response).addCookie(cookieCaptor.capture()); + Cookie addedCookie = cookieCaptor.getValue(); + + assertEquals("accessToken", addedCookie.getName()); + assertNull(addedCookie.getValue()); // Value should be null to remove + assertEquals("/", addedCookie.getPath()); + // MaxAge might be 0 or not set depending on exact removal strategy, check path mainly + } + + + // --- Tests for removeRefreshTokenFromCookieAndExpire --- + // This requires setting the 'claims' field first, as extractEmail depends on it. + + private void setupClaimsForEmailExtraction() { + // Helper to simulate that validateAccessToken was called successfully before + SecretKey key = Keys.hmacShaKeyFor(testSecret.getBytes()); + Claims claims = Jwts.claims().subject(testEmail).build(); + ReflectionTestUtils.setField(tokenService, "claims", claims); + } + + @Test + @DisplayName("Should remove refresh token cookie and expire token in DB") + void removeRefreshTokenFromCookieAndExpire_ValidState_ShouldPerformActions() { + // Arrange + setupClaimsForEmailExtraction(); // Simulate prior successful access token validation + + User user = User.builder().id(testUserId).email(testEmail).build(); + RefreshToken refreshToken = RefreshToken.builder() + .id(testRefreshTokenId) + .user(user) + .createdAt(Instant.now().minus(1, ChronoUnit.DAYS)) + .expiresAt(Instant.now().plus(5, ChronoUnit.DAYS)) + .build(); + + when(userRepository.findByEmail(testEmail)).thenReturn(Optional.of(user)); + when(refreshTokenRepository.findByUserIdAndExpiresAtAfter(eq(testUserId), any(Instant.class))) + .thenReturn(Optional.of(refreshToken)); + + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(RefreshToken.class); + ArgumentCaptor cookieCaptor = ArgumentCaptor.forClass(Cookie.class); + + // Act + tokenService.removeRefreshTokenFromCookieAndExpire(response); + + // Assert + // 1. Verify token was expired + verify(refreshTokenRepository).save(tokenCaptor.capture()); + RefreshToken expiredToken = tokenCaptor.getValue(); + assertEquals(refreshToken.getId(), expiredToken.getId()); + assertTrue(expiredToken.getExpiresAt().isBefore(Instant.now().plusSeconds(1))); // Expired now + + // 2. Verify cookie was removed + verify(response).addCookie(cookieCaptor.capture()); + Cookie removedCookie = cookieCaptor.getValue(); + assertEquals("refreshToken", removedCookie.getName()); + assertNull(removedCookie.getValue()); + assertEquals("/api/auth/refresh-token", removedCookie.getPath()); + } + + @Test + @DisplayName("removeRefreshTokenFromCookieAndExpire should throw if user not found") + void removeRefreshTokenFromCookieAndExpire_UserNotFound_ShouldThrowValidationException() { + // Arrange + setupClaimsForEmailExtraction(); + when(userRepository.findByEmail(testEmail)).thenReturn(Optional.empty()); + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + tokenService.removeRefreshTokenFromCookieAndExpire(response); + }); + assertEquals("Validation error: User not found", + exception.getMessage()); + verify(refreshTokenRepository, never()).findByUserIdAndExpiresAtAfter(any(), any()); + verify(refreshTokenRepository, never()).save(any()); + verify(response, never()).addCookie(any()); + } + + @Test + @DisplayName("removeRefreshTokenFromCookieAndExpire should throw if refresh token not found") + void removeRefreshTokenFromCookieAndExpire_TokenNotFound_ShouldThrowValidationException() { + // Arrange + setupClaimsForEmailExtraction(); + User user = User.builder().id(testUserId).email(testEmail).build(); + + when(userRepository.findByEmail(testEmail)).thenReturn(Optional.of(user)); + when(refreshTokenRepository.findByUserIdAndExpiresAtAfter(eq(testUserId), any(Instant.class))) + .thenReturn(Optional.empty()); // Token not found + + // Act & Assert + ValidationException exception = assertThrows(ValidationException.class, () -> { + tokenService.removeRefreshTokenFromCookieAndExpire(response); + }); + assertEquals("Validation error: Refresh token not found", + exception.getMessage()); + verify(refreshTokenRepository, never()).save(any()); + verify(response, never()).addCookie(any()); + } + + + @Test + @DisplayName("Should extract email from claims") + void extractEmail_WhenClaimsSet_ShouldReturnSubject() { + // Arrange + setupClaimsForEmailExtraction(); // Sets claims with testEmail as subject + + // Act + String extractedEmail = tokenService.extractEmail(); + + // Assert + assertEquals(testEmail, extractedEmail); + } + + @Test + @DisplayName("extractEmail should throw NullPointerException if claims not set") + void extractEmail_WhenClaimsNull_ShouldThrowNullPointerException() { + // Arrange: claims field is null by default or after reset + + // Act & Assert + assertThrows(NullPointerException.class, () -> { + tokenService.extractEmail(); + }, "Expected NullPointerException because claims object is null"); + } +} \ No newline at end of file From 7d9ab5dedb1c4d5fe9e18868ed9cd834961a84d5 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 13:09:52 +0300 Subject: [PATCH 46/60] Validate role existence before assigning to account in AuthenticationService --- .../auth/service/AuthenticationService.java | 7 ++++++- .../service/AuthenticationServiceTest.java | 18 ++++++------------ 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 504982f..9f3a93a 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -93,7 +93,12 @@ public void registerAccount(final SignupRequest signupRequest) { signupRequest.getPassword())) .build(); Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); - account.setRoles(role != null ? Collections.singleton(role) : null); + + if (role == null) { + throw new ValidationException("Role_USER not found."); + } + + account.setRoles(Collections.singleton(role)); userRepository.save(account); } diff --git a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java index d5b6da3..dd04c4e 100644 --- a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java @@ -151,25 +151,19 @@ void registerAccount_shouldHandleRoleNotFoundGracefully() { when(userRepository.existsByEmail(signupRequest.getEmail())).thenReturn(false); when(passwordEncoder.encode(signupRequest.getPassword())).thenReturn("encodedPassword"); when(roleRepository.findByErole(ERole.ROLE_USER)).thenReturn(Optional.empty()); // Role not found - when(userRepository.save(any(User.class))).thenReturn(user); // Act - authenticationService.registerAccount(signupRequest); + ValidationException exception = assertThrows(ValidationException.class, () -> { + authenticationService.registerAccount(signupRequest); + }); + + assertEquals("Validation error: Role_USER not found.", + exception.getMessage()); // Assert verify(userRepository).existsByEmail(signupRequest.getEmail()); verify(passwordEncoder).encode(signupRequest.getPassword()); verify(roleRepository).findByErole(ERole.ROLE_USER); - - ArgumentCaptor userCaptor = ArgumentCaptor.forClass(User.class); - verify(userRepository).save(userCaptor.capture()); - User savedUser = userCaptor.getValue(); - - // Check that roles are empty or null as expected when role isn't found - assertTrue(savedUser.getRoles() == null || savedUser.getRoles().isEmpty()); - assertEquals(signupRequest.getName(), savedUser.getName()); - assertEquals(signupRequest.getEmail(), savedUser.getEmail()); - assertEquals("encodedPassword", savedUser.getPassword()); } From 794a650a58dcdce97209f31056ff180400b58a57 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 13:19:26 +0300 Subject: [PATCH 47/60] test --- .../java/com/podzilla/auth/service/TokenServiceTest.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java index c67c256..7dd049b 100644 --- a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java @@ -148,7 +148,8 @@ void generateRefreshToken_WhenValidExists_ShouldUseExistingAndAddCookie() { .id(testRefreshTokenId) .user(user) .createdAt(Instant.now().minus(1, ChronoUnit.DAYS)) - .expiresAt(Instant.now().plus(5, ChronoUnit.DAYS)) // Still valid + .expiresAt(Instant.now().plus(50, ChronoUnit.DAYS)) // Still + // valid .build(); when(userRepository.findByEmail(testEmail)).thenReturn(Optional.of(user)); @@ -199,7 +200,7 @@ void renewRefreshToken_ValidToken_ShouldExpireOldCreateNewAddCookieAndReturnEmai RefreshToken oldToken = RefreshToken.builder() .id(testRefreshTokenId) .user(user) - .createdAt(Instant.now().minus(1, ChronoUnit.DAYS)) + .createdAt(Instant.now().minus(10, ChronoUnit.DAYS)) .expiresAt(Instant.now().plus(5, ChronoUnit.DAYS)) .build(); String oldTokenString = oldToken.getId().toString(); @@ -392,8 +393,8 @@ void removeRefreshTokenFromCookieAndExpire_ValidState_ShouldPerformActions() { RefreshToken refreshToken = RefreshToken.builder() .id(testRefreshTokenId) .user(user) - .createdAt(Instant.now().minus(1, ChronoUnit.DAYS)) - .expiresAt(Instant.now().plus(5, ChronoUnit.DAYS)) + .createdAt(Instant.now().minus(7, ChronoUnit.DAYS)) + .expiresAt(Instant.now().plus(60, ChronoUnit.DAYS)) .build(); when(userRepository.findByEmail(testEmail)).thenReturn(Optional.of(user)); From 138152047b57cbf8055c22dcacf08187b31f208f Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 13:26:27 +0300 Subject: [PATCH 48/60] check linter --- src/test/java/com/podzilla/auth/service/TokenServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java index 7dd049b..46c80f3 100644 --- a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java @@ -394,7 +394,7 @@ void removeRefreshTokenFromCookieAndExpire_ValidState_ShouldPerformActions() { .id(testRefreshTokenId) .user(user) .createdAt(Instant.now().minus(7, ChronoUnit.DAYS)) - .expiresAt(Instant.now().plus(60, ChronoUnit.DAYS)) + .expiresAt(Instant.now().plus(21, ChronoUnit.DAYS)) .build(); when(userRepository.findByEmail(testEmail)).thenReturn(Optional.of(user)); From 97b533540ca9ac15022a122dda59ecde38f4da56 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 13:38:38 +0300 Subject: [PATCH 49/60] try linter --- src/test/java/com/podzilla/auth/service/TokenServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java index 46c80f3..980d619 100644 --- a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java @@ -148,7 +148,7 @@ void generateRefreshToken_WhenValidExists_ShouldUseExistingAndAddCookie() { .id(testRefreshTokenId) .user(user) .createdAt(Instant.now().minus(1, ChronoUnit.DAYS)) - .expiresAt(Instant.now().plus(50, ChronoUnit.DAYS)) // Still + .expiresAt(Instant.now().plus(51, ChronoUnit.DAYS)) // Still // valid .build(); From 5dd728a1e7ba592159e74e9abac399f8064b04c0 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 19:09:01 +0300 Subject: [PATCH 50/60] Add unit tests for AdminController and update role authority handling --- .../auth/dto/CustomGrantedAuthority.java | 27 ++++ .../podzilla/auth/dto/CustomUserDetails.java | 3 + .../auth/security/SecurityConfig.java | 2 +- .../service/CustomUserDetailsService.java | 4 +- .../auth/controller/AdminControllerTest.java | 115 ++++++++++++++++++ .../service/AuthenticationServiceTest.java | 4 +- 6 files changed, 150 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/podzilla/auth/dto/CustomGrantedAuthority.java create mode 100644 src/test/java/com/podzilla/auth/controller/AdminControllerTest.java diff --git a/src/main/java/com/podzilla/auth/dto/CustomGrantedAuthority.java b/src/main/java/com/podzilla/auth/dto/CustomGrantedAuthority.java new file mode 100644 index 0000000..541c48d --- /dev/null +++ b/src/main/java/com/podzilla/auth/dto/CustomGrantedAuthority.java @@ -0,0 +1,27 @@ +package com.podzilla.auth.dto; + +import org.springframework.security.core.GrantedAuthority; + +public class CustomGrantedAuthority implements GrantedAuthority { + private String authority; + + public CustomGrantedAuthority() { + // No-arg constructor required by Jackson + } + + public CustomGrantedAuthority(final String authority) { + this.authority = authority; + } + + @Override + public String getAuthority() { + return authority; + } + + @Override + public String toString() { + return "CustomGrantedAuthority{" + + "authority='" + authority + '\'' + + '}'; + } +} diff --git a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java index e1db335..edcf3e6 100644 --- a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java +++ b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java @@ -1,6 +1,7 @@ package com.podzilla.auth.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -12,6 +13,8 @@ public class CustomUserDetails implements UserDetails { private String username; private String password; + + @JsonDeserialize(contentAs = CustomGrantedAuthority.class) private Set authorities; public CustomUserDetails() { diff --git a/src/main/java/com/podzilla/auth/security/SecurityConfig.java b/src/main/java/com/podzilla/auth/security/SecurityConfig.java index fef3d0c..1ae9147 100644 --- a/src/main/java/com/podzilla/auth/security/SecurityConfig.java +++ b/src/main/java/com/podzilla/auth/security/SecurityConfig.java @@ -43,7 +43,7 @@ SecurityFilterChain securityFilterChain(final HttpSecurity http) .requestMatchers("/auth/refresh-token") .permitAll() .requestMatchers("/admin/**") - .hasRole("ADMIN") + .hasAuthority("ROLE_ADMIN") .requestMatchers("/swagger-ui/**", "/v3/api-docs/**") .permitAll() diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index 1d2e2d4..eee38ac 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -1,5 +1,6 @@ package com.podzilla.auth.service; +import com.podzilla.auth.dto.CustomGrantedAuthority; import com.podzilla.auth.dto.CustomUserDetails; import com.podzilla.auth.exception.NotFoundException; import com.podzilla.auth.exception.ValidationException; @@ -8,7 +9,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; 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.stereotype.Service; @@ -41,7 +41,7 @@ public UserDetails loadUserByUsername(final String email) { Set authorities = user .getRoles() .stream() - .map((role) -> new SimpleGrantedAuthority( + .map((role) -> new CustomGrantedAuthority( role.getErole().name())) .collect(Collectors.toSet()); diff --git a/src/test/java/com/podzilla/auth/controller/AdminControllerTest.java b/src/test/java/com/podzilla/auth/controller/AdminControllerTest.java new file mode 100644 index 0000000..400ee63 --- /dev/null +++ b/src/test/java/com/podzilla/auth/controller/AdminControllerTest.java @@ -0,0 +1,115 @@ +package com.podzilla.auth.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.podzilla.auth.model.ERole; +import com.podzilla.auth.model.Role; +import com.podzilla.auth.model.User; +import com.podzilla.auth.repository.UserRepository; +import io.jsonwebtoken.lang.Collections; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +@Sql(statements = { + "INSERT INTO roles (id, erole) VALUES (1, 'ROLE_USER'), (2, 'ROLE_ADMIN')", +}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS) +class AdminControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private ObjectMapper objectMapper; + + private User user1; + private User user2; + + @BeforeEach + void setUp() { + userRepository.deleteAll(); // Clean slate before each test + + Role adminRole = new Role(); + adminRole.setId(2L); + adminRole.setErole(ERole.ROLE_ADMIN); + + Role userRole = new Role(); + userRole.setId(1L); + userRole.setErole(ERole.ROLE_USER); + + user1 = new User(); + user1.setEmail("adminUser"); + user1.setPassword(passwordEncoder.encode("password")); + user1.setRoles(Collections.setOf(adminRole)); + user1.setEmail("admin@example.com"); + + user2 = new User(); + user2.setEmail("normalUser"); + user2.setPassword(passwordEncoder.encode("password")); + user2.setRoles(Collections.setOf(userRole)); + user2.setEmail("user@example.com"); + + userRepository.saveAll(Arrays.asList(user1, user2)); + } + + @AfterEach + void tearDown() { + userRepository.deleteAll(); // Clean up after each test + } + + @Test + @WithMockUser(authorities = "ROLE_ADMIN") + void getUsers_shouldReturnListOfUsers_whenUserIsAdmin() throws Exception { + List expectedUsers = Arrays.asList(user1, user2); + + mockMvc.perform(get("/admin/users") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].name", is(user1.getName()))) + .andExpect(jsonPath("$[0].email", is(user1.getEmail()))) + .andExpect(jsonPath("$[0].password", is(user1.getPassword()))) + .andExpect(jsonPath("$[1].name", is(user2.getName()))) + .andExpect(jsonPath("$[1].email", is(user2.getEmail()))) + .andExpect(jsonPath("$[1].password", is(user2.getPassword()))); + } + + @Test + @WithMockUser(roles = "USER") // Simulate an authenticated user with USER role + void getUsers_shouldReturnForbidden_whenUserIsNotAdmin() throws Exception { + mockMvc.perform(get("/admin/users") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()); + } + + @Test + void getUsers_shouldReturnUnauthorized_whenUserIsNotAuthenticated() throws Exception { + mockMvc.perform(get("/admin/users") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()); + } +} diff --git a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java index dd04c4e..2f5fde0 100644 --- a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java @@ -1,5 +1,6 @@ package com.podzilla.auth.service; +import com.podzilla.auth.dto.CustomGrantedAuthority; import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; import com.podzilla.auth.exception.ValidationException; @@ -21,7 +22,6 @@ import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; @@ -175,7 +175,7 @@ void login_shouldReturnUsernameAndSetTokens_whenCredentialsAreValid() { UserDetails userDetails = new org.springframework.security.core.userdetails.User( loginRequest.getEmail(), "encodedPassword", // Password doesn't matter much here as AuthenticationManager handles it - Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) + Collections.singletonList(new CustomGrantedAuthority("ROLE_USER")) ); Authentication successfulAuth = new UsernamePasswordAuthenticationToken( userDetails, // Principal From 60458eb025910e3cce26c6c3d0cb1dfd75c049a6 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 20:54:15 +0300 Subject: [PATCH 51/60] Refactor authentication tests and improve role handling in AdminControllerTest --- .../auth/service/AuthenticationService.java | 9 +- .../auth/controller/AdminControllerTest.java | 14 +- .../AuthenticationControllerTest.java | 241 ++++++++++++++++++ .../service/AuthenticationServiceTest.java | 7 +- .../auth/service/TokenServiceTest.java | 1 + src/test/resources/application.properties | 2 +- 6 files changed, 262 insertions(+), 12 deletions(-) create mode 100644 src/test/java/com/podzilla/auth/controller/AuthenticationControllerTest.java diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 9f3a93a..37ca647 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -10,6 +10,7 @@ import com.podzilla.auth.repository.UserRepository; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -110,14 +111,18 @@ public void logoutUser( public String refreshToken(final HttpServletRequest request, final HttpServletResponse response) { - String refreshToken = tokenService.getRefreshTokenFromCookie(request); try { + String refreshToken = + tokenService.getRefreshTokenFromCookie(request); + if (refreshToken == null) { + throw new AccessDeniedException("Refresh token not found."); + } String email = tokenService.renewRefreshToken(refreshToken, response); tokenService.generateAccessToken(email, response); return email; } catch (IllegalArgumentException e) { - throw new ValidationException("Invalid refresh token."); + throw new AccessDeniedException("Invalid refresh token."); } } } diff --git a/src/test/java/com/podzilla/auth/controller/AdminControllerTest.java b/src/test/java/com/podzilla/auth/controller/AdminControllerTest.java index 400ee63..a89afb5 100644 --- a/src/test/java/com/podzilla/auth/controller/AdminControllerTest.java +++ b/src/test/java/com/podzilla/auth/controller/AdminControllerTest.java @@ -4,6 +4,7 @@ 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 io.jsonwebtoken.lang.Collections; import org.junit.jupiter.api.AfterEach; @@ -15,7 +16,6 @@ import org.springframework.http.MediaType; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; import java.util.Arrays; @@ -28,9 +28,6 @@ @SpringBootTest @AutoConfigureMockMvc -@Sql(statements = { - "INSERT INTO roles (id, erole) VALUES (1, 'ROLE_USER'), (2, 'ROLE_ADMIN')", -}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS) class AdminControllerTest { @Autowired @@ -39,6 +36,9 @@ class AdminControllerTest { @Autowired private UserRepository userRepository; + @Autowired + private RoleRepository roleRepository; + @Autowired private PasswordEncoder passwordEncoder; @@ -51,14 +51,15 @@ class AdminControllerTest { @BeforeEach void setUp() { userRepository.deleteAll(); // Clean slate before each test + roleRepository.deleteAll(); Role adminRole = new Role(); - adminRole.setId(2L); adminRole.setErole(ERole.ROLE_ADMIN); + roleRepository.save(adminRole); Role userRole = new Role(); - userRole.setId(1L); userRole.setErole(ERole.ROLE_USER); + roleRepository.save(userRole); user1 = new User(); user1.setEmail("adminUser"); @@ -78,6 +79,7 @@ void setUp() { @AfterEach void tearDown() { userRepository.deleteAll(); // Clean up after each test + roleRepository.deleteAll(); } @Test diff --git a/src/test/java/com/podzilla/auth/controller/AuthenticationControllerTest.java b/src/test/java/com/podzilla/auth/controller/AuthenticationControllerTest.java new file mode 100644 index 0000000..cc35333 --- /dev/null +++ b/src/test/java/com/podzilla/auth/controller/AuthenticationControllerTest.java @@ -0,0 +1,241 @@ +package com.podzilla.auth.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +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 com.podzilla.auth.service.TokenService; // Assuming you have a JwtService +import jakarta.servlet.http.Cookie; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.Optional; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +class AuthenticationControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + + @Autowired + private RoleRepository roleRepository; // Inject RoleRepository + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private TokenService tokenService; + + private final String testUserEmail = "testuser@example.com"; + private final String testUserPassword = "password123"; + + @BeforeEach + void setUp() { + roleRepository.deleteAll(); + userRepository.deleteAll(); // Clean slate before each test + + Role adminRole = new Role(); + adminRole.setErole(ERole.ROLE_ADMIN); + roleRepository.save(adminRole); + + Role userRole = new Role(); + userRole.setErole(ERole.ROLE_USER); + roleRepository.save(userRole); + + // Create a pre-existing user for login tests + User user = new User(); + user.setEmail(testUserEmail); + user.setPassword(passwordEncoder.encode(testUserPassword)); + user.setName("Test User"); // Assuming name is required or desired + user.getRoles().add(userRole); + userRepository.save(user); + } + + @AfterEach + void tearDown() { + userRepository.deleteAll(); // Clean up after each test + roleRepository.deleteAll(); + } + + @Test + void registerUser_shouldCreateNewUser_whenEmailIsNotTaken() throws Exception { + SignupRequest signupRequest = new SignupRequest(); + signupRequest.setEmail("newuser@example.com"); + signupRequest.setPassword("newpassword"); + signupRequest.setName("New User"); + + mockMvc.perform(post("/auth/register") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(signupRequest))) + .andExpect(status().isCreated()) + .andExpect(content().string("Account registered.")); + + // Verify user exists in the database + Optional registeredUser = userRepository.findByEmail("newuser@example.com"); + assertTrue(registeredUser.isPresent()); + assertEquals("New User", registeredUser.get().getName()); + assertTrue(passwordEncoder.matches("newpassword", registeredUser.get().getPassword())); + // Verify role assignment if applicable (assuming default role is USER) + assertTrue(registeredUser.get().getRoles().stream() + .anyMatch(role -> role.getErole() == ERole.ROLE_USER)); + } + + @Test + void registerUser_shouldReturnBadRequest_whenEmailIsTaken() throws Exception { + SignupRequest signupRequest = new SignupRequest(); + signupRequest.setEmail(testUserEmail); // Email already exists from setup + signupRequest.setPassword("anotherpassword"); + signupRequest.setName("Another User"); + + mockMvc.perform(post("/auth/register") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(signupRequest))) + // Assuming AuthenticationService throws an exception leading to 4xx + // Adjust status code based on actual exception handling (e.g., 400 Bad Request or 409 Conflict) + .andExpect(status().isBadRequest()); // Or Conflict (409) depending on implementation + } + + + @Test + void login_shouldReturnOkAndSetCookies_whenCredentialsAreValid() throws Exception { + LoginRequest loginRequest = new LoginRequest(); + loginRequest.setEmail(testUserEmail); + loginRequest.setPassword(testUserPassword); + + mockMvc.perform(post("/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isOk()) + .andExpect(content().string("User " + testUserEmail + " logged in successfully")) + .andExpect(cookie().exists("accessToken")) // Check if cookies are set + .andExpect(cookie().exists("refreshToken")); + // Add more specific cookie checks if needed (e.g., HttpOnly, Secure, MaxAge) + // .andExpect(cookie().httpOnly("accessToken", true)) + // .andExpect(cookie().maxAge("accessToken", expectedMaxAge)); + } + + @Test + void login_shouldReturnUnauthorized_whenCredentialsAreInvalid() throws Exception { + LoginRequest loginRequest = new LoginRequest(); + loginRequest.setEmail(testUserEmail); + loginRequest.setPassword("wrongpassword"); + + mockMvc.perform(post("/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isUnauthorized()); // Standard Spring Security behavior + } + + @Test + void logoutUser_shouldClearCookiesAndReturnOk() throws Exception { + // First, log in to get cookies + LoginRequest loginRequest = new LoginRequest(); + loginRequest.setEmail(testUserEmail); + loginRequest.setPassword(testUserPassword); + + MvcResult loginResult = mockMvc.perform(post("/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isOk()) + .andReturn(); + + Cookie accessTokenCookie = loginResult.getResponse().getCookie("accessToken"); + Cookie refreshTokenCookie = loginResult.getResponse().getCookie("refreshToken"); + + assertNotNull(accessTokenCookie); + assertNotNull(refreshTokenCookie); + + // Perform logout using the obtained cookies + mockMvc.perform(post("/auth/logout") + .cookie(accessTokenCookie) // Send cookies back + .cookie(refreshTokenCookie)) + .andExpect(status().isOk()) + .andExpect(content().string("You've been signed out!")) + // Check that cookies are cleared (Max-Age=0) + .andExpect(cookie().value("accessToken", (String) null)) + .andExpect(cookie().value("refreshToken", (String) null)); + } + + @Test + void refreshToken_shouldReturnOkAndNewTokens_whenRefreshTokenIsValid() throws Exception { + // 1. Login to get initial tokens + LoginRequest loginRequest = new LoginRequest(); + loginRequest.setEmail(testUserEmail); + loginRequest.setPassword(testUserPassword); + + MvcResult loginResult = mockMvc.perform(post("/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isOk()) + .andReturn(); + + Cookie initialAccessToken = loginResult.getResponse().getCookie("accessToken"); + Cookie initialRefreshToken = loginResult.getResponse().getCookie("refreshToken"); + assertNotNull(initialRefreshToken); + assertNotNull(initialAccessToken); + assertNotEquals(0, initialRefreshToken.getMaxAge()); // Ensure it's not already expired + + Thread.sleep(3000); + + // 2. Use the refresh token to get new tokens + MvcResult refreshResult = mockMvc.perform(post("/auth/refresh-token") + .cookie(initialRefreshToken)) // Send only the refresh token + .andExpect(status().isOk()) + .andExpect(content().string(containsString("refreshed tokens successfully"))) + .andExpect(cookie().exists("accessToken")) + .andExpect(cookie().exists("refreshToken")) + .andReturn(); + + // 3. Verify new tokens are different from old ones + Cookie newAccessToken = refreshResult.getResponse().getCookie("accessToken"); + Cookie newRefreshToken = refreshResult.getResponse().getCookie("refreshToken"); + + assertNotNull(newAccessToken); + assertNotNull(newRefreshToken); + assertNotEquals(initialAccessToken.getValue(), newAccessToken.getValue()); + // Depending on your implementation, the refresh token might also be rotated + // assertNotEquals(initialRefreshToken.getValue(), newRefreshToken.getValue()); + + // Optional: Verify the expiry/max-age of the new cookies + assertNotEquals(0, newAccessToken.getMaxAge()); + assertNotEquals(0, newRefreshToken.getMaxAge()); + } + + @Test + void refreshToken_shouldReturnUnauthorized_whenRefreshTokenIsMissingOrInvalid() throws Exception { + // Test without sending any cookie + mockMvc.perform(post("/auth/refresh-token")) + .andExpect(status().isForbidden()); + // Test with an invalid/expired cookie + Cookie invalidCookie = new Cookie("refreshToken", "invalid-or-expired-token-value"); + invalidCookie.setPath("/"); // Set path and other relevant attributes if needed + + mockMvc.perform(post("/auth/refresh-token") + .cookie(invalidCookie)) + .andExpect(status().isForbidden()); + } +} \ No newline at end of file diff --git a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java index 2f5fde0..3947094 100644 --- a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java @@ -18,6 +18,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -263,7 +264,7 @@ void refreshToken_shouldReturnEmailAndGenerateAccessToken_whenTokenIsValid() { } @Test - void refreshToken_shouldThrowValidationException_whenTokenIsInvalid() { + void refreshToken_shouldThrowAccessDeniedException_whenTokenIsInvalid() { // Arrange String invalidRefreshToken = "invalid-refresh-token"; @@ -273,11 +274,11 @@ void refreshToken_shouldThrowValidationException_whenTokenIsInvalid() { .thenThrow(new IllegalArgumentException("Token invalid")); // Act & Assert - ValidationException exception = assertThrows(ValidationException.class, () -> { + AccessDeniedException exception = assertThrows(AccessDeniedException.class, () -> { authenticationService.refreshToken(httpServletRequest, httpServletResponse); }); - assertEquals("Validation error: Invalid refresh token.", + assertEquals("Invalid refresh token.", exception.getMessage()); verify(tokenService).getRefreshTokenFromCookie(httpServletRequest); verify(tokenService).renewRefreshToken(invalidRefreshToken, httpServletResponse); diff --git a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java index 980d619..6879bfd 100644 --- a/src/test/java/com/podzilla/auth/service/TokenServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/TokenServiceTest.java @@ -20,6 +20,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Value; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.util.WebUtils; diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 6ac6fdd..fe561b7 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -6,5 +6,5 @@ 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.secret=${SECRET_KEY:testSecretKeyForJwtTokenGenerationWhichIsVeryLongAndSecure} jwt.token.expires=30 \ No newline at end of file From a784ec64b7b31794d8d9f92c578f249ec1e08102 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Thu, 1 May 2025 22:06:11 +0300 Subject: [PATCH 52/60] Add cache configuration and update application properties for cache management --- pom.xml | 12 ++++++++++++ .../com/podzilla/auth/redis/RedisCacheConfig.java | 11 +++++++++-- src/main/resources/application.properties | 4 +++- src/test/resources/application.properties | 4 +++- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index d6c6bf7..84202a5 100644 --- a/pom.xml +++ b/pom.xml @@ -96,6 +96,18 @@ jakarta.validation-api 3.0.2 + + org.mockito + mockito-core + 5.14.2 + test + + + org.mockito + mockito-junit-jupiter + 5.14.2 + test + diff --git a/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java b/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java index 93ed31a..1a169bd 100644 --- a/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java +++ b/src/main/java/com/podzilla/auth/redis/RedisCacheConfig.java @@ -1,6 +1,9 @@ package com.podzilla.auth.redis; import com.podzilla.auth.dto.CustomUserDetails; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.CacheManager; +import org.springframework.cache.support.NoOpCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; @@ -17,8 +20,12 @@ public class RedisCacheConfig { private static final int CACHE_TTL = 60 * 60; @Bean - public RedisCacheManager cacheManager( - final RedisConnectionFactory redisConnectionFactory) { + public CacheManager cacheManager( + final RedisConnectionFactory redisConnectionFactory, + @Value("${appconfig.cache.enabled}") final String cacheEnabled) { + if (!Boolean.parseBoolean(cacheEnabled)) { + return new NoOpCacheManager(); + } RedisCacheConfiguration defaultConfig = RedisCacheConfiguration .defaultCacheConfig() diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 6dcc38a..6d68851 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -33,4 +33,6 @@ logging.level.org.springframework.security=DEBUG #jwt.token.secret jwt.token.secret=${SECRET_KEY} -jwt.token.expires=30 \ No newline at end of file +jwt.token.expires=30 + +appconfig.cache.enabled=true \ No newline at end of file diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index fe561b7..b169238 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -7,4 +7,6 @@ spring.jpa.hibernate.ddl-auto=create-drop logging.level.org.hibernate.SQL=debug jwt.token.secret=${SECRET_KEY:testSecretKeyForJwtTokenGenerationWhichIsVeryLongAndSecure} -jwt.token.expires=30 \ No newline at end of file +jwt.token.expires=30 + +appconfig.cache.enabled=false \ No newline at end of file From 86e1c23934cc4f610f1ee6e6a8f872ca37513e15 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Fri, 2 May 2025 18:31:38 +0300 Subject: [PATCH 53/60] Enhance authentication flow and caching: add checks for logged-in users, improve CustomUserDetails, and implement caching for user details retrieval --- .../podzilla/auth/dto/CustomUserDetails.java | 63 +++++++++++++++++++ .../security/JWTAuthenticationFilter.java | 3 +- .../auth/service/AuthenticationService.java | 6 ++ .../service/CustomUserDetailsService.java | 6 +- .../service/AuthenticationServiceTest.java | 3 + 5 files changed, 79 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java index edcf3e6..cd06524 100644 --- a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java +++ b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java @@ -1,7 +1,9 @@ package com.podzilla.auth.dto; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.Getter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -12,13 +14,28 @@ public class CustomUserDetails implements UserDetails { private String username; + + @JsonIgnore private String password; @JsonDeserialize(contentAs = CustomGrantedAuthority.class) private Set authorities; + @Getter + private final boolean accountNonExpired; + @Getter + private final boolean accountNonLocked; + @Getter + private final boolean credentialsNonExpired; + @Getter + private final boolean enabled; + public CustomUserDetails() { // No-arg constructor required by Jackson + this.accountNonExpired = true; + this.accountNonLocked = true; + this.credentialsNonExpired = true; + this.enabled = true; } public CustomUserDetails(final String username, final String password, @@ -26,6 +43,25 @@ public CustomUserDetails(final String username, final String password, this.username = username; this.password = password; this.authorities = authorities; + this.accountNonExpired = true; + this.accountNonLocked = true; + this.credentialsNonExpired = true; + this.enabled = true; + } + + public CustomUserDetails(final String username, final String password, + final Set authorities, + final boolean accountNonExpired, + final boolean accountNonLocked, + final boolean credentialsNonExpired, + final boolean enabled) { + this.username = username; + this.password = password; + this.authorities = authorities; + this.accountNonExpired = accountNonExpired; + this.accountNonLocked = accountNonLocked; + this.credentialsNonExpired = credentialsNonExpired; + this.enabled = enabled; } @Override @@ -42,4 +78,31 @@ public String getPassword() { public Collection getAuthorities() { return authorities; } + + public void eraseCredentials() { + this.password = null; + } + + public int hashCode() { + return this.username.hashCode(); + } + + public boolean equals(final Object obj) { + if (obj instanceof CustomUserDetails user) { + return this.username.equals(user.getUsername()); + } else { + return false; + } + } + + public String toString() { + return this.getClass().getName() + " [" + + "Username=" + this.username + ", " + + "Password=[PROTECTED], " + + "Enabled=" + this.enabled + ", " + + "AccountNonExpired=" + this.accountNonExpired + ", " + + "CredentialsNonExpired=" + this.credentialsNonExpired + ", " + + "AccountNonLocked=" + this.accountNonLocked + ", " + + "Granted Authorities=" + this.authorities + "]"; + } } diff --git a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java index a2d2855..3af4f3b 100644 --- a/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java +++ b/src/main/java/com/podzilla/auth/security/JWTAuthenticationFilter.java @@ -47,7 +47,8 @@ protected void doFilterInternal(final HttpServletRequest request, String userEmail = tokenService.extractEmail(); UserDetails userDetails = - customUserDetailsService.loadUserByUsername(userEmail); + customUserDetailsService + .loadUserByUsernameCached(userEmail); UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 37ca647..c82d208 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -2,6 +2,7 @@ import com.podzilla.auth.dto.LoginRequest; import com.podzilla.auth.dto.SignupRequest; +import com.podzilla.auth.exception.InvalidActionException; import com.podzilla.auth.exception.ValidationException; import com.podzilla.auth.model.ERole; import com.podzilla.auth.model.Role; @@ -47,6 +48,11 @@ public AuthenticationService( public String login(final LoginRequest loginRequest, final HttpServletResponse response) { + if (SecurityContextHolder.getContext().getAuthentication() + instanceof UsernamePasswordAuthenticationToken) { + throw new InvalidActionException("User already logged in."); + } + Authentication authenticationRequest = UsernamePasswordAuthenticationToken. unauthenticated( diff --git a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java index eee38ac..1aaf662 100644 --- a/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java +++ b/src/main/java/com/podzilla/auth/service/CustomUserDetailsService.java @@ -27,7 +27,6 @@ public CustomUserDetailsService(final UserRepository userRepository) { } @Override - @Cacheable(value = "userDetails", key = "#email") public UserDetails loadUserByUsername(final String email) { User user = userRepository.findByEmail(email) .orElseThrow(() -> @@ -51,4 +50,9 @@ public UserDetails loadUserByUsername(final String email) { authorities ); } + + @Cacheable(value = "userDetails", key = "#email") + public UserDetails loadUserByUsernameCached(final String email) { + return loadUserByUsername(email); + } } diff --git a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java index 3947094..8c01d4a 100644 --- a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java @@ -23,6 +23,7 @@ import org.springframework.security.authentication.BadCredentialsException; 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; @@ -79,6 +80,8 @@ void setUp() { .password("encodedPassword") .roles(Collections.singleton(userRole)) .build(); + + SecurityContextHolder.getContext().setAuthentication(null); } // --- registerAccount Tests --- From 5b2b6e55228101f6ac196b40a9b11b9853043f9c Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Fri, 2 May 2025 18:45:15 +0300 Subject: [PATCH 54/60] Refactor equals method in CustomUserDetails for improved readability --- src/main/java/com/podzilla/auth/dto/CustomUserDetails.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java index cd06524..f8702a3 100644 --- a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java +++ b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java @@ -88,8 +88,9 @@ public int hashCode() { } public boolean equals(final Object obj) { - if (obj instanceof CustomUserDetails user) { - return this.username.equals(user.getUsername()); + if (obj instanceof CustomUserDetails) { + return this.username + .equals(((CustomUserDetails) obj).getUsername()); } else { return false; } From fd4635841be7a79fdce844af65f8f8869ea17888 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sat, 3 May 2025 10:07:53 +0300 Subject: [PATCH 55/60] Refactor account registration and token handling: streamline null checks and improve exception handling --- .../auth/service/AuthenticationService.java | 52 ++++++++++++------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index c82d208..55cdc54 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -72,20 +72,14 @@ public String login(final LoginRequest loginRequest, } public void registerAccount(final SignupRequest signupRequest) { - if (signupRequest.getPassword() == null - || signupRequest.getPassword().isEmpty()) { - throw new ValidationException("Password cannot be empty."); - } - - if (signupRequest.getName() == null - || signupRequest.getName().isEmpty()) { - throw new ValidationException("Name cannot be empty."); - } - - if (signupRequest.getEmail() == null - || signupRequest.getEmail().isEmpty()) { - throw new ValidationException("Email cannot be empty."); - } + checkNotNullValidationException(signupRequest, + "Signup request cannot be null."); + checkNotNullValidationException(signupRequest.getEmail(), + "Email cannot be null."); + checkNotNullValidationException(signupRequest.getPassword(), + "Password cannot be null."); + checkNotNullValidationException(signupRequest.getName(), + "Name cannot be null."); if (userRepository.existsByEmail(signupRequest.getEmail())) { throw new ValidationException("Email already in use."); @@ -101,9 +95,7 @@ public void registerAccount(final SignupRequest signupRequest) { .build(); Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); - if (role == null) { - throw new ValidationException("Role_USER not found."); - } + checkNotNullValidationException(role, "Role_USER not found."); account.setRoles(Collections.singleton(role)); userRepository.save(account); @@ -120,9 +112,8 @@ public String refreshToken(final HttpServletRequest request, try { String refreshToken = tokenService.getRefreshTokenFromCookie(request); - if (refreshToken == null) { - throw new AccessDeniedException("Refresh token not found."); - } + checkNotNullAccessDeniedException(refreshToken, + "Refresh token cannot be found."); String email = tokenService.renewRefreshToken(refreshToken, response); tokenService.generateAccessToken(email, response); @@ -131,4 +122,25 @@ public String refreshToken(final HttpServletRequest request, throw new AccessDeniedException("Invalid refresh token."); } } + + public void checkNotNullValidationException(final String value, + final String message) { + if (value == null || value.isEmpty()) { + throw new ValidationException(message); + } + } + + public void checkNotNullValidationException(final Object value, + final String message) { + if (value == null) { + throw new ValidationException(message); + } + } + + public void checkNotNullAccessDeniedException(final Object value, + final String message) { + if (value == null) { + throw new AccessDeniedException(message); + } + } } From 5b178e342f99901596dd4647ff6bc441f0eaed2b Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sat, 3 May 2025 10:08:45 +0300 Subject: [PATCH 56/60] Refactor account registration and token handling: streamline null checks and improve exception handling --- .../com/podzilla/auth/service/AuthenticationService.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index 55cdc54..d4a4c58 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -123,21 +123,21 @@ public String refreshToken(final HttpServletRequest request, } } - public void checkNotNullValidationException(final String value, + private void checkNotNullValidationException(final String value, final String message) { if (value == null || value.isEmpty()) { throw new ValidationException(message); } } - public void checkNotNullValidationException(final Object value, + private void checkNotNullValidationException(final Object value, final String message) { if (value == null) { throw new ValidationException(message); } } - public void checkNotNullAccessDeniedException(final Object value, + private void checkNotNullAccessDeniedException(final Object value, final String message) { if (value == null) { throw new AccessDeniedException(message); From 7029f7eb5f7acda01ef9e6bbc67f8bcd174647b7 Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sat, 3 May 2025 10:30:29 +0300 Subject: [PATCH 57/60] Refactor CustomUserDetails constructor: improve parameter order and clarity --- src/main/java/com/podzilla/auth/dto/CustomUserDetails.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java index f8702a3..f5bed3d 100644 --- a/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java +++ b/src/main/java/com/podzilla/auth/dto/CustomUserDetails.java @@ -49,12 +49,13 @@ public CustomUserDetails(final String username, final String password, this.enabled = true; } - public CustomUserDetails(final String username, final String password, - final Set authorities, + public CustomUserDetails(final String username, + final String password, + final boolean enabled, final boolean accountNonExpired, final boolean accountNonLocked, final boolean credentialsNonExpired, - final boolean enabled) { + final Set authorities) { this.username = username; this.password = password; this.authorities = authorities; From f464838681e4489e29a505ae22b00b098c2915ab Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sat, 3 May 2025 10:49:30 +0300 Subject: [PATCH 58/60] Update validation message in AuthenticationServiceTest and enable user in CustomUserDetailsServiceTest --- .../com/podzilla/auth/service/AuthenticationServiceTest.java | 2 +- .../com/podzilla/auth/service/CustomUserDetailsServiceTest.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java index 8c01d4a..87ac508 100644 --- a/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/AuthenticationServiceTest.java @@ -141,7 +141,7 @@ void registerAccount_shouldThrowValidationException_whenPasswordIsEmpty() { authenticationService.registerAccount(signupRequest); }); - assertEquals("Validation error: Password cannot be empty.", + assertEquals("Validation error: Password cannot be null.", exception.getMessage()); verify(userRepository, never()).existsByEmail(anyString()); verify(passwordEncoder, never()).encode(anyString()); diff --git a/src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java b/src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java index c411ed8..b660052 100644 --- a/src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java +++ b/src/test/java/com/podzilla/auth/service/CustomUserDetailsServiceTest.java @@ -55,6 +55,7 @@ void setUp() { .email(userEmail) .password(userPassword) .roles(roles) + .enabled(true) .build(); } From 2e202e04c677e9f0a115ddf0217c23c56781efef Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sat, 3 May 2025 11:27:38 +0300 Subject: [PATCH 59/60] Set user as enabled during account creation in AuthenticationService --- .../java/com/podzilla/auth/service/AuthenticationService.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index d4a4c58..b3a12fd 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -92,6 +92,7 @@ public void registerAccount(final SignupRequest signupRequest) { .password( passwordEncoder.encode( signupRequest.getPassword())) + .enabled(true) .build(); Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null); From 79518c996a7527741add4a67799103c54d6a935c Mon Sep 17 00:00:00 2001 From: Nour Eldien Ayman Date: Sat, 3 May 2025 11:29:21 +0300 Subject: [PATCH 60/60] Remove automatic user enablement during account creation in AuthenticationService --- .../java/com/podzilla/auth/service/AuthenticationService.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index b3a12fd..d4a4c58 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -92,7 +92,6 @@ public void registerAccount(final SignupRequest signupRequest) { .password( passwordEncoder.encode( signupRequest.getPassword())) - .enabled(true) .build(); Role role = roleRepository.findByErole(ERole.ROLE_USER).orElse(null);