diff --git a/README.md b/README.md new file mode 100644 index 0000000..22086c4 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +## DDD Refactoring (Work in Progress) + +This branch contains ongoing refactoring to DDD structure. diff --git a/src/main/java/se/jensen/yuki/springboot/Application.java b/src/main/java/se/jensen/yuki/springboot/Application.java index be4f038..ed2b728 100644 --- a/src/main/java/se/jensen/yuki/springboot/Application.java +++ b/src/main/java/se/jensen/yuki/springboot/Application.java @@ -3,9 +3,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.persistence.autoconfigure.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication -@EntityScan("se.jensen.yuki.springboot.model") +@EntityScan("se.jensen.yuki.springboot") +@EnableJpaRepositories("se.jensen.yuki.springboot") public class Application { public static void main(String[] args) { diff --git a/src/main/java/se/jensen/yuki/springboot/config/JwtFilter.java b/src/main/java/se/jensen/yuki/springboot/config/JwtFilter.java index 5b0f852..52a5abf 100644 --- a/src/main/java/se/jensen/yuki/springboot/config/JwtFilter.java +++ b/src/main/java/se/jensen/yuki/springboot/config/JwtFilter.java @@ -5,29 +5,32 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; -import se.jensen.yuki.springboot.exception.UnauthorizedException; +import se.jensen.yuki.springboot.exception.UserNotFoundException; import se.jensen.yuki.springboot.model.SecurityUser; -import se.jensen.yuki.springboot.model.User; -import se.jensen.yuki.springboot.repository.UserRepository; import se.jensen.yuki.springboot.service.JwtService; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.usecase.UserLoadService; import java.io.IOException; +@Slf4j @Component @RequiredArgsConstructor public class JwtFilter extends OncePerRequestFilter { private final JwtService jwtService; - private final UserRepository userRepository; + private final UserLoadService userLoadService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + log.debug("Starting JWT filter for request: {}", request.getRequestURI()); final String authHeader = request.getHeader("Authorization"); if (authHeader == null || !authHeader.startsWith("Bearer ")) { @@ -39,24 +42,32 @@ protected void doFilterInternal(HttpServletRequest request, if (!jwtService.validateToken(jwt)) { // invalid token: do not set authentication, just continue + log.warn("Invalid JWT token"); filterChain.doFilter(request, response); return; } Long userId = jwtService.extractUserId(jwt); - User user = userRepository.findById(userId).orElseThrow(() -> new UnauthorizedException("User not found")); - SecurityUser securityUser = new SecurityUser(user); - UsernamePasswordAuthenticationToken authToken = - new UsernamePasswordAuthenticationToken( - securityUser, - null, - securityUser.getAuthorities() - ); + try { + UserJpaEntity user = userLoadService.requireJpaById(userId); - if (SecurityContextHolder.getContext().getAuthentication() == null) { - SecurityContextHolder.getContext().setAuthentication(authToken); + SecurityUser securityUser = new SecurityUser(user.getId(), user.getEmail(), user.getRole(), user.getPassword()); + UsernamePasswordAuthenticationToken authToken = + new UsernamePasswordAuthenticationToken( + securityUser, + null, + securityUser.getAuthorities() + ); + + if (SecurityContextHolder.getContext().getAuthentication() == null) { + SecurityContextHolder.getContext().setAuthentication(authToken); + } + } catch (UserNotFoundException e) { + log.warn("User not found for ID extracted from JWT: {}", userId); + SecurityContextHolder.clearContext(); + // no response manipulation → treat as unauthenticated } filterChain.doFilter(request, response); } diff --git a/src/main/java/se/jensen/yuki/springboot/controller/UserController.java b/src/main/java/se/jensen/yuki/springboot/controller/UserController.java deleted file mode 100644 index fcc5719..0000000 --- a/src/main/java/se/jensen/yuki/springboot/controller/UserController.java +++ /dev/null @@ -1,85 +0,0 @@ -package se.jensen.yuki.springboot.controller; - -import jakarta.validation.Valid; -import lombok.RequiredArgsConstructor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import se.jensen.yuki.springboot.dto.user.UserProfileResponse; -import se.jensen.yuki.springboot.dto.user.UserUpdateEmailRequest; -import se.jensen.yuki.springboot.dto.user.UserUpdatePasswordRequest; -import se.jensen.yuki.springboot.dto.user.UserUpdateProfileRequest; -import se.jensen.yuki.springboot.service.AuthService; -import se.jensen.yuki.springboot.service.UserService; - -import java.util.List; - -@RestController -@RequiredArgsConstructor -@RequestMapping("/users") -public class UserController { - private static final Logger log = LoggerFactory.getLogger(UserController.class); - private final UserService userService; - private final AuthService authService; - - @GetMapping("/admin/users") - public ResponseEntity> getAllUsers() { - log.info("Starting to get all users"); - return ResponseEntity.ok().body(userService.getAllUsers()); - } - - @GetMapping("/me") - public ResponseEntity getMyProfile() { - log.info("Starting to get my profile"); - return ResponseEntity - .ok() - .body(userService.getUserById(authService.getCurrentUserId())); - } - - @GetMapping("/{id}") - public ResponseEntity getUserById(@PathVariable Long id) { - log.info("Starting to get a user by ID={}", id); - return ResponseEntity - .ok() - .body(userService.getUserById(id)); - } - - @PutMapping("/me/profile") - public ResponseEntity updateProfile(@Valid @RequestBody UserUpdateProfileRequest request) { - log.info("Stating to update my profilee"); - return ResponseEntity - .ok() - .body(userService.updateProfile(authService.getCurrentUserId(), request)); - } - - @PutMapping("/me/email") - public ResponseEntity updateEmail(@Valid @RequestBody UserUpdateEmailRequest request) { - authService.checkCurrentPassword(request.currentPassword()); - log.info("Stating to update my Account"); - userService.updateEmail(authService.getCurrentUserId(), request); - return ResponseEntity - .noContent() - .build(); - } - - @PutMapping("/me/password") - public ResponseEntity updatePassword(@Valid @RequestBody UserUpdatePasswordRequest request) { - authService.checkCurrentPassword(request.currentPassword()); - log.info("Stating to update my Account"); - userService.updatePassword(authService.getCurrentUserId(), request); - return ResponseEntity.noContent().build(); - } - - @DeleteMapping("/{id}") - public ResponseEntity deleteUser(@PathVariable Long id) { - log.info("Starting to delete a user by id={}", id); - Long userId = authService.getCurrentUserId(); - if (!id.equals(userId)) { - throw new IllegalArgumentException("Wrong request id=" + id); - } - userService.deleteUser(id); - log.info("Deleted a user successfully with id={}", id); - return ResponseEntity.noContent().build(); - } -} diff --git a/src/main/java/se/jensen/yuki/springboot/dto/user/UserProfileResponse.java b/src/main/java/se/jensen/yuki/springboot/dto/user/UserProfileResponse.java deleted file mode 100644 index acba8e7..0000000 --- a/src/main/java/se/jensen/yuki/springboot/dto/user/UserProfileResponse.java +++ /dev/null @@ -1,5 +0,0 @@ -package se.jensen.yuki.springboot.dto.user; - -public record UserProfileResponse(Long id, String username, String email, String role, String displayName, String bio, - String avatarUrl) { -} diff --git a/src/main/java/se/jensen/yuki/springboot/mapper/AuthMapper.java b/src/main/java/se/jensen/yuki/springboot/mapper/AuthMapper.java index d330a44..731714a 100644 --- a/src/main/java/se/jensen/yuki/springboot/mapper/AuthMapper.java +++ b/src/main/java/se/jensen/yuki/springboot/mapper/AuthMapper.java @@ -4,22 +4,22 @@ import org.mapstruct.Mapping; import org.mapstruct.NullValuePropertyMappingStrategy; import se.jensen.yuki.springboot.dto.auth.AuthRegisterRequestDTO; -import se.jensen.yuki.springboot.model.User; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Mapper(componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) public interface AuthMapper { @Mapping(target = "role", constant = "USER") @Mapping(target = "displayName", source = "username") @Mapping(target = "bio", constant = "") - User registerDtoToUser(AuthRegisterRequestDTO dto); + UserJpaEntity registerDtoToUser(AuthRegisterRequestDTO dto); // User loginDtoToUser(LoginDTO dto); // -// LoginDTO toLoginDTO(User user); +// LoginDTO toLoginDTO(UserJpaEntity user); // User toUser(AuthRegisterRequestDTO requestDTO) { -// User user = new User(); +// UserJpaEntity user = new User(); // user.setUsername(requestDTO.username()); // user.setEmail(requestDTO.email()); // user.setPassword(requestDTO.password()); diff --git a/src/main/java/se/jensen/yuki/springboot/mapper/CommentMapper.java b/src/main/java/se/jensen/yuki/springboot/mapper/CommentMapper.java index 787cb00..51fdfb1 100644 --- a/src/main/java/se/jensen/yuki/springboot/mapper/CommentMapper.java +++ b/src/main/java/se/jensen/yuki/springboot/mapper/CommentMapper.java @@ -10,7 +10,7 @@ import se.jensen.yuki.springboot.dto.comment.CommentUpdateResponse; import se.jensen.yuki.springboot.model.Comment; import se.jensen.yuki.springboot.model.Post; -import se.jensen.yuki.springboot.model.User; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Mapper(componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) public interface CommentMapper { @@ -19,14 +19,14 @@ public interface CommentMapper { @Mapping(target = "parent", ignore = true) @Mapping(target = "deleted", expression = "java(false)") @Mapping(target = "edited", expression = "java(false)") - Comment createRequestToComment(Post post, User author, CommentCreateRequest request); + Comment createRequestToComment(Post post, UserJpaEntity author, CommentCreateRequest request); @Mapping(target = "id", ignore = true) @Mapping(target = "content", source = "request.content") @Mapping(target = "parent", source = "parent") @Mapping(target = "deleted", expression = "java(false)") @Mapping(target = "edited", expression = "java(false)") - Comment createRequestToComment(Post post, User author, Comment parent, CommentCreateRequest request); + Comment createRequestToComment(Post post, UserJpaEntity author, Comment parent, CommentCreateRequest request); @Mapping(target = "authorUserId", source = "comment.author.id") @Mapping(target = "authorUsername", source = "comment.author.username") diff --git a/src/main/java/se/jensen/yuki/springboot/mapper/PostMapper.java b/src/main/java/se/jensen/yuki/springboot/mapper/PostMapper.java index 5289ade..49e9c9b 100644 --- a/src/main/java/se/jensen/yuki/springboot/mapper/PostMapper.java +++ b/src/main/java/se/jensen/yuki/springboot/mapper/PostMapper.java @@ -7,7 +7,7 @@ import se.jensen.yuki.springboot.dto.post.PostCreateResponse; import se.jensen.yuki.springboot.dto.post.PostFeedResponse; import se.jensen.yuki.springboot.model.Post; -import se.jensen.yuki.springboot.model.User; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Mapper(componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) public interface PostMapper { @@ -15,10 +15,10 @@ public interface PostMapper { @Mapping(target = "id", ignore = true) @Mapping(target = "user", expression = "java(author)") @Mapping(target = "originalPost", ignore = true) - Post PostCreateToPost(PostCreateRequest requestDTO, User author); + Post PostCreateToPost(PostCreateRequest requestDTO, UserJpaEntity author); PostCreateResponse toCreateResponse(Post post); - + PostFeedResponse toFeedResponse(Post post); } diff --git a/src/main/java/se/jensen/yuki/springboot/mapper/UserMapper.java b/src/main/java/se/jensen/yuki/springboot/mapper/UserMapper.java deleted file mode 100644 index 5e03c7d..0000000 --- a/src/main/java/se/jensen/yuki/springboot/mapper/UserMapper.java +++ /dev/null @@ -1,26 +0,0 @@ -package se.jensen.yuki.springboot.mapper; - -import jakarta.validation.Valid; -import org.mapstruct.Mapper; -import org.mapstruct.Mapping; -import org.mapstruct.MappingTarget; -import org.mapstruct.NullValuePropertyMappingStrategy; -import se.jensen.yuki.springboot.dto.user.*; -import se.jensen.yuki.springboot.model.User; - -@Mapper(componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) -public interface UserMapper { - // @Mapping(target = "id", ignore = true) -// @Mapping(target = "enabled", ignore = true) -// @Mapping(target = "posts", ignore = true) - User toUser(UserRequestDTO dto); - - UserProfileResponse toResponse(User user); - - void FromUpdateProfileRequest(UserUpdateProfileRequest dto, @MappingTarget User user); - - void FromUpdateEmailRequest(@Valid UserUpdateEmailRequest request, @MappingTarget User user); - - @Mapping(target = "password", source = "request.newPassword") - void FromUpdatePasswordRequest(@Valid UserUpdatePasswordRequest request, @MappingTarget User user); -} diff --git a/src/main/java/se/jensen/yuki/springboot/model/Block.java b/src/main/java/se/jensen/yuki/springboot/model/Block.java index 45ee162..b37e4ed 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/Block.java +++ b/src/main/java/se/jensen/yuki/springboot/model/Block.java @@ -4,6 +4,7 @@ import lombok.*; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Entity @Setter @@ -26,10 +27,10 @@ public class Block extends BaseEntity { @ManyToOne(optional = false) @JoinColumn(name = "blocking_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User blocking; + private UserJpaEntity blocking; @ManyToOne(optional = false) @JoinColumn(name = "blocked_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User blocked; + private UserJpaEntity blocked; } \ No newline at end of file diff --git a/src/main/java/se/jensen/yuki/springboot/model/Comment.java b/src/main/java/se/jensen/yuki/springboot/model/Comment.java index 7ef6309..ad7f57b 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/Comment.java +++ b/src/main/java/se/jensen/yuki/springboot/model/Comment.java @@ -4,6 +4,7 @@ import lombok.*; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Entity @Getter @@ -23,7 +24,7 @@ public class Comment extends BaseEntity { @ManyToOne(optional = false) @JoinColumn(name = "user_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User author; + private UserJpaEntity author; @ManyToOne(optional = false) @JoinColumn(name = "post_id", nullable = false) diff --git a/src/main/java/se/jensen/yuki/springboot/model/CommentLike.java b/src/main/java/se/jensen/yuki/springboot/model/CommentLike.java index 4336a4d..fc4447e 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/CommentLike.java +++ b/src/main/java/se/jensen/yuki/springboot/model/CommentLike.java @@ -4,6 +4,7 @@ import lombok.*; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Entity @Setter @@ -26,7 +27,7 @@ public class CommentLike extends BaseEntity { @ManyToOne(optional = false) @JoinColumn(name = "user_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User user; + private UserJpaEntity user; @ManyToOne(optional = false) @JoinColumn(name = "comment_id", nullable = false) diff --git a/src/main/java/se/jensen/yuki/springboot/model/Follow.java b/src/main/java/se/jensen/yuki/springboot/model/Follow.java index d078104..f437e87 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/Follow.java +++ b/src/main/java/se/jensen/yuki/springboot/model/Follow.java @@ -4,6 +4,7 @@ import lombok.*; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Entity @Setter @@ -26,10 +27,10 @@ public class Follow extends BaseEntity { @ManyToOne(optional = false) @JoinColumn(name = "follower_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User follower; + private UserJpaEntity follower; @ManyToOne(optional = false) @JoinColumn(name = "followed_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User followed; + private UserJpaEntity followed; } diff --git a/src/main/java/se/jensen/yuki/springboot/model/Mute.java b/src/main/java/se/jensen/yuki/springboot/model/Mute.java index 89129f3..9af04b8 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/Mute.java +++ b/src/main/java/se/jensen/yuki/springboot/model/Mute.java @@ -4,6 +4,7 @@ import lombok.*; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Entity @Setter @@ -26,10 +27,10 @@ public class Mute extends BaseEntity { @ManyToOne(optional = false) @JoinColumn(name = "muting_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User muting; + private UserJpaEntity muting; @ManyToOne(optional = false) @JoinColumn(name = "muted_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User muted; + private UserJpaEntity muted; } diff --git a/src/main/java/se/jensen/yuki/springboot/model/Post.java b/src/main/java/se/jensen/yuki/springboot/model/Post.java index d798308..f53aa5f 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/Post.java +++ b/src/main/java/se/jensen/yuki/springboot/model/Post.java @@ -4,6 +4,7 @@ import lombok.*; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Entity @Setter @@ -23,7 +24,7 @@ public class Post extends BaseEntity { @ManyToOne(optional = false) @JoinColumn(name = "user_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User user; + private UserJpaEntity user; @ManyToOne @JoinColumn(name = "original_post_id") diff --git a/src/main/java/se/jensen/yuki/springboot/model/PostLike.java b/src/main/java/se/jensen/yuki/springboot/model/PostLike.java index dea04c1..98c60b1 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/PostLike.java +++ b/src/main/java/se/jensen/yuki/springboot/model/PostLike.java @@ -4,6 +4,7 @@ import lombok.*; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; @Entity @Setter @@ -26,7 +27,7 @@ public class PostLike extends BaseEntity { @ManyToOne(optional = false) @JoinColumn(name = "user_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) - private User user; + private UserJpaEntity user; @ManyToOne(optional = false) @JoinColumn(name = "post_id", nullable = false) diff --git a/src/main/java/se/jensen/yuki/springboot/model/RefreshToken.java b/src/main/java/se/jensen/yuki/springboot/model/RefreshToken.java index ac42a2c..d161489 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/RefreshToken.java +++ b/src/main/java/se/jensen/yuki/springboot/model/RefreshToken.java @@ -2,6 +2,7 @@ import jakarta.persistence.*; import lombok.*; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; import java.time.Instant; @@ -19,7 +20,7 @@ public class RefreshToken extends BaseEntity { @ManyToOne @JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false) - private User user; + private UserJpaEntity user; private String token; diff --git a/src/main/java/se/jensen/yuki/springboot/model/SecurityUser.java b/src/main/java/se/jensen/yuki/springboot/model/SecurityUser.java index ff7bc54..d0e6a54 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/SecurityUser.java +++ b/src/main/java/se/jensen/yuki/springboot/model/SecurityUser.java @@ -14,11 +14,11 @@ public class SecurityUser implements UserDetails { private final String role; private final String password; - public SecurityUser(User user) { - this.id = user.getId(); - this.email = user.getEmail(); - this.role = user.getRole(); - this.password = user.getPassword(); + public SecurityUser(Long id, String email, String role, String password) { + this.id = id; + this.email = email; + this.role = role; + this.password = password; } public SecurityUser(Long id, String email, String role) { @@ -55,8 +55,7 @@ public boolean isEnabled() { @Override public Collection getAuthorities() { String r = role; - String role = r == null || r.isBlank() ? "ROLE_USER" : - (r.startsWith("ROLE_") ? r : "ROLE_" + r); + String role = r == null || r.isBlank() ? "USER" : r; return List.of(new SimpleGrantedAuthority(role)); } diff --git a/src/main/java/se/jensen/yuki/springboot/repository/FollowRepository.java b/src/main/java/se/jensen/yuki/springboot/repository/FollowRepository.java index 8ab4312..5e53353 100644 --- a/src/main/java/se/jensen/yuki/springboot/repository/FollowRepository.java +++ b/src/main/java/se/jensen/yuki/springboot/repository/FollowRepository.java @@ -72,7 +72,7 @@ CASE WHEN (SELECT COUNT(f3) FROM Follow f3 WHERE f3.follower.id = :userId AND f3 u.username, u.displayName, u.avatarUrl) - FROM User u + FROM UserJpaEntity u WHERE u.id = :userId """) FollowResponse findByFollowerIdAndFollowedId(@Param("currentUserId") Long currentUserId, @Param("userId") Long userId); diff --git a/src/main/java/se/jensen/yuki/springboot/repository/UserRepository.java b/src/main/java/se/jensen/yuki/springboot/repository/UserRepository.java deleted file mode 100644 index b2ef0dd..0000000 --- a/src/main/java/se/jensen/yuki/springboot/repository/UserRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package se.jensen.yuki.springboot.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import se.jensen.yuki.springboot.model.User; - -import java.util.Optional; - - -public interface UserRepository extends JpaRepository { - boolean existsByUsernameOrEmail(String username, String email); - - Optional findByUsername(String username); - - Optional findByEmail(String email); -} diff --git a/src/main/java/se/jensen/yuki/springboot/service/AuthService.java b/src/main/java/se/jensen/yuki/springboot/service/AuthService.java index 365e89c..825b50e 100644 --- a/src/main/java/se/jensen/yuki/springboot/service/AuthService.java +++ b/src/main/java/se/jensen/yuki/springboot/service/AuthService.java @@ -15,26 +15,27 @@ import se.jensen.yuki.springboot.exception.UserNotFoundException; import se.jensen.yuki.springboot.model.RefreshToken; import se.jensen.yuki.springboot.model.SecurityUser; -import se.jensen.yuki.springboot.model.User; import se.jensen.yuki.springboot.repository.RefreshTokenRepository; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; import java.time.Instant; import java.util.Optional; import java.util.UUID; + @Service @RequiredArgsConstructor public class AuthService { private final JwtService jwtService; private final AuthenticationManager authenticationManager; - private final UserRepository userRepository; + private final UserJpaRepository userJpaRepository; private final PasswordEncoder passwordEncoder; private final RefreshTokenRepository refreshTokenRepository; private final long refreshTokenDurationSeconds = 60L * 60 * 24 * 30; // 30 days - public RefreshToken createRefreshToken(User user) { + public RefreshToken createRefreshToken(UserJpaEntity user) { RefreshToken rt = RefreshToken.builder() .user(user) .token(generateTokenValue()) @@ -58,7 +59,7 @@ public Optional refreshAccessToken(String refreshTokenValue) { return Optional.empty(); } - User user = rt.getUser(); + UserJpaEntity user = rt.getUser(); // rotation: revoke old token and create a new one rt.setRevoked(true); refreshTokenRepository.save(rt); @@ -74,12 +75,12 @@ public void revokeAllForUser(Long userId) { } private String generateTokenValue() { - return UUID.randomUUID().toString() + "-" + UUID.randomUUID(); + return UUID.randomUUID() + "-" + UUID.randomUUID(); } @Transactional public TokenPair registerUser(AuthRegisterRequestDTO dto) { - User user = User.builder() + UserJpaEntity user = UserJpaEntity.builder() .username(dto.username()) .email(dto.email()) .password(passwordEncoder.encode(dto.password())) @@ -88,7 +89,7 @@ public TokenPair registerUser(AuthRegisterRequestDTO dto) { .role("USER") .build(); - User registeredUser = userRepository.save(user); + UserJpaEntity registeredUser = userJpaRepository.save(user); String access = jwtService.generateAccessToken(registeredUser.getId()); RefreshToken rt = createRefreshToken(registeredUser); @@ -101,7 +102,7 @@ public TokenPair login(LoginDTO dto) { ); SecurityUser securityUser = (SecurityUser) authentication.getPrincipal(); - User user = userRepository.findById(securityUser.getId()) + UserJpaEntity user = userJpaRepository.findById(securityUser.getId()) .orElseThrow(() -> new UserNotFoundException("No user found")); String access = jwtService.generateAccessToken(securityUser.getId()); RefreshToken rt = createRefreshToken(user); @@ -127,7 +128,7 @@ public Long getCurrentUserId() { public void checkCurrentPassword(String currentPassword) { Long userId = getCurrentUserId(); - User currentUser = userRepository.findById(userId) + UserJpaEntity currentUser = userJpaRepository.findById(userId) .orElseThrow(() -> new UserNotFoundException("No user found")); if (!passwordEncoder.matches(currentPassword, currentUser.getPassword())) { throw new BadCredentialsException("Wrong password"); diff --git a/src/main/java/se/jensen/yuki/springboot/service/CommentService.java b/src/main/java/se/jensen/yuki/springboot/service/CommentService.java index dd3ca2d..46ccba0 100644 --- a/src/main/java/se/jensen/yuki/springboot/service/CommentService.java +++ b/src/main/java/se/jensen/yuki/springboot/service/CommentService.java @@ -10,14 +10,13 @@ import se.jensen.yuki.springboot.dto.comment.*; import se.jensen.yuki.springboot.exception.CommentNotFoundException; import se.jensen.yuki.springboot.exception.PostNotFoundException; -import se.jensen.yuki.springboot.exception.UserNotFoundException; import se.jensen.yuki.springboot.mapper.CommentMapper; import se.jensen.yuki.springboot.model.Comment; import se.jensen.yuki.springboot.model.Post; -import se.jensen.yuki.springboot.model.User; import se.jensen.yuki.springboot.repository.CommentRepository; import se.jensen.yuki.springboot.repository.PostRepository; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.usecase.UserLoadService; import java.time.Instant; import java.util.List; @@ -26,7 +25,7 @@ @RequiredArgsConstructor public class CommentService { private final CommentRepository commentRepository; - private final UserRepository userRepository; + private final UserLoadService userLoadService; private final PostRepository postRepository; private final CommentMapper commentMapper; @@ -37,7 +36,7 @@ public CommentCreateResponse addComment(Long postId, Long userId, CommentCreateR } else if (userId == null || userId <= 0) { throw new IllegalArgumentException("Invalid user id"); } - User author = userRepository.findById(userId).orElseThrow(() -> new UserNotFoundException("Author doesn't exist with id=" + userId)); + UserJpaEntity author = userLoadService.requireJpaById(userId); Post post = postRepository.findById(postId).orElseThrow(() -> new PostNotFoundException("Post doesn't exist with id=" + postId)); Comment comment; // If there is a parent comment diff --git a/src/main/java/se/jensen/yuki/springboot/service/CustomUserDetailsService.java b/src/main/java/se/jensen/yuki/springboot/service/CustomUserDetailsService.java index a5846ac..33ce2e9 100644 --- a/src/main/java/se/jensen/yuki/springboot/service/CustomUserDetailsService.java +++ b/src/main/java/se/jensen/yuki/springboot/service/CustomUserDetailsService.java @@ -4,19 +4,19 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -import se.jensen.yuki.springboot.exception.UserNotFoundException; import se.jensen.yuki.springboot.model.SecurityUser; -import se.jensen.yuki.springboot.model.User; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.usecase.UserLoadService; + @Service @RequiredArgsConstructor public class CustomUserDetailsService implements UserDetailsService { - private final UserRepository userRepository; + private final UserLoadService userLoadService; @Override public SecurityUser loadUserByUsername(String email) throws UsernameNotFoundException { - User user = userRepository.findByEmail(email).orElseThrow(() -> new UserNotFoundException("User not found")); - return new SecurityUser(user); + UserJpaEntity user = userLoadService.requireJpaByEmail(email); + return new SecurityUser(user.getId(), user.getEmail(), user.getRole(), user.getPassword()); } } diff --git a/src/main/java/se/jensen/yuki/springboot/service/LikeService.java b/src/main/java/se/jensen/yuki/springboot/service/LikeService.java index 65011e5..62d7962 100644 --- a/src/main/java/se/jensen/yuki/springboot/service/LikeService.java +++ b/src/main/java/se/jensen/yuki/springboot/service/LikeService.java @@ -13,15 +13,20 @@ import se.jensen.yuki.springboot.dto.like.PostLikeResponse; import se.jensen.yuki.springboot.model.CommentLike; import se.jensen.yuki.springboot.model.PostLike; -import se.jensen.yuki.springboot.repository.*; +import se.jensen.yuki.springboot.repository.CommentLikeRepository; +import se.jensen.yuki.springboot.repository.CommentRepository; +import se.jensen.yuki.springboot.repository.PostLikeRepository; +import se.jensen.yuki.springboot.repository.PostRepository; +import se.jensen.yuki.springboot.user.usecase.UserLoadService; import java.util.Optional; + @Service @RequiredArgsConstructor public class LikeService { private final PostLikeRepository postLikeRepository; - private final UserRepository userRepository; + private final UserLoadService userLoadService; private final PostRepository postRepository; private final CommentRepository commentRepository; private final CommentLikeRepository commentLikeRepository; @@ -33,7 +38,7 @@ public LikeResponse likePost(Long postId, Long userId) { } else { PostLike postLike = new PostLike(); postLike.setPost(postRepository.findById(postId).orElseThrow(() -> new IllegalArgumentException("Post not found"))); - postLike.setUser(userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("User not found"))); + postLike.setUser(userLoadService.requireJpaById(userId)); postLikeRepository.save(postLike); return new LikeResponse(true, postLikeRepository.countByPostId(postId)); } @@ -66,7 +71,7 @@ public Slice getPostLikesByPostId(Long postId, } else { CommentLike cl = new CommentLike(); cl.setComment(commentRepository.findById(commentId).orElseThrow(() -> new IllegalArgumentException("Comment not found"))); - cl.setUser(userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("User not found"))); + cl.setUser(userLoadService.requireJpaById(userId)); commentLikeRepository.save(cl); return new LikeResponse(true, commentLikeRepository.countByCommentId(commentId)); } diff --git a/src/main/java/se/jensen/yuki/springboot/service/PostService.java b/src/main/java/se/jensen/yuki/springboot/service/PostService.java index d023f9a..c43ab3e 100644 --- a/src/main/java/se/jensen/yuki/springboot/service/PostService.java +++ b/src/main/java/se/jensen/yuki/springboot/service/PostService.java @@ -1,5 +1,6 @@ package se.jensen.yuki.springboot.service; +import lombok.RequiredArgsConstructor; import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,30 +15,25 @@ import se.jensen.yuki.springboot.dto.post.PostCreateResponse; import se.jensen.yuki.springboot.dto.post.PostFeedResponse; import se.jensen.yuki.springboot.exception.PostNotFoundException; -import se.jensen.yuki.springboot.exception.UserNotFoundException; import se.jensen.yuki.springboot.mapper.PostMapper; import se.jensen.yuki.springboot.model.Post; -import se.jensen.yuki.springboot.model.User; import se.jensen.yuki.springboot.repository.PostRepository; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.usecase.UserLoadService; import java.util.List; + @Service +@RequiredArgsConstructor public class PostService { private final Logger log = LoggerFactory.getLogger(PostService.class); private final PostMapper postMapper; private final PostRepository postRepository; - private final UserRepository userRepository; - - public PostService(PostMapper postMapper, PostRepository postRepository, UserRepository userRepository) { - this.postMapper = postMapper; - this.postRepository = postRepository; - this.userRepository = userRepository; - } + private final UserLoadService userLoadService; /** - * MUST MODIFY RETURN TYPE + * TODO: MUST MODIFY RETURN TYPE * * @return */ @@ -61,7 +57,7 @@ public PostFeedResponse getPostById(Long id) { public PostFeedResponse addPost(Long userId, PostCreateRequest requestDTO) { log.info("Starting to add a post"); - User author = userRepository.findById(userId).orElseThrow(() -> new UserNotFoundException("The post's author doesn't exist")); + UserJpaEntity author = userLoadService.requireJpaById(userId); Post post = postMapper.PostCreateToPost(requestDTO, author); postRepository.save(post); log.info("Added a post successfully"); @@ -80,9 +76,7 @@ public PostFeedResponse updatePost(Long postId, PostCreateRequest requestDTO, Lo throw new IllegalArgumentException("Invalid User ID"); } - User author = userRepository - .findById(userId) - .orElseThrow(() -> new UserNotFoundException("The request author doesn't exist")); + UserJpaEntity author = userLoadService.requireJpaById(userId); Post currentPost = postRepository .findById(postId) .orElseThrow(() -> new PostNotFoundException("No post found with id= " + postId)); diff --git a/src/main/java/se/jensen/yuki/springboot/service/UserService.java b/src/main/java/se/jensen/yuki/springboot/service/UserService.java deleted file mode 100644 index 6eef227..0000000 --- a/src/main/java/se/jensen/yuki/springboot/service/UserService.java +++ /dev/null @@ -1,100 +0,0 @@ -package se.jensen.yuki.springboot.service; - -import jakarta.validation.Valid; -import lombok.RequiredArgsConstructor; -import org.jspecify.annotations.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import se.jensen.yuki.springboot.dto.user.UserProfileResponse; -import se.jensen.yuki.springboot.dto.user.UserUpdateEmailRequest; -import se.jensen.yuki.springboot.dto.user.UserUpdatePasswordRequest; -import se.jensen.yuki.springboot.dto.user.UserUpdateProfileRequest; -import se.jensen.yuki.springboot.exception.UserNotFoundException; -import se.jensen.yuki.springboot.mapper.UserMapper; -import se.jensen.yuki.springboot.model.User; -import se.jensen.yuki.springboot.repository.UserRepository; - -import java.util.List; - -@Service -@RequiredArgsConstructor -public class UserService { - private static final Logger log = LoggerFactory.getLogger(UserService.class); - private final UserMapper userMapper; - private final UserRepository userRepository; - private final PasswordEncoder passwordEncoder; - - public List getAllUsers() { - log.info("Starting to get all users"); - return userRepository.findAll() - .stream() - .map(userMapper::toResponse) - .toList(); - } - - public UserProfileResponse getUserById(Long id) { - log.info("Starting to get a user by ID={}", id); - if (id == null || id < 0) { - log.warn("Tried to get a user with invalid ID={}", id); - throw new IllegalArgumentException("Invalid ID"); - } - return userRepository.findById(id) - .map(userMapper::toResponse) - .orElseThrow(() -> new UserNotFoundException("User with id " + id + " not found")); - } - - public UserProfileResponse updateProfile(Long id, UserUpdateProfileRequest request) { - log.info("Starting to update a user with ID={}", id); - if (id == null || id < 0) { - log.warn("Tried to update a user with invalid ID={}", id); - throw new IllegalArgumentException("Invalid ID"); - } - - User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("No user found")); - userMapper.FromUpdateProfileRequest(request, user); - User renewedUser = userRepository.save(user); - log.info("Updated a user successfully with ID={}", id); - return userMapper.toResponse(renewedUser); - } - - public void deleteUser(Long id) { - log.info("Starting to delete a user by ID={}", id); - if (id == null || id < 0) { - log.warn("Tried to delete a user with invalid ID={}", id); - throw new IllegalArgumentException("No users found"); - } - userRepository.deleteById(id); - log.info("Deleted a user successfully by ID={}", id); - } - - - public @Nullable UserProfileResponse updateEmail(Long id, @Valid UserUpdateEmailRequest request) { - log.info("Starting to update a user with ID={}", id); - if (id == null || id < 0) { - log.warn("Tried to update a user with invalid ID={}", id); - throw new IllegalArgumentException("Invalid ID"); - } - - User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("No user found")); - userMapper.FromUpdateEmailRequest(request, user); - User renewedUser = userRepository.save(user); - log.info("Updated a user successfully with ID={}", id); - return userMapper.toResponse(renewedUser); - } - - public @Nullable UserProfileResponse updatePassword(Long id, @Valid UserUpdatePasswordRequest request) { - log.info("Starting to update a user with ID={}", id); - if (id == null || id < 0) { - log.warn("Tried to update a user with invalid ID={}", id); - throw new IllegalArgumentException("Invalid ID"); - } - - User user = userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("No user found")); - user.setPassword(passwordEncoder.encode(request.newPassword())); - User renewedUser = userRepository.save(user); - log.info("Updated a user successfully with ID={}", id); - return userMapper.toResponse(renewedUser); - } -} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/User.java b/src/main/java/se/jensen/yuki/springboot/user/domain/User.java new file mode 100644 index 0000000..60765c5 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/User.java @@ -0,0 +1,129 @@ +package se.jensen.yuki.springboot.user.domain; + +import lombok.Getter; +import se.jensen.yuki.springboot.user.domain.vo.*; + +import java.util.Objects; + +/** + * Represents a user in the system with properties such as username, email, password, role, display name, bio, and avatar URL. + * Provides methods for creating and reconstructing users, as well as updating user information. + */ +@Getter +public class User { + private final UserId id; + private final Username username; + private Email email; + private HashedPassword password; + private final UserRole role; + private DisplayName displayName; + private Bio bio; + private AvatarUrl avatarUrl; + + /** + * Private constructor to enforce the use of factory methods for creating and reconstructing users. + * + * @param id the unique identifier of the user, can be null for new users + * @param username the username of the user, must not be null + * @param email the email address of the user, must not be null + * @param password the hashed password of the user, must not be null + * @param role the role of the user, must not be null + * @param displayName the display name of the user, must not be null + * @param bio the bio of the user, must not be null + * @param avatarUrl the avatar URL of the user, must not be null + */ + private User(UserId id, Username username, Email email, HashedPassword password, UserRole role, DisplayName displayName, Bio bio, AvatarUrl avatarUrl) { + this.id = id; + this.username = username; + this.email = email; + this.password = password; + this.role = role; + this.displayName = displayName; + this.bio = bio; + this.avatarUrl = avatarUrl; + } + + /** + * Factory method to create a new user with the specified properties. The ID is set to null for new users. + * + * @param username the username of the user, must not be null + * @param email the email address of the user, must not be null + * @param password the hashed password of the user, must not be null + * @param role the role of the user, must not be null + * @param displayName the display name of the user, must not be null + * @param bio the bio of the user, must not be null + * @param avatarUrl the avatar URL of the user, must not be null + * @return a new User instance with the specified properties and a null ID + */ + public static User create(Username username, Email email, HashedPassword password, UserRole role, DisplayName displayName, Bio bio, AvatarUrl avatarUrl) { + return new User(null, username, email, password, role, displayName, bio, avatarUrl); + } + + /** + * Factory method to reconstruct an existing user with the specified properties, including the ID. + * + * @param id the unique identifier of the user, must not be null + * @param username the username of the user, must not be null + * @param email the email address of the user, must not be null + * @param password the hashed password of the user, must not be null + * @param role the role of the user, must not be null + * @param displayName the display name of the user, must not be null + * @param bio the bio of the user, must not be null + * @param avatarUrl the avatar URL of the user, must not be null + * @return a User instance with the specified properties and ID + */ + public static User reconstruct(UserId id, Username username, Email email, HashedPassword password, UserRole role, DisplayName displayName, Bio bio, AvatarUrl avatarUrl) { + Objects.requireNonNull(id, "User ID cannot be null for reconstruction"); + return new User(id, username, email, password, role, displayName, bio, avatarUrl); + } + + /** + * Updates the user's email address. The new email must not be null and must be different from the current email. + * + * @param newEmail the new email address to set, must not be null and must be different from the current email + * @throws IllegalArgumentException if the new email is null or the same as the current email + */ + public void changeEmail(Email newEmail) { + Objects.requireNonNull(newEmail, "New email cannot be null"); + + if (this.email.equals(newEmail)) { + throw new IllegalArgumentException("New email must be different from the current email."); + } + + this.email = newEmail; + } + + /** + * Updates the user's password. The new password must not be null and must be different from the current password. + * + * @param newHashedPassword the new hashed password to set, must not be null and must be different from the current password + * @throws IllegalArgumentException if the new password is null or the same as the current password + */ + public void changePassword(HashedPassword newHashedPassword) { + Objects.requireNonNull(newHashedPassword, "New password cannot be null"); + + if (this.password.equals(newHashedPassword)) { + throw new IllegalArgumentException("New password must be different from the current password."); + } + + this.password = newHashedPassword; + } + + /** + * Updates the user's profile information, including display name, bio, and avatar URL. All new values must not be null. + * + * @param newDisplayName the new display name to set, must not be null + * @param newBio the new bio to set, must not be null + * @param newAvatarUrl the new avatar URL to set, must not be null + * @throws IllegalArgumentException if any of the new values are null + */ + public void updateProfile(DisplayName newDisplayName, Bio newBio, AvatarUrl newAvatarUrl) { + Objects.requireNonNull(newDisplayName, "Display name cannot be null"); + Objects.requireNonNull(newBio, "Bio cannot be null"); + Objects.requireNonNull(newAvatarUrl, "Avatar URL cannot be null"); + + this.displayName = newDisplayName; + this.bio = newBio; + this.avatarUrl = newAvatarUrl; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/UserRepository.java b/src/main/java/se/jensen/yuki/springboot/user/domain/UserRepository.java new file mode 100644 index 0000000..28848e1 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/UserRepository.java @@ -0,0 +1,47 @@ +package se.jensen.yuki.springboot.user.domain; + +import se.jensen.yuki.springboot.user.domain.vo.UserId; + +import java.util.List; + +/** + * Repository interface for managing User entities. + */ +public interface UserRepository { + /** + * Finds a User by their unique identifier. + * + * @param id the unique identifier of the User + * @return the User with the specified id, or throw exception if no such User exists + */ + User findById(UserId id); + + /** + * Saves a User to the repository. If the User already exists, it will be updated; otherwise, a new User will be created. + * + * @param user the User to save + */ + void save(User user); + + /** + * Checks if a User exists in the repository by their email address. + * + * @param email the email address to check for existence + * @return true if a User with the specified email exists, false otherwise + */ + boolean existsByEmail(String email); + + /** + * Deletes a User from the repository by their unique identifier. + * + * @param id the unique identifier of the User to delete + */ + void deleteById(UserId id); + + /** + * Retrieves all Users from the repository. + * + * @return a list of all Users + */ + List findAll(); +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/AvatarUrl.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/AvatarUrl.java new file mode 100644 index 0000000..83492e9 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/AvatarUrl.java @@ -0,0 +1,55 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +/** + * Value object representing a user's avatar URL. + */ +public final class AvatarUrl { + private final String value; + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the avatar URL string + * @throws IllegalArgumentException if the value is null or blank + */ + private AvatarUrl(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Avatar URL cannot be null or blank"); + } + + this.value = value; + } + + /** + * Factory method to create an AvatarUrl instance. + * + * @param value the avatar URL string + * @return a new AvatarUrl instance + * @throws IllegalArgumentException if the value is null or blank + */ + public static AvatarUrl of(String value) { + return new AvatarUrl(value); + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof AvatarUrl avatarUrl)) return false; + + return value.equals(avatarUrl.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Bio.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Bio.java new file mode 100644 index 0000000..4a4e533 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Bio.java @@ -0,0 +1,66 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +import java.util.regex.Pattern; + +/** + * Value object representing a user's bio. + *

+ * The bio must be between 0 and 200 characters and can only contain letters, numbers, spaces, and basic punctuation. + */ +public final class Bio { + private final String value; + // Maximum length for a bio + private static final int MAX_LENGTH = 200; + // Regex pattern to allow letters, numbers, spaces, and basic punctuation + private static final Pattern BIO_PATTERN = Pattern.compile("^[\\p{L}\\p{N} ,.?!'\"\\-()]*$"); + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the bio string + * @throws IllegalArgumentException if the bio is null, exceeds the maximum length, or contains invalid characters + */ + private Bio(String value) { + if (value == null || value.length() > MAX_LENGTH) { + throw new IllegalArgumentException("Bio must be between 0 and " + MAX_LENGTH + " characters"); + } + + if (!BIO_PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException("Bio contains invalid characters"); + } + + this.value = value; + } + + /** + * Factory method to create a new Bio instance. + * + * @param value the bio string + * @return a new Bio instance + */ + public static Bio of(String value) { + return new Bio(value); + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Bio bio)) return false; + + return value.equals(bio.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/DisplayName.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/DisplayName.java new file mode 100644 index 0000000..1e5621f --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/DisplayName.java @@ -0,0 +1,72 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +import java.util.regex.Pattern; + +/** + * Value object representing a user's display name. + *

+ * The display name must be between 3 and 30 characters long and can contain letters, numbers, spaces, underscores, hyphens, and periods. + * It must start with a letter or number and cannot contain consecutive special characters. + */ +public final class DisplayName { + private final String value; + // Maximum and minimum length for a display name + private static final int MAX_LENGTH = 30; + private static final int MIN_LENGTH = 3; + // Regex pattern to allow letters, numbers, spaces, underscores, hyphens, and periods, with specific rules for starting character and consecutive special characters + private static final Pattern VALID_CHARACTERS = Pattern.compile("^[\\p{L}\\p{N}][\\p{L}\\p{N} _.-]{2,29}$"); + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the display name string + * @throws IllegalArgumentException if the display name is null, empty, does not meet length requirements, or contains invalid characters + */ + private DisplayName(String value) { + if (value == null || value.trim().isEmpty()) { + throw new IllegalArgumentException("Display name cannot be null or empty"); + } + + if (value.length() < 3 || value.length() > 30) { + throw new IllegalArgumentException("Display name must be between 3 and 30 characters"); + } + + if (!VALID_CHARACTERS.matcher(value).matches()) { + throw new IllegalArgumentException("Display name contains invalid characters"); + } + + this.value = value; + } + + /** + * Factory method to create a new DisplayName instance. + * + * @param value the display name string + * @return a new DisplayName instance + */ + public static DisplayName of(String value) { + return new DisplayName(value); + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof DisplayName that)) return false; + + return value.equals(that.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Email.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Email.java new file mode 100644 index 0000000..f2cf070 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Email.java @@ -0,0 +1,67 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * Value object representing an email address. + *

+ * This class is immutable and validates the email format upon creation. + */ +public final class Email { + // Simple regex pattern for basic email validation + private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"); + // Maximum length for an email address + private static final int MAX_LENGTH = 255; + + private final String value; + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the email string + * @throws IllegalArgumentException if the email is null, blank, exceeds the maximum length, or does not match the email pattern + */ + private Email(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Email cannot be null or blank"); + } + + if (!EMAIL_PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException("Invalid email format: " + value); + } + + if (value.length() > MAX_LENGTH) { + throw new IllegalArgumentException("Email cannot be longer than " + MAX_LENGTH + " characters"); + } + + + this.value = value; + } + + public static Email of(String value) { + return new Email(value); + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Email email)) return false; + + return Objects.equals(value, email.value); + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/HashedPassword.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/HashedPassword.java new file mode 100644 index 0000000..4fab830 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/HashedPassword.java @@ -0,0 +1,69 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +import java.util.regex.Pattern; + +/** + * Value object representing a hashed password, specifically a BCrypt hash. + * This class ensures that the provided password hash is valid and follows the expected format. + */ +public final class HashedPassword { + private final String value; + // BCrypt hashes are always 60 characters long + private final static int LENGTH = 60; + // Regex pattern to allow valid BCrypt hash formats (e.g., $2a$, $2b$, $2y$ followed by cost and salt+hash) + private final static Pattern BCRYPT_PATTERN = Pattern.compile("^\\$2[aby]\\$\\d{2}\\$[./A-Za-z0-9]{53}$"); + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the hashed password string + * @throws IllegalArgumentException if the password is null, blank, does not have the correct length, or does not match the BCrypt pattern + */ + private HashedPassword(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Password cannot be null or blank"); + } + + if (value.length() != LENGTH) { + throw new IllegalArgumentException("Invalid BCrypt hash length"); + } + + if (!BCRYPT_PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException("Invalid password format"); + } + + this.value = value; + } + + /** + * Factory method to create a new HashedPassword instance. + * + * @param value the hashed password string + * @return a new HashedPassword instance + */ + public static HashedPassword of(String value) { + return new HashedPassword(value); + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof HashedPassword password)) return false; + + return value.equals(password.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/UserId.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/UserId.java new file mode 100644 index 0000000..76a1523 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/UserId.java @@ -0,0 +1,54 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +/** + * Value object representing a User ID. + */ +public final class UserId { + private final Long value; + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the Long value of the User ID + * @throws IllegalArgumentException if the value is null or not a positive number + */ + private UserId(Long value) { + if (value == null || value <= 0) { + throw new IllegalArgumentException("User ID must be a positive number."); + } + + this.value = value; + } + + /** + * Factory method to create a new UserId instance. + * + * @param value the Long value of the User ID + * @return a new UserId instance + */ + public static UserId of(Long value) { + return new UserId(value); + } + + public Long getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof UserId userId)) return false; + + return value.equals(userId.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return String.valueOf(value); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/UserRole.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/UserRole.java new file mode 100644 index 0000000..1286814 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/UserRole.java @@ -0,0 +1,65 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +import java.util.Set; + +/** + * Value object representing a user's role in the system. + * Valid roles are "USER" and "ADMIN". + */ +public final class UserRole { + private final String value; + // Define a set of valid roles for easy validation + private static final Set VALID_ROLES = Set.of("USER", "ADMIN"); + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the String value of the user role + * @throws IllegalArgumentException if the value is null, blank, or not a valid role + */ + private UserRole(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Role cannot be null or blank"); + } + + String normalizedValue = value.trim().toUpperCase(); + + if (!VALID_ROLES.contains(normalizedValue)) { + throw new IllegalArgumentException("Invalid role: " + value); + } + + this.value = normalizedValue; + } + + /** + * Factory method to create a new UserRole instance. + * + * @param value the String value of the user role + * @return a new UserRole instance + */ + public static UserRole of(String value) { + return new UserRole(value); + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof UserRole role)) return false; + + return value.equals(role.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Username.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Username.java new file mode 100644 index 0000000..4e710e6 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/Username.java @@ -0,0 +1,64 @@ +package se.jensen.yuki.springboot.user.domain.vo; + +/** + * Value object representing a username in the user domain. + *

+ * This class is immutable and validates the username according to specific rules: + * - The username cannot be null or blank. + * - The username must be between 3 and 20 characters long. + */ +public final class Username { + private final String value; + private static final int MIN_LENGTH = 3; + private static final int MAX_LENGTH = 20; + + /** + * Private constructor to enforce the use of the factory method. + * + * @param value the username string + * @throws IllegalArgumentException if the username is null, blank, or does not meet length requirements + */ + private Username(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Username cannot be null or blank"); + } + + if (value.length() < MIN_LENGTH || value.length() > MAX_LENGTH) { + throw new IllegalArgumentException("Username must be between 3 and 20 characters"); + } + + this.value = value; + } + + /** + * Factory method to create a new Username instance. + * + * @param value the username string + * @return a new Username instance + */ + public static Username of(String value) { + return new Username(value); + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Username username)) return false; + + return value.equals(username.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/AvatarUrlMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/AvatarUrlMapper.java new file mode 100644 index 0000000..33c62f1 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/AvatarUrlMapper.java @@ -0,0 +1,30 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.AvatarUrl; + +/** + * MapStruct mapper for converting between AvatarUrl value object and String. + */ +@Mapper(componentModel = "spring") +public interface AvatarUrlMapper { + /** + * Maps an AvatarUrl value object to its String representation. + * + * @param avatarUrl the AvatarUrl to map + * @return the String representation of the AvatarUrl, or null if the input is null + */ + default String map(AvatarUrl avatarUrl) { + return avatarUrl == null ? null : avatarUrl.getValue(); + } + + /** + * Maps a String to an AvatarUrl value object. + * + * @param value the String to map + * @return the AvatarUrl value object, or null if the input is null + */ + default AvatarUrl map(String value) { + return value == null ? null : AvatarUrl.of(value); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/BioMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/BioMapper.java new file mode 100644 index 0000000..275ff85 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/BioMapper.java @@ -0,0 +1,30 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.Bio; + +/** + * MapStruct mapper for converting between Bio value object and String. + */ +@Mapper(componentModel = "spring") +public interface BioMapper { + /** + * Maps a Bio value object to its String representation. + * + * @param bio the Bio to map + * @return the String representation of the Bio, or null if the input is null + */ + default String map(Bio bio) { + return bio == null ? null : bio.getValue(); + } + + /** + * Maps a String to a Bio value object. + * + * @param value the String to map + * @return the Bio value object, or null if the input is null + */ + default Bio map(String value) { + return value == null ? null : Bio.of(value); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/DisplayNameMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/DisplayNameMapper.java new file mode 100644 index 0000000..60aac6d --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/DisplayNameMapper.java @@ -0,0 +1,30 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.DisplayName; + +/** + * MapStruct mapper for converting between DisplayName value object and String. + */ +@Mapper(componentModel = "spring") +public interface DisplayNameMapper { + /** + * Maps a DisplayName value object to its String representation. + * + * @param displayName the DisplayName to map + * @return the String representation of the DisplayName, or null if the input is null + */ + default String map(DisplayName displayName) { + return displayName == null ? null : displayName.getValue(); + } + + /** + * Maps a String to a DisplayName value object. + * + * @param displayName the String to map + * @return the DisplayName value object, or null if the input is null + */ + default DisplayName map(String displayName) { + return displayName == null ? null : DisplayName.of(displayName); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/EmailMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/EmailMapper.java new file mode 100644 index 0000000..10f207b --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/EmailMapper.java @@ -0,0 +1,30 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.Email; + +/** + * MapStruct mapper for converting between Email value object and String. + */ +@Mapper(componentModel = "spring") +public interface EmailMapper { + /** + * Maps an Email value object to its String representation. + * + * @param email the Email to map + * @return the String representation of the Email, or null if the input is null + */ + default String map(Email email) { + return email == null ? null : email.getValue(); + } + + /** + * Maps a String to an Email value object. + * + * @param value the String to map + * @return the Email value object, or null if the input is null + */ + default Email map(String value) { + return value == null ? null : Email.of(value); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/HashedPasswordMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/HashedPasswordMapper.java new file mode 100644 index 0000000..8703018 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/HashedPasswordMapper.java @@ -0,0 +1,27 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.HashedPassword; + +@Mapper(componentModel = "spring") +public interface HashedPasswordMapper { + /** + * Maps a HashedPassword value object to its String representation. + * + * @param password the HashedPassword to map + * @return the String representation of the HashedPassword, or null if the input is null + */ + default String map(HashedPassword password) { + return password == null ? null : password.getValue(); + } + + /** + * Maps a String to a HashedPassword value object. + * + * @param value the String to map + * @return the HashedPassword value object, or null if the input is null + */ + default HashedPassword map(String value) { + return value == null ? null : HashedPassword.of(value); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UserIdMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UserIdMapper.java new file mode 100644 index 0000000..65e74c4 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UserIdMapper.java @@ -0,0 +1,30 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.UserId; + +/** + * MapStruct mapper for converting between UserId value object and Long. + */ +@Mapper(componentModel = "spring") +public interface UserIdMapper { + /** + * Maps a UserId value object to its Long representation. + * + * @param userId the UserId to map + * @return the Long representation of the UserId, or null if the input is null + */ + default Long map(UserId userId) { + return userId == null ? null : userId.getValue(); + } + + /** + * Maps a Long to a UserId value object. + * + * @param value the Long to map + * @return the UserId value object, or null if the input is null + */ + default UserId map(Long value) { + return value == null ? null : UserId.of(value); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UserRoleMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UserRoleMapper.java new file mode 100644 index 0000000..bdafc0c --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UserRoleMapper.java @@ -0,0 +1,30 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.UserRole; + +/** + * MapStruct mapper for converting between UserRole value object and String. + */ +@Mapper(componentModel = "spring") +public interface UserRoleMapper { + /** + * Maps a UserRole value object to its String representation. + * + * @param role the UserRole to map + * @return the String representation of the UserRole, or null if the input is null + */ + default String map(UserRole role) { + return role == null ? null : role.getValue(); + } + + /** + * Maps a String to a UserRole value object. + * + * @param value the String to map + * @return the UserRole value object, or null if the input is null + */ + default UserRole map(String value) { + return value == null ? null : UserRole.of(value); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UsernameMapper.java b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UsernameMapper.java new file mode 100644 index 0000000..a7aad4c --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/domain/vo/mapper/UsernameMapper.java @@ -0,0 +1,30 @@ +package se.jensen.yuki.springboot.user.domain.vo.mapper; + +import org.mapstruct.Mapper; +import se.jensen.yuki.springboot.user.domain.vo.Username; + +/** + * MapStruct mapper for converting between Username value object and String. + */ +@Mapper(componentModel = "spring") +public interface UsernameMapper { + /** + * Maps a Username value object to its String representation. + * + * @param username the Username to map + * @return the String representation of the Username, or null if the input is null + */ + default String map(Username username) { + return username == null ? null : username.getValue(); + } + + /** + * Maps a String to a Username value object. + * + * @param username the String to map + * @return the Username value object, or null if the input is null + */ + default Username map(String username) { + return username == null ? null : Username.of(username); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/model/User.java b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaEntity.java similarity index 76% rename from src/main/java/se/jensen/yuki/springboot/model/User.java rename to src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaEntity.java index 06cad1b..dcd59ee 100644 --- a/src/main/java/se/jensen/yuki/springboot/model/User.java +++ b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaEntity.java @@ -1,10 +1,15 @@ -package se.jensen.yuki.springboot.model; +package se.jensen.yuki.springboot.user.infrastructure.jpa; import jakarta.persistence.*; import lombok.*; +import se.jensen.yuki.springboot.model.BaseEntity; +import se.jensen.yuki.springboot.model.Post; import java.util.List; +/** + * JPA entity representing a user in the system. + */ @Entity @Getter @Setter @@ -12,7 +17,7 @@ @AllArgsConstructor @Builder @Table(name = "users") -public class User extends BaseEntity { +public class UserJpaEntity extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaMapper.java b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaMapper.java new file mode 100644 index 0000000..a4094dc --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaMapper.java @@ -0,0 +1,34 @@ +package se.jensen.yuki.springboot.user.infrastructure.jpa; + +import org.springframework.stereotype.Component; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.vo.*; + +/** + * Mapper for converting between User domain model and UserJpaEntity. + */ +@Component +public class UserJpaMapper { + public void toEntity(User user, UserJpaEntity entity) { + entity.setUsername(user.getUsername().getValue()); + entity.setEmail(user.getEmail().getValue()); + entity.setPassword(user.getPassword().getValue()); + entity.setRole(user.getRole().getValue()); + entity.setDisplayName(user.getDisplayName().getValue()); + entity.setBio(user.getBio().getValue()); + entity.setAvatarUrl(user.getAvatarUrl().getValue()); + } + + public User toDomain(UserJpaEntity user) { + return User.reconstruct( + UserId.of(user.getId()), + Username.of(user.getUsername()), + Email.of(user.getEmail()), + HashedPassword.of(user.getPassword()), + UserRole.of(user.getRole()), + DisplayName.of(user.getDisplayName()), + Bio.of(user.getBio()), + AvatarUrl.of(user.getAvatarUrl()) + ); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaRepository.java b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaRepository.java new file mode 100644 index 0000000..e7fc11e --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserJpaRepository.java @@ -0,0 +1,26 @@ +package se.jensen.yuki.springboot.user.infrastructure.jpa; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +/** + * Spring Data JPA repository for User entities. + */ +public interface UserJpaRepository extends JpaRepository { + /** + * Finds a user by email. + * + * @param email the email of the user to find + * @return an Optional containing the found user, or empty if no user is found with the given email + */ + Optional findByEmail(String email); + + /** + * Checks if a user exists by email. + * + * @param email the email to check + * @return true if a user exists with the given email, false otherwise + */ + boolean existsByEmail(String email); +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserRepositoryImpl.java b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserRepositoryImpl.java new file mode 100644 index 0000000..6c68bf9 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/infrastructure/jpa/UserRepositoryImpl.java @@ -0,0 +1,89 @@ +package se.jensen.yuki.springboot.user.infrastructure.jpa; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import se.jensen.yuki.springboot.exception.UserNotFoundException; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.UserId; + +import java.util.List; + +/** + * Implementation of UserRepository using JPA. + */ +@Repository +@RequiredArgsConstructor +public class UserRepositoryImpl implements UserRepository { + private final UserJpaRepository userJpaRepository; + private final UserJpaMapper userJpaMapper; + + /** + * Finds a user by ID. + * + * @param id the ID of the user to find + * @return the found user + * @throws UserNotFoundException if no user is found with the given ID + */ + @Override + public User findById(UserId id) { + return userJpaRepository.findById(id.getValue()) + .map(userJpaMapper::toDomain) + .orElseThrow(() -> new UserNotFoundException("No user found with ID=" + id)); + } + + /** + * Saves a user. If the user has an ID, it updates the existing user; otherwise, it creates a new user. + * + * @param user the user to save + * @throws UserNotFoundException if trying to update a user that does not exist + */ + @Override + public void save(User user) { + UserJpaEntity entity; + if (user.getId() == null) { + entity = new UserJpaEntity(); + userJpaMapper.toEntity(user, entity); + } else { + entity = userJpaRepository.findById(user.getId().getValue()) + .orElseThrow(() -> new UserNotFoundException("No user found with ID=" + user.getId())); + userJpaMapper.toEntity(user, entity); + } + + userJpaRepository.save(entity); + } + + /** + * Checks if a user exists by email. + * + * @param email the email to check + * @return true if a user exists with the given email, false otherwise + */ + @Override + public boolean existsByEmail(String email) { + return userJpaRepository.existsByEmail(email); + } + + /** + * Deletes a user by ID. + * + * @param id the ID of the user to delete + */ + @Override + public void deleteById(UserId id) { + userJpaRepository.deleteById(id.getValue()); + } + + /** + * Finds all users. + * + * @return a list of all users + */ + @Override + public List findAll() { + return userJpaRepository.findAll() + .stream() + .map(userJpaMapper::toDomain) + .toList(); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/UserLoadService.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/UserLoadService.java new file mode 100644 index 0000000..73d749e --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/UserLoadService.java @@ -0,0 +1,25 @@ +package se.jensen.yuki.springboot.user.usecase; + +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; + +/** + * Temporary Service for migration + * Will be removed after QueryService is fully adopted. + */ +public interface UserLoadService { + /** + * Loads a user by their unique identifier. + * + * @param id the unique identifier of the user + * @return the UserJpaEntity corresponding to the given id, or throw an exception if not found + */ + UserJpaEntity requireJpaById(Long id); + + /** + * Loads a user by their email address. + * + * @param email the email address of the user + * @return the UserJpaEntity corresponding to the given email, or throw an exception if not found + */ + UserJpaEntity requireJpaByEmail(String email); +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/UserLoadServiceImpl.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/UserLoadServiceImpl.java new file mode 100644 index 0000000..47fe4fa --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/UserLoadServiceImpl.java @@ -0,0 +1,42 @@ +package se.jensen.yuki.springboot.user.usecase; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import se.jensen.yuki.springboot.exception.UserNotFoundException; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; + +/** + * Service for loading user data from the database. + */ +@Service +@RequiredArgsConstructor +public class UserLoadServiceImpl implements UserLoadService { + private final UserJpaRepository userJpaRepository; + + /** + * Loads a user by ID. + * + * @param id the ID of the user to load + * @return the loaded user entity + * @throws UserNotFoundException if no user is found with the given ID + */ + @Override + public UserJpaEntity requireJpaById(Long id) { + return userJpaRepository.findById(id) + .orElseThrow(() -> new UserNotFoundException("User not found by id " + id)); + } + + /** + * Loads a user by email. + * + * @param email the email of the user to load + * @return the loaded user entity + * @throws UserNotFoundException if no user is found with the given email + */ + @Override + public UserJpaEntity requireJpaByEmail(String email) { + return userJpaRepository.findByEmail(email) + .orElseThrow(() -> new UserNotFoundException("User not found by email " + email)); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/command/DeleteUserUseCase.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/DeleteUserUseCase.java new file mode 100644 index 0000000..66d086d --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/DeleteUserUseCase.java @@ -0,0 +1,32 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.UserId; + +/** + * Use case for deleting a user by ID. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class DeleteUserUseCase { + private final UserRepository userRepository; + + /** + * Deletes a user by ID. + * + * @param id the ID of the user to delete + */ + @Transactional + public void execute(Long id) { + log.debug("Starting to delete a user by ID={}", id); + + userRepository.deleteById(UserId.of(id)); + + log.debug("Deleted a user successfully by ID={}", id); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdateEmailUseCase.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdateEmailUseCase.java new file mode 100644 index 0000000..1f2383d --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdateEmailUseCase.java @@ -0,0 +1,48 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.Email; +import se.jensen.yuki.springboot.user.domain.vo.UserId; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateEmailRequest; + +/** + * Use case for updating a user's email. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UpdateEmailUseCase { + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + + /** + * Updates a user's email. + * + * @param id the ID of the user to update + * @param request the request containing the new email and current password + */ + @Transactional + public void execute(Long id, UserUpdateEmailRequest request) { + log.debug("Starting to update a user with ID={}", id); + + User user = userRepository.findById(UserId.of(id)); + + if (!passwordEncoder.matches(request.currentPassword(), user.getPassword().getValue())) { + throw new IllegalArgumentException("Current password is incorrect"); + } + + Email newEmail = Email.of(request.email()); + + user.changeEmail(newEmail); + + userRepository.save(user); + + log.debug("Updated a user successfully with ID={}", id); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdatePasswordUseCase.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdatePasswordUseCase.java new file mode 100644 index 0000000..eb29bb7 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdatePasswordUseCase.java @@ -0,0 +1,53 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.HashedPassword; +import se.jensen.yuki.springboot.user.domain.vo.UserId; +import se.jensen.yuki.springboot.user.web.dto.UserUpdatePasswordRequest; + +/** + * Use case for updating a user's password. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class UpdatePasswordUseCase { + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + + /** + * Updates a user's password. + * + * @param id the ID of the user to update + * @param request the request containing the current and new passwords + */ + @Transactional + public void execute(Long id, @Valid UserUpdatePasswordRequest request) { + log.debug("Starting to update a user with ID={}", id); + + User user = userRepository.findById(UserId.of(id)); + + if (!passwordEncoder.matches(request.currentPassword(), user.getPassword().getValue())) { + throw new IllegalArgumentException("Current password is incorrect"); + } + + if (passwordEncoder.matches(request.newPassword(), user.getPassword().getValue())) { + throw new IllegalArgumentException("New password must be different from the current password"); + } + + HashedPassword newHashedPassword = HashedPassword.of(passwordEncoder.encode(request.newPassword())); + + user.changePassword(newHashedPassword); + + userRepository.save(user); + + log.debug("Updated a user successfully with ID={}", id); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdateUserProfileUseCase.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdateUserProfileUseCase.java new file mode 100644 index 0000000..fab04c1 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/command/UpdateUserProfileUseCase.java @@ -0,0 +1,51 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.AvatarUrl; +import se.jensen.yuki.springboot.user.domain.vo.Bio; +import se.jensen.yuki.springboot.user.domain.vo.DisplayName; +import se.jensen.yuki.springboot.user.domain.vo.UserId; +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateProfileRequest; +import se.jensen.yuki.springboot.user.web.mapper.UserResponseMapper; + +/** + * Use case for updating a user's profile information. + */ +@Service +@Slf4j +@RequiredArgsConstructor +public class UpdateUserProfileUseCase { + private final UserRepository userRepository; + private final UserResponseMapper userMapper; + + /** + * Updates a user's profile information. + * + * @param id the ID of the user to update + * @param request the request containing the new profile information + * @return the updated user profile response + */ + @Transactional + public UserProfileResponse execute(Long id, UserUpdateProfileRequest request) { + log.debug("Starting to update a user with ID={}", id); + + User user = userRepository.findById(UserId.of(id)); + + DisplayName displayName = DisplayName.of(request.displayName()); + Bio bio = Bio.of(request.bio()); + AvatarUrl avatarUrl = AvatarUrl.of(request.avatarUrl()); + + user.updateProfile(displayName, bio, avatarUrl); + + userRepository.save(user); + + log.debug("Updated a user successfully with ID={}", id); + return userMapper.toResponse(user); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/query/UserQueryService.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/query/UserQueryService.java new file mode 100644 index 0000000..7a60aea --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/query/UserQueryService.java @@ -0,0 +1,13 @@ +package se.jensen.yuki.springboot.user.usecase.query; + +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; + +import java.util.List; + + +public interface UserQueryService { + + List findAll(); + + UserProfileResponse findById(Long id); +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/usecase/query/UserQueryServiceImpl.java b/src/main/java/se/jensen/yuki/springboot/user/usecase/query/UserQueryServiceImpl.java new file mode 100644 index 0000000..12e535b --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/usecase/query/UserQueryServiceImpl.java @@ -0,0 +1,32 @@ +package se.jensen.yuki.springboot.user.usecase.query; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.UserId; +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; +import se.jensen.yuki.springboot.user.web.mapper.UserResponseMapper; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class UserQueryServiceImpl implements UserQueryService { + private final UserRepository userRepository; + private final UserResponseMapper userMapper; + + @Override + public List findAll() { + return userRepository.findAll() + .stream() + .map(userMapper::toResponse) + .toList(); + } + + @Override + public UserProfileResponse findById(Long id) { + UserId userId = UserId.of(id); + return userMapper.toResponse(userRepository.findById(userId)); + } + +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/web/UserCommandController.java b/src/main/java/se/jensen/yuki/springboot/user/web/UserCommandController.java new file mode 100644 index 0000000..b3d814b --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/web/UserCommandController.java @@ -0,0 +1,99 @@ +package se.jensen.yuki.springboot.user.web; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import se.jensen.yuki.springboot.service.AuthService; +import se.jensen.yuki.springboot.user.usecase.command.DeleteUserUseCase; +import se.jensen.yuki.springboot.user.usecase.command.UpdateEmailUseCase; +import se.jensen.yuki.springboot.user.usecase.command.UpdatePasswordUseCase; +import se.jensen.yuki.springboot.user.usecase.command.UpdateUserProfileUseCase; +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateEmailRequest; +import se.jensen.yuki.springboot.user.web.dto.UserUpdatePasswordRequest; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateProfileRequest; + +/** + * REST controller for handling user-related commands such as updating profile, email, password, and deleting the user account. + */ +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("/users") +public class UserCommandController { + private final AuthService authService; + private final UpdateUserProfileUseCase updateUserProfileUseCase; + private final UpdatePasswordUseCase updatePasswordUseCase; + private final UpdateEmailUseCase updateEmailUseCase; + private final DeleteUserUseCase deleteUserUseCase; + + + /** + * Updates the profile of the currently authenticated user. + * + * @param request the request containing the new profile information + * @return a response entity containing the updated user profile + */ + @PutMapping("/me/profile") + public ResponseEntity updateProfile(@Valid @RequestBody UserUpdateProfileRequest request) { + log.debug("Starting to update my profile"); + + UserProfileResponse response = updateUserProfileUseCase.execute(authService.getCurrentUserId(), request); + + return ResponseEntity.ok(response); + } + + /** + * Updates the email of the currently authenticated user. + * + * @param request the request containing the new email information + * @return a response entity with no content + */ + @PutMapping("/me/email") + public ResponseEntity updateEmail(@Valid @RequestBody UserUpdateEmailRequest request) { + log.debug("Starting to update my Account"); + + updateEmailUseCase.execute(authService.getCurrentUserId(), request); + + return ResponseEntity + .noContent() + .build(); + } + + /** + * Updates the password of the currently authenticated user. + * + * @param request the request containing the current and new password information + * @return a response entity with no content + */ + @PutMapping("/me/password") + public ResponseEntity updatePassword(@Valid @RequestBody UserUpdatePasswordRequest request) { + log.debug("Starting to update my Account"); + + updatePasswordUseCase.execute(authService.getCurrentUserId(), request); + + return ResponseEntity.noContent().build(); + } + + /** + * Deletes the account of the currently authenticated user. + * + * @param id the ID of the user to delete + * @return a response entity with no content + */ + @DeleteMapping("/{id}") + public ResponseEntity deleteUser(@PathVariable Long id) { + log.debug("Starting to delete a user by id={}", id); + + if (!id.equals(authService.getCurrentUserId())) { + throw new IllegalArgumentException("Wrong request id=" + id); + } + + deleteUserUseCase.execute(id); + + log.debug("Deleted a user successfully with id={}", id); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/web/UserQueryController.java b/src/main/java/se/jensen/yuki/springboot/user/web/UserQueryController.java new file mode 100644 index 0000000..033e638 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/web/UserQueryController.java @@ -0,0 +1,69 @@ +package se.jensen.yuki.springboot.user.web; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import se.jensen.yuki.springboot.service.AuthService; +import se.jensen.yuki.springboot.user.usecase.query.UserQueryService; +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; + +import java.util.List; + +/** + * REST controller for handling user-related queries. + */ +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("/users") +public class UserQueryController { + private final UserQueryService userQueryService; + private final AuthService authService; + + /** + * Retrieves a list of all users in the system. This endpoint is intended for admin use. + * + * @return a ResponseEntity containing a list of UserProfileResponse objects representing all users + */ + @GetMapping("/admin/users") + public ResponseEntity> getAllUsers() { + log.debug("Starting to get all users"); + + List response = userQueryService.findAll(); + + return ResponseEntity.ok(response); + } + + /** + * Retrieves the profile of the currently authenticated user. + * + * @return a ResponseEntity containing a UserProfileResponse object representing the current user's profile + */ + @GetMapping("/me") + public ResponseEntity getMyProfile() { + log.debug("Starting to get my profile"); + + UserProfileResponse response = userQueryService.findById(authService.getCurrentUserId()); + + return ResponseEntity.ok(response); + } + + /** + * Retrieves a user by their ID. + * + * @param id the ID of the user to retrieve + * @return a ResponseEntity containing a UserProfileResponse object representing the user with the specified ID + */ + @GetMapping("/{id}") + public ResponseEntity getUserById(@PathVariable Long id) { + log.debug("Starting to get a user by ID={}", id); + + UserProfileResponse response = userQueryService.findById(id); + + return ResponseEntity.ok(response); + } +} diff --git a/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserProfileResponse.java b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserProfileResponse.java new file mode 100644 index 0000000..a645a63 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserProfileResponse.java @@ -0,0 +1,16 @@ +package se.jensen.yuki.springboot.user.web.dto; + +/** + * DTO for user profile response. + * + * @param id the user's ID + * @param username the user's username + * @param email the user's email + * @param role the user's role + * @param displayName the user's display name + * @param bio the user's bio + * @param avatarUrl the URL of the user's avatar + */ +public record UserProfileResponse(Long id, String username, String email, String role, String displayName, String bio, + String avatarUrl) { +} diff --git a/src/main/java/se/jensen/yuki/springboot/dto/user/UserRequestDTO.java b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserRequestDTO.java similarity index 77% rename from src/main/java/se/jensen/yuki/springboot/dto/user/UserRequestDTO.java rename to src/main/java/se/jensen/yuki/springboot/user/web/dto/UserRequestDTO.java index 95e7e52..12c20fc 100644 --- a/src/main/java/se/jensen/yuki/springboot/dto/user/UserRequestDTO.java +++ b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserRequestDTO.java @@ -1,9 +1,13 @@ -package se.jensen.yuki.springboot.dto.user; +package se.jensen.yuki.springboot.user.web.dto; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; +/** + * UserRequestDTO is a record that represents the data transfer object for user requests. + * It includes validation annotations to ensure that the input data meets specific criteria. + */ public record UserRequestDTO( @NotBlank(message = "It can't be empty") @Size(min = 3, max = 50, message = "It must be between 3 - 50 letters") @@ -29,12 +33,12 @@ public record UserRequestDTO( @NotBlank(message = "It can't be empty") @Size(min = 3, max = 30, message = "It must be between 3 - 30 letters") - @Pattern(regexp = "^[A-Za-z0-9 ]*$", message = "Only letters, numbers and space allowed") + @Pattern(regexp = "^[\\p{L}\\p{N} _.-]{2,29}$", message = "Display name must be 3–30 characters and contain only letters, numbers, spaces, \".\", \"_\" or \"-\".") String displayName, @NotBlank(message = "It can't be empty") @Size(min = 1, max = 200, message = "It must be between 1 - 200 letters") - @Pattern(regexp = "^[A-Za-z0-9 ,.]*$", message = "Only letters, numbers, space, \",\" and \".\" allowed") + @Pattern(regexp = "^[\\p{L}\\p{N} ,.?!'\"\\-()]*$", message = "Allowed characters: letters, numbers, spaces, and .,?!'\"-()") String bio, @Size(max = 30, message = "It must be max 30 letters") diff --git a/src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdateEmailRequest.java b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdateEmailRequest.java similarity index 65% rename from src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdateEmailRequest.java rename to src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdateEmailRequest.java index ef5d385..e00efcc 100644 --- a/src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdateEmailRequest.java +++ b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdateEmailRequest.java @@ -1,9 +1,15 @@ -package se.jensen.yuki.springboot.dto.user; +package se.jensen.yuki.springboot.user.web.dto; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; +/** + * DTO for updating a user's email address. + * + * @param email the new email address to set for the user + * @param currentPassword the current password of the user, required for authentication + */ public record UserUpdateEmailRequest( @NotBlank(message = "It can't be empty") @Size(min = 3, max = 60, message = "It must be between 3 - 60 letters") diff --git a/src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdatePasswordRequest.java b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdatePasswordRequest.java similarity index 70% rename from src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdatePasswordRequest.java rename to src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdatePasswordRequest.java index 02404c5..224f5f6 100644 --- a/src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdatePasswordRequest.java +++ b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdatePasswordRequest.java @@ -1,9 +1,15 @@ -package se.jensen.yuki.springboot.dto.user; +package se.jensen.yuki.springboot.user.web.dto; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; +/** + * DTO for updating a user's password. + * + * @param newPassword the new password to set for the user + * @param currentPassword the current password of the user, used for verification + */ public record UserUpdatePasswordRequest( @NotBlank(message = "It can't be empty") @Size(min = 8, max = 40, message = "It must be between 8 - 40 letters") diff --git a/src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdateProfileRequest.java b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdateProfileRequest.java similarity index 59% rename from src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdateProfileRequest.java rename to src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdateProfileRequest.java index 495b1c2..ea85e83 100644 --- a/src/main/java/se/jensen/yuki/springboot/dto/user/UserUpdateProfileRequest.java +++ b/src/main/java/se/jensen/yuki/springboot/user/web/dto/UserUpdateProfileRequest.java @@ -1,17 +1,20 @@ -package se.jensen.yuki.springboot.dto.user; +package se.jensen.yuki.springboot.user.web.dto; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; +/** + * DTO for updating a user's profile information, including display name, bio, and avatar URL. + */ public record UserUpdateProfileRequest( @Size(min = 3, max = 30, message = "It must be between 3 - 30 letters") - @Pattern(regexp = "^[A-Za-z0-9 ]*$", message = "Only letters, numbers and space allowed") + @Pattern(regexp = "^[\\p{L}\\p{N} _.-]{2,29}$", message = "Display name must be 3–30 characters and contain only letters, numbers, spaces, \".\", \"_\" or \"-\".") String displayName, @NotBlank(message = "It can't be empty") @Size(min = 1, max = 200, message = "It must be between 1 - 200 letters") - @Pattern(regexp = "^[A-Za-z0-9 ,.]*$", message = "Only letters, numbers, space, \",\" and \".\" allowed") + @Pattern(regexp = "^[\\p{L}\\p{N} ,.?!'\"\\-()]*$", message = "Allowed characters: letters, numbers, spaces, and .,?!'\"-()") String bio, @Size(max = 30, message = "It must be max 30 letters") diff --git a/src/main/java/se/jensen/yuki/springboot/user/web/mapper/UserResponseMapper.java b/src/main/java/se/jensen/yuki/springboot/user/web/mapper/UserResponseMapper.java new file mode 100644 index 0000000..58f8ed0 --- /dev/null +++ b/src/main/java/se/jensen/yuki/springboot/user/web/mapper/UserResponseMapper.java @@ -0,0 +1,23 @@ +package se.jensen.yuki.springboot.user.web.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.NullValuePropertyMappingStrategy; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.vo.mapper.*; +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; + +/** + * MapStruct mapper for converting User domain model to UserProfileResponse DTO. + */ +@Mapper(componentModel = "spring", + uses = {EmailMapper.class, UsernameMapper.class, HashedPasswordMapper.class, UserRoleMapper.class, DisplayNameMapper.class, BioMapper.class, AvatarUrlMapper.class, UserIdMapper.class}, + nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) +public interface UserResponseMapper { + /** + * Maps a User domain model to a UserProfileResponse DTO. + * + * @param user the User to map + * @return the UserProfileResponse DTO, or null if the input is null + */ + UserProfileResponse toResponse(User user); +} diff --git a/src/main/java/se/jensen/yuki/springboot/util/CurrentUserProvider.java b/src/main/java/se/jensen/yuki/springboot/util/CurrentUserProvider.java index 077f5b4..e3d7802 100644 --- a/src/main/java/se/jensen/yuki/springboot/util/CurrentUserProvider.java +++ b/src/main/java/se/jensen/yuki/springboot/util/CurrentUserProvider.java @@ -4,18 +4,17 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.usecase.UserLoadService; + @Component @RequiredArgsConstructor public class CurrentUserProvider { - private final UserRepository userRepository; + private final UserLoadService userLoadService; public Long getCurrentUserId() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String email = authentication.getName(); - return userRepository.findByEmail(email) - .orElseThrow(() -> new RuntimeException("User not found")) - .getId(); + return userLoadService.requireJpaByEmail(email).getId(); } } diff --git a/src/test/java/se/jensen/yuki/springboot/service/AuthServiceIntegrationTest.java b/src/test/java/se/jensen/yuki/springboot/service/AuthServiceIntegrationTest.java index 8bb7a4f..51d3992 100644 --- a/src/test/java/se/jensen/yuki/springboot/service/AuthServiceIntegrationTest.java +++ b/src/test/java/se/jensen/yuki/springboot/service/AuthServiceIntegrationTest.java @@ -10,9 +10,9 @@ import se.jensen.yuki.springboot.dto.auth.AuthRegisterRequestDTO; import se.jensen.yuki.springboot.dto.auth.LoginDTO; import se.jensen.yuki.springboot.model.RefreshToken; -import se.jensen.yuki.springboot.model.User; import se.jensen.yuki.springboot.repository.RefreshTokenRepository; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; import java.util.Optional; @@ -27,7 +27,7 @@ public class AuthServiceIntegrationTest { private AuthService authService; @Autowired - private UserRepository userRepository; + private UserJpaRepository userJpaRepository; @Autowired private RefreshTokenRepository refreshTokenRepository; @@ -38,7 +38,7 @@ public class AuthServiceIntegrationTest { @BeforeEach void clean() { refreshTokenRepository.deleteAll(); - userRepository.deleteAll(); + userJpaRepository.deleteAll(); } // ---------- register ---------- @@ -62,7 +62,7 @@ void registerUser_success() { assertThat(tokenPair.refreshToken()).isNotBlank(); // user保存されてる - User user = userRepository + UserJpaEntity user = userJpaRepository .findByEmail("test@test.com") .orElseThrow(); @@ -85,7 +85,7 @@ void registerUser_success() { void login_success() { // user準備 - User user = User.builder() + UserJpaEntity user = UserJpaEntity.builder() .username("loginuser") .email("login@test.com") .password(passwordEncoder.encode("secret")) @@ -94,7 +94,7 @@ void login_success() { .bio("bio") .build(); - userRepository.save(user); + userJpaRepository.save(user); LoginDTO dto = new LoginDTO("login@test.com", "secret"); @@ -113,7 +113,7 @@ void login_success() { void refreshToken_rotate_success() { // user作成 - User user = User.builder() + UserJpaEntity user = UserJpaEntity.builder() .username("refreshuser") .email("refresh@test.com") .password(passwordEncoder.encode("pw")) @@ -122,7 +122,7 @@ void refreshToken_rotate_success() { .bio("bio") .build(); - userRepository.save(user); + userJpaRepository.save(user); // 最初のtoken RefreshToken rt = diff --git a/src/test/java/se/jensen/yuki/springboot/service/BlockServiceIntegrationTest.java b/src/test/java/se/jensen/yuki/springboot/service/BlockServiceIntegrationTest.java index c602307..ba494a2 100644 --- a/src/test/java/se/jensen/yuki/springboot/service/BlockServiceIntegrationTest.java +++ b/src/test/java/se/jensen/yuki/springboot/service/BlockServiceIntegrationTest.java @@ -10,9 +10,9 @@ import org.springframework.transaction.annotation.Transactional; import se.jensen.yuki.springboot.dto.block.BlockBlockingResponse; import se.jensen.yuki.springboot.dto.block.BlockResponse; -import se.jensen.yuki.springboot.model.User; import se.jensen.yuki.springboot.repository.BlockRepository; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; import static org.assertj.core.api.Assertions.assertThat; @@ -25,19 +25,19 @@ class BlockServiceIntegrationTest { private BlockService blockService; @Autowired - private UserRepository userRepository; + private UserJpaRepository userJpaRepository; @Autowired private BlockRepository blockRepository; - private User userA; - private User userB; + private UserJpaEntity userA; + private UserJpaEntity userB; @BeforeEach void setUp() { - userA = userRepository.save( - User.builder() + userA = userJpaRepository.save( + UserJpaEntity.builder() .username("userA") .email("a@test.com") .password("pass") @@ -47,8 +47,8 @@ void setUp() { .build() ); - userB = userRepository.save( - User.builder() + userB = userJpaRepository.save( + UserJpaEntity.builder() .username("userB") .email("b@test.com") .password("pass") @@ -151,7 +151,7 @@ void getBlockings_shouldReturnBlockedUsers() { assertThat(slice.getContent()).hasSize(1); BlockBlockingResponse res = - slice.getContent().get(0); + slice.getContent().getFirst(); assertThat(res.blockedUserId()).isEqualTo(userB.getId()); } diff --git a/src/test/java/se/jensen/yuki/springboot/service/FollowServiceIntegrationTest.java b/src/test/java/se/jensen/yuki/springboot/service/FollowServiceIntegrationTest.java index 152f8e6..a9ac4f9 100644 --- a/src/test/java/se/jensen/yuki/springboot/service/FollowServiceIntegrationTest.java +++ b/src/test/java/se/jensen/yuki/springboot/service/FollowServiceIntegrationTest.java @@ -7,9 +7,9 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.transaction.annotation.Transactional; import se.jensen.yuki.springboot.dto.follow.FollowResponse; -import se.jensen.yuki.springboot.model.User; import se.jensen.yuki.springboot.repository.FollowRepository; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; import static org.assertj.core.api.Assertions.assertThat; @@ -21,24 +21,24 @@ public class FollowServiceIntegrationTest { private FollowService followService; @Autowired - private UserRepository userRepository; + private UserJpaRepository userJpaRepository; @Autowired private FollowRepository followRepository; - private User userA; - private User userB; + private UserJpaEntity userA; + private UserJpaEntity userB; @BeforeEach void setup() { followRepository.deleteAll(); - userRepository.deleteAll(); + userJpaRepository.deleteAll(); - userA = userRepository.save( - User.builder() + userA = userJpaRepository.save( + UserJpaEntity.builder() .username("userA") .email("a@test.com") .password("pw") @@ -48,8 +48,8 @@ void setup() { .build() ); - userB = userRepository.save( - User.builder() + userB = userJpaRepository.save( + UserJpaEntity.builder() .username("userB") .email("b@test.com") .password("pw") diff --git a/src/test/java/se/jensen/yuki/springboot/service/LikeServiceIntegrationTest.java b/src/test/java/se/jensen/yuki/springboot/service/LikeServiceIntegrationTest.java index 852fa99..f1fa4f9 100644 --- a/src/test/java/se/jensen/yuki/springboot/service/LikeServiceIntegrationTest.java +++ b/src/test/java/se/jensen/yuki/springboot/service/LikeServiceIntegrationTest.java @@ -13,8 +13,12 @@ import se.jensen.yuki.springboot.dto.like.PostLikeResponse; import se.jensen.yuki.springboot.model.Comment; import se.jensen.yuki.springboot.model.Post; -import se.jensen.yuki.springboot.model.User; -import se.jensen.yuki.springboot.repository.*; +import se.jensen.yuki.springboot.repository.CommentLikeRepository; +import se.jensen.yuki.springboot.repository.CommentRepository; +import se.jensen.yuki.springboot.repository.PostLikeRepository; +import se.jensen.yuki.springboot.repository.PostRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; import static org.assertj.core.api.Assertions.assertThat; @@ -27,7 +31,7 @@ class LikeServiceIntegrationTest { private LikeService likeService; @Autowired - private UserRepository userRepository; + private UserJpaRepository userJpaRepository; @Autowired private PostRepository postRepository; @@ -41,15 +45,15 @@ class LikeServiceIntegrationTest { @Autowired private CommentLikeRepository commentLikeRepository; - private User user; + private UserJpaEntity user; private Post post; private Comment comment; @BeforeEach void setUp() { - user = userRepository.save( - User.builder() + user = userJpaRepository.save( + UserJpaEntity.builder() .username("user1") .email("user1@test.com") .password("pass") @@ -211,7 +215,7 @@ void getCommentLikes_shouldReturnList() { assertThat(slice.getContent()).hasSize(1); CommentLikeResponse res = - slice.getContent().get(0); + slice.getContent().getFirst(); assertThat(res.userId()).isEqualTo(user.getId()); } diff --git a/src/test/java/se/jensen/yuki/springboot/service/MuteServiceIntegrationTest.java b/src/test/java/se/jensen/yuki/springboot/service/MuteServiceIntegrationTest.java index 9ec96a4..6b29037 100644 --- a/src/test/java/se/jensen/yuki/springboot/service/MuteServiceIntegrationTest.java +++ b/src/test/java/se/jensen/yuki/springboot/service/MuteServiceIntegrationTest.java @@ -10,8 +10,8 @@ import org.springframework.transaction.annotation.Transactional; import se.jensen.yuki.springboot.dto.mute.MuteMutingResponse; import se.jensen.yuki.springboot.dto.mute.MuteResponse; -import se.jensen.yuki.springboot.model.User; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; import static org.assertj.core.api.Assertions.assertThat; @@ -25,18 +25,18 @@ class MuteServiceIntegrationTest { private MuteService muteService; @Autowired - private UserRepository userRepository; + private UserJpaRepository userJpaRepository; - private User user1; - private User user2; + private UserJpaEntity user1; + private UserJpaEntity user2; @BeforeEach void setUp() { - user1 = userRepository.save( - User.builder() + user1 = userJpaRepository.save( + UserJpaEntity.builder() .username("user1") .email("user1@test.com") .password("pass") @@ -46,8 +46,8 @@ void setUp() { .build() ); - user2 = userRepository.save( - User.builder() + user2 = userJpaRepository.save( + UserJpaEntity.builder() .username("user2") .email("user2@test.com") .password("pass") @@ -123,7 +123,7 @@ void getMutings_shouldReturnList() { assertThat(slice.getContent()).hasSize(1); MuteMutingResponse res = - slice.getContent().get(0); + slice.getContent().getFirst(); assertThat(res.mutedUserId()).isEqualTo(user2.getId()); } diff --git a/src/test/java/se/jensen/yuki/springboot/service/PostServiceIntegrationTest.java b/src/test/java/se/jensen/yuki/springboot/service/PostServiceIntegrationTest.java index 8032796..738a139 100644 --- a/src/test/java/se/jensen/yuki/springboot/service/PostServiceIntegrationTest.java +++ b/src/test/java/se/jensen/yuki/springboot/service/PostServiceIntegrationTest.java @@ -11,8 +11,8 @@ import se.jensen.yuki.springboot.dto.post.PostFeedResponse; import se.jensen.yuki.springboot.exception.PostNotFoundException; import se.jensen.yuki.springboot.exception.UserNotFoundException; -import se.jensen.yuki.springboot.model.User; -import se.jensen.yuki.springboot.repository.UserRepository; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaEntity; +import se.jensen.yuki.springboot.user.infrastructure.jpa.UserJpaRepository; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -26,14 +26,14 @@ class PostServiceIntegrationTest { private PostService postService; @Autowired - private UserRepository userRepository; + private UserJpaRepository userJpaRepository; - private User testUser; + private UserJpaEntity testUser; @BeforeEach void setup() { - testUser = User.builder() + testUser = UserJpaEntity.builder() .username("testuser") .email("test@test.com") .password("password") @@ -43,7 +43,7 @@ void setup() { .avatarUrl(null) .build(); - testUser = userRepository.save(testUser); + testUser = userJpaRepository.save(testUser); } /** diff --git a/src/test/java/se/jensen/yuki/springboot/service/UserServiceIntegrationTest.java b/src/test/java/se/jensen/yuki/springboot/service/UserServiceIntegrationTest.java deleted file mode 100644 index e30537e..0000000 --- a/src/test/java/se/jensen/yuki/springboot/service/UserServiceIntegrationTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package se.jensen.yuki.springboot.service; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.transaction.annotation.Transactional; -import se.jensen.yuki.springboot.dto.user.UserProfileResponse; -import se.jensen.yuki.springboot.dto.user.UserUpdatePasswordRequest; -import se.jensen.yuki.springboot.dto.user.UserUpdateProfileRequest; -import se.jensen.yuki.springboot.exception.UserNotFoundException; -import se.jensen.yuki.springboot.model.User; -import se.jensen.yuki.springboot.repository.UserRepository; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - - -@SpringBootTest -@ActiveProfiles("test") -@Transactional -class UserServiceIntegrationTest { - - @Autowired - private UserService userService; - - @Autowired - private UserRepository userRepository; - - @Autowired - private PasswordEncoder passwordEncoder; - - private User testUser; - - @BeforeEach - void setUp() { - testUser = User.builder() - .username("testuser") - .email("test@test.com") - .password(passwordEncoder.encode("password")) - .role("USER") - .displayName("Test User") - .bio("test bio") - .avatarUrl("avatar.png") - .build(); - - testUser = userRepository.save(testUser); - } - - // ---------------------------- - // getUserById success - // ---------------------------- - @Test - void getUserById_success() { - UserProfileResponse response = - userService.getUserById(testUser.getId()); - - assertThat(response).isNotNull(); - assertThat(response.username()).isEqualTo("testuser"); - assertThat(response.email()).isEqualTo("test@test.com"); - } - - // ---------------------------- - // getUserById not found - // ---------------------------- - @Test - void getUserById_notFound() { - Long invalidId = 9999L; - - assertThatThrownBy(() -> - userService.getUserById(invalidId)) - .isInstanceOf(UserNotFoundException.class); - } - - // ---------------------------- - // updateProfile success - // ---------------------------- - @Test - void updateProfile_success() { - UserUpdateProfileRequest request = - new UserUpdateProfileRequest( - "New Name", - "New Bio", - "new-avatar.png" - ); - - UserProfileResponse response = - userService.updateProfile(testUser.getId(), request); - - assertThat(response.displayName()).isEqualTo("New Name"); - assertThat(response.bio()).isEqualTo("New Bio"); - assertThat(response.avatarUrl()).isEqualTo("new-avatar.png"); - - // DB確認 - User updated = - userRepository.findById(testUser.getId()).get(); - - assertThat(updated.getDisplayName()).isEqualTo("New Name"); - } - - // ---------------------------- - // updatePassword success - // ---------------------------- - @Test - void updatePassword_success() { - UserUpdatePasswordRequest request = - new UserUpdatePasswordRequest("newPassword123", "currentPassword123"); - - userService.updatePassword(testUser.getId(), request); - - User updated = - userRepository.findById(testUser.getId()).get(); - - assertThat( - passwordEncoder.matches( - "newPassword123", - updated.getPassword() - ) - ).isTrue(); - } - - // ---------------------------- - // deleteUser success - // ---------------------------- - @Test - void deleteUser_success() { - userService.deleteUser(testUser.getId()); - - Optional deleted = - userRepository.findById(testUser.getId()); - - assertThat(deleted).isEmpty(); - } -} - diff --git a/src/test/java/se/jensen/yuki/springboot/testutil/TestPasswords.java b/src/test/java/se/jensen/yuki/springboot/testutil/TestPasswords.java new file mode 100644 index 0000000..1b4d30b --- /dev/null +++ b/src/test/java/se/jensen/yuki/springboot/testutil/TestPasswords.java @@ -0,0 +1,12 @@ +package se.jensen.yuki.springboot.testutil; + +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +public final class TestPasswords { + private static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + + public static String hashed(String rawPassword) { + return passwordEncoder.encode(rawPassword); + } +} diff --git a/src/test/java/se/jensen/yuki/springboot/testutil/TestUsers.java b/src/test/java/se/jensen/yuki/springboot/testutil/TestUsers.java new file mode 100644 index 0000000..10475d4 --- /dev/null +++ b/src/test/java/se/jensen/yuki/springboot/testutil/TestUsers.java @@ -0,0 +1,14 @@ +package se.jensen.yuki.springboot.testutil; + +import se.jensen.yuki.springboot.model.SecurityUser; + +public class TestUsers { + + public static SecurityUser user() { + return new SecurityUser(1L, "user@test.com", "USER"); + } + + public static SecurityUser admin() { + return new SecurityUser(99L, "admin@test.com", "ADMIN"); + } +} diff --git a/src/test/java/se/jensen/yuki/springboot/user/usecase/command/DeleteUserUseCaseTest.java b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/DeleteUserUseCaseTest.java new file mode 100644 index 0000000..d54939f --- /dev/null +++ b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/DeleteUserUseCaseTest.java @@ -0,0 +1,46 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +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 se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.UserId; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class DeleteUserUseCaseTest { + @Mock + UserRepository userRepository; + + @InjectMocks + DeleteUserUseCase useCase; + + @Test + void execute_ShouldDeleteUserSuccessfully() { + // Given + Long userId = 1L; + + // Then + assertDoesNotThrow(() -> useCase.execute(userId)); + verify(userRepository).deleteById(UserId.of(userId)); + } + + @Test + void execute_ShouldHandleNonExistingUser() { + // Given + Long nonExistingUserId = 999L; + UserId nonExistingUserIdVo = UserId.of(nonExistingUserId); + + doThrow(new RuntimeException("DB failure")) + .when(userRepository).deleteById(nonExistingUserIdVo); + + assertThrows(RuntimeException.class, + () -> useCase.execute(nonExistingUserId)); + } +} \ No newline at end of file diff --git a/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdateEmailUseCaseTest.java b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdateEmailUseCaseTest.java new file mode 100644 index 0000000..63a892a --- /dev/null +++ b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdateEmailUseCaseTest.java @@ -0,0 +1,77 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +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.crypto.password.PasswordEncoder; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.Email; +import se.jensen.yuki.springboot.user.domain.vo.HashedPassword; +import se.jensen.yuki.springboot.user.domain.vo.UserId; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateEmailRequest; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class UpdateEmailUseCaseTest { + + @Mock + UserRepository userRepository; + + @Mock + PasswordEncoder passwordEncoder; + + @InjectMocks + UpdateEmailUseCase useCase; + + @Test + void execute_shouldUpdateEmail_whenPasswordMatches() { + Long userId = 1L; + UserId userIdVo = UserId.of(userId); + + UserUpdateEmailRequest request = + new UserUpdateEmailRequest("new@mail.com", "correct-password"); + + User user = mock(User.class); + HashedPassword password = mock(HashedPassword.class); + + when(userRepository.findById(userIdVo)).thenReturn(user); + when(user.getPassword()).thenReturn(password); + when(password.getValue()).thenReturn("encoded-password"); + when(passwordEncoder.matches("correct-password", "encoded-password")) + .thenReturn(true); + + useCase.execute(userId, request); + + verify(user).changeEmail(any(Email.class)); + verify(userRepository).save(user); + } + + @Test + void execute_shouldThrowException_whenPasswordDoesNotMatch() { + Long userId = 1L; + UserId userIdVo = UserId.of(userId); + + UserUpdateEmailRequest request = + new UserUpdateEmailRequest("new@mail.com", "wrong-password"); + + User user = mock(User.class); + HashedPassword password = mock(HashedPassword.class); + + when(userRepository.findById(userIdVo)).thenReturn(user); + when(user.getPassword()).thenReturn(password); + when(password.getValue()).thenReturn("encoded-password"); + when(passwordEncoder.matches("wrong-password", "encoded-password")) + .thenReturn(false); + + assertThrows(IllegalArgumentException.class, + () -> useCase.execute(userId, request)); + + verify(user, never()).changeEmail(any()); + verify(userRepository, never()).save(any()); + } +} \ No newline at end of file diff --git a/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdatePasswordUseCaseTest.java b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdatePasswordUseCaseTest.java new file mode 100644 index 0000000..ff0505b --- /dev/null +++ b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdatePasswordUseCaseTest.java @@ -0,0 +1,117 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +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.crypto.password.PasswordEncoder; +import se.jensen.yuki.springboot.testutil.TestPasswords; +import se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.HashedPassword; +import se.jensen.yuki.springboot.user.domain.vo.UserId; +import se.jensen.yuki.springboot.user.web.dto.UserUpdatePasswordRequest; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class UpdatePasswordUseCaseTest { + + @Mock + UserRepository userRepository; + + @Mock + PasswordEncoder passwordEncoder; + + @InjectMocks + UpdatePasswordUseCase useCase; + + @Test + void execute_shouldUpdatePassword_whenValidRequest() { + Long userId = 1L; + UserId userIdVo = UserId.of(userId); + + UserUpdatePasswordRequest request = + new UserUpdatePasswordRequest("new-password", "current-password"); + + User user = mock(User.class); + HashedPassword password = mock(HashedPassword.class); + + String currentEncodedPassword = TestPasswords.hashed("current-password"); + + when(userRepository.findById(userIdVo)).thenReturn(user); + when(user.getPassword()).thenReturn(password); + when(password.getValue()).thenReturn(currentEncodedPassword); + + when(passwordEncoder.matches(request.currentPassword(), currentEncodedPassword)) + .thenReturn(true); + + when(passwordEncoder.matches(request.newPassword(), currentEncodedPassword)) + .thenReturn(false); + + String newHashedPassword = TestPasswords.hashed("new-encoded-password"); + + when(passwordEncoder.encode("new-password")) + .thenReturn(newHashedPassword); + + useCase.execute(userId, request); + + verify(user).changePassword(HashedPassword.of(newHashedPassword)); + verify(userRepository).save(user); + } + + @Test + void execute_shouldThrowException_whenCurrentPasswordIncorrect() { + Long userId = 1L; + UserId userIdVo = UserId.of(userId); + + UserUpdatePasswordRequest request = + new UserUpdatePasswordRequest("new-password", "wrong-password"); + + User user = mock(User.class); + HashedPassword password = mock(HashedPassword.class); + + when(userRepository.findById(userIdVo)).thenReturn(user); + when(user.getPassword()).thenReturn(password); + when(password.getValue()).thenReturn("encoded-password"); + + when(passwordEncoder.matches("wrong-password", "encoded-password")) + .thenReturn(false); + + assertThrows(IllegalArgumentException.class, + () -> useCase.execute(userId, request)); + + verify(user, never()).changePassword(any()); + verify(userRepository, never()).save(any()); + } + + @Test + void execute_shouldThrowException_whenNewPasswordSameAsCurrent() { + Long userId = 1L; + UserId userIdVo = UserId.of(userId); + + UserUpdatePasswordRequest request = + new UserUpdatePasswordRequest("same-password", "current-password"); + + User user = mock(User.class); + HashedPassword password = mock(HashedPassword.class); + + when(userRepository.findById(userIdVo)).thenReturn(user); + when(user.getPassword()).thenReturn(password); + when(password.getValue()).thenReturn("encoded-password"); + + when(passwordEncoder.matches("current-password", "encoded-password")) + .thenReturn(true); + + when(passwordEncoder.matches("same-password", "encoded-password")) + .thenReturn(true); + + assertThrows(IllegalArgumentException.class, + () -> useCase.execute(userId, request)); + + verify(user, never()).changePassword(any()); + verify(userRepository, never()).save(any()); + } +} diff --git a/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdateUserProfileUseCaseTest.java b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdateUserProfileUseCaseTest.java new file mode 100644 index 0000000..9f60f55 --- /dev/null +++ b/src/test/java/se/jensen/yuki/springboot/user/usecase/command/UpdateUserProfileUseCaseTest.java @@ -0,0 +1,58 @@ +package se.jensen.yuki.springboot.user.usecase.command; + +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 se.jensen.yuki.springboot.user.domain.User; +import se.jensen.yuki.springboot.user.domain.UserRepository; +import se.jensen.yuki.springboot.user.domain.vo.AvatarUrl; +import se.jensen.yuki.springboot.user.domain.vo.Bio; +import se.jensen.yuki.springboot.user.domain.vo.DisplayName; +import se.jensen.yuki.springboot.user.domain.vo.UserId; +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateProfileRequest; +import se.jensen.yuki.springboot.user.web.mapper.UserResponseMapper; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class UpdateUserProfileUseCaseTest { + + @Mock + UserRepository userRepository; + + @Mock + UserResponseMapper userMapper; + + @InjectMocks + UpdateUserProfileUseCase useCase; + + @Test + void execute_shouldUpdateProfile_andReturnResponse() { + Long userId = 1L; + UserId userIdVo = UserId.of(userId); + + UserUpdateProfileRequest request = + new UserUpdateProfileRequest("NewName", "NewBio", "/avatar.png"); + + User user = mock(User.class); + UserProfileResponse response = mock(UserProfileResponse.class); + + when(userRepository.findById(userIdVo)).thenReturn(user); + when(userMapper.toResponse(user)).thenReturn(response); + + UserProfileResponse result = useCase.execute(userId, request); + + verify(user).updateProfile( + DisplayName.of("NewName"), + Bio.of("NewBio"), + AvatarUrl.of("/avatar.png")); + verify(userRepository).save(user); + verify(userMapper).toResponse(user); + + assertSame(response, result); + } +} diff --git a/src/test/java/se/jensen/yuki/springboot/user/web/UserControllerTest.java b/src/test/java/se/jensen/yuki/springboot/user/web/UserControllerTest.java new file mode 100644 index 0000000..e7bd38f --- /dev/null +++ b/src/test/java/se/jensen/yuki/springboot/user/web/UserControllerTest.java @@ -0,0 +1,145 @@ +package se.jensen.yuki.springboot.user.web; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import se.jensen.yuki.springboot.testutil.TestUsers; +import se.jensen.yuki.springboot.user.usecase.command.DeleteUserUseCase; +import se.jensen.yuki.springboot.user.usecase.command.UpdateEmailUseCase; +import se.jensen.yuki.springboot.user.usecase.command.UpdatePasswordUseCase; +import se.jensen.yuki.springboot.user.usecase.command.UpdateUserProfileUseCase; +import se.jensen.yuki.springboot.user.usecase.query.UserQueryService; +import se.jensen.yuki.springboot.user.web.dto.UserProfileResponse; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateEmailRequest; +import se.jensen.yuki.springboot.user.web.dto.UserUpdatePasswordRequest; +import se.jensen.yuki.springboot.user.web.dto.UserUpdateProfileRequest; +import tools.jackson.databind.ObjectMapper; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@SpringBootTest +@AutoConfigureMockMvc +class UserControllerTest { + + @Autowired + MockMvc mockMvc; + + @Autowired + ObjectMapper objectMapper; + + @MockitoBean + UpdatePasswordUseCase updatePasswordUseCase; + @MockitoBean + UpdateEmailUseCase updateEmailUseCase; + @MockitoBean + UpdateUserProfileUseCase updateUserProfileUseCase; + @MockitoBean + DeleteUserUseCase deleteUserUseCase; + @MockitoBean + UserQueryService userQueryService; + + /* ------------------------- + GET /users/me + ------------------------- */ + @Test + void getMyProfile_shouldReturnProfile() throws Exception { + + UserProfileResponse response = + new UserProfileResponse(1L, "user", "user@test.com", "User", "user", "Bio", "avatar.png"); + + when(userQueryService.findById(1L)).thenReturn(response); + + mockMvc.perform(get("/users/me") + .with(user(TestUsers.user()))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(1L)) + .andExpect(jsonPath("$.email").value("user@test.com")); + } + + /* ------------------------- + PUT /users/me/password + ------------------------- */ + @Test + void updatePassword_shouldReturnNoContent() throws Exception { + + UserUpdatePasswordRequest request = + new UserUpdatePasswordRequest("newPass123", "currentPass123"); + + mockMvc.perform(put("/users/me/password") + .with(user(TestUsers.user())) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isNoContent()); + + verify(updatePasswordUseCase) + .execute(eq(1L), any(UserUpdatePasswordRequest.class)); + } + + /* ------------------------- + PUT /users/me/email + ------------------------- */ + @Test + void updateEmail_shouldReturnNoContent() throws Exception { + + UserUpdateEmailRequest request = + new UserUpdateEmailRequest("new@mail.com", "currentPass123"); + + mockMvc.perform(put("/users/me/email") + .with(user(TestUsers.user())) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isNoContent()); + + verify(updateEmailUseCase) + .execute(eq(1L), any(UserUpdateEmailRequest.class)); + } + + /* ------------------------- + PUT /users/me/profile + ------------------------- */ + @Test + void updateProfile_shouldReturnUpdatedProfile() throws Exception { + + UserUpdateProfileRequest request = + new UserUpdateProfileRequest("NewName", "NewBio", "/newAvatar.png"); + + UserProfileResponse response = + new UserProfileResponse(1L, "user", "user@test.com", "User", "NewName", "NewBio", "/newAvatar.png"); + + when(updateUserProfileUseCase.execute(eq(1L), any())) + .thenReturn(response); + + mockMvc.perform(put("/users/me/profile") + .with(user(TestUsers.user())) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.displayName").value("NewName")); + } + + /* ------------------------- + DELETE /users/{id} + ------------------------- */ + @Test + void deleteUser_shouldReturnNoContent() throws Exception { + + mockMvc.perform(delete("/users/1") + .with(user(TestUsers.user()))) + .andExpect(status().isNoContent()); + + verify(deleteUserUseCase).execute(1L); + } +} +