Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public record UserProfileResponse(
@Schema(description = "자기소개", example = "주말마다 카메라와 도감을 들고 전국의 탐조지를 찾아다니는 평범한 직장인입니다.", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
String bio,

@Schema(description = "표시 순서대로 정렬된 외부 프로필 링크 목록", requiredMode = Schema.RequiredMode.REQUIRED)
List<String> profileLinks,

@Schema(description = "가입일", example = "2024-01-15", requiredMode = Schema.RequiredMode.REQUIRED)
LocalDate joinedDate,

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public interface UserProfileMapper {
/* 메인 매핑 */
@Mapping(target = "nickname", source = "user.nickname")
@Mapping(target = "bio", source = "user.bio")
@Mapping(target = "profileLinks", source = "user.profileLinks")
@Mapping(target = "joinedDate",
expression = "java(OffsetDateTimeLocalizer.toSeoulLocalDate(user.getJoinedAt()))")
@Mapping(target = "profileImageUrl",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ public UserInfoResponse getMyUserInfo(

수정 가능한 항목:
- nickname: 닉네임 (정책 미준수 또는 중복 시 400 Bad Request)
- profileLinks: 외부 프로필 링크 목록 (최대 3개, 제출 순서대로 교체, 최대 100자/URL)
생략하거나 null이면 유지하고, 빈 배열이면 전체 삭제합니다.
주소에는 앞뒤에 문자가 있는 점(.)이 하나 이상 있어야 합니다.
스킴이 없는 주소에는 http://를 붙이며, 100자 제한은 저장할 주소에 적용합니다.
- profileImageObjectKey: 프로필 사진 Object Key (Presigned URL 발급 시 받은 것)
- profileImageContentType: 프로필 사진 Content-Type

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Schema(description = "사용자 정보 수정 요청 DTO")
@Data
@NoArgsConstructor
Expand All @@ -15,6 +17,9 @@ public class UpdateUserProfileRequest {
@Schema(description = "자기소개", example = "주말마다 카메라와 도감을 들고 전국의 탐조지를 찾아다니는 평범한 직장인입니다.")
private String bio;

@Schema(description = "프로필 링크 목록 (최대 3개). 생략하거나 null이면 유지하고, 빈 배열이면 전체 삭제합니다.")
private List<String> profileLinks;

@Schema(description = "프로필 이미지 S3 Object Key",
example = "user-profile-images/99999/15fd9a32-bb4e-4b7c-bd8b-4fd1e2b3d8a4")
private String profileImageObjectKey;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package org.devkor.apu.saerok_server.domain.user.api.dto.response;

import lombok.Data;
import java.util.List;

public record UpdateUserProfileResponse(
String nickname,
String email,
String bio,
List<String> profileLinks,
String profileImageUrl,
String thumbnailProfileImageUrl
) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package org.devkor.apu.saerok_server.domain.user.api.response;

import java.time.LocalDate;
import java.util.List;

public record UserInfoResponse(
String nickname,
String email,
String bio,
List<String> profileLinks,
LocalDate joinedDate,
String profileImageUrl,
String thumbnailProfileImageUrl
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public UpdateUserProfileResponse updateUserProfile(UpdateUserProfileCommand comm
try {
if (command.nickname() != null) userProfileUpdateService.changeNickname(user, command.nickname());
if (command.bio() != null) userProfileUpdateService.changeBio(user, command.bio());
if (command.profileLinks() != null) userProfileUpdateService.changeProfileLinks(user, command.profileLinks());

} catch (IllegalArgumentException e) {
throw new BadRequestException("사용자 정보 수정이 거부되었습니다: " + e.getMessage());
Expand All @@ -61,6 +62,7 @@ public UpdateUserProfileResponse updateUserProfile(UpdateUserProfileCommand comm
user.getNickname(),
user.getEmail(),
user.getBio(),
user.getProfileLinks(),
userProfileImageUrlService.getProfileImageUrlFor(user),
userProfileImageUrlService.getProfileThumbnailImageUrlFor(user)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public UserInfoResponse getMyUserInfo(Long userId) {
user.getNickname(),
user.getEmail(),
user.getBio(),
user.getProfileLinks(),
OffsetDateTimeLocalizer.toSeoulLocalDate(user.getJoinedAt()),
userProfileImageUrlService.getProfileImageUrlFor(user),
userProfileImageUrlService.getProfileThumbnailImageUrlFor(user)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package org.devkor.apu.saerok_server.domain.user.application.dto;

import java.util.List;

public record UpdateUserProfileCommand(
Long userId,
String nickname,
String bio,
List<String> profileLinks,
String profileImageObjectKey,
String profileImageContentType
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
import lombok.Getter;
import lombok.Setter;
import org.devkor.apu.saerok_server.global.shared.entity.SoftDeletableAuditable;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.List;

@Entity
@Table(name = "users")
Expand Down Expand Up @@ -39,6 +42,11 @@ public class User extends SoftDeletableAuditable {
@Column(name = "bio")
private String bio;

@Setter
@JdbcTypeCode(SqlTypes.ARRAY)
@Column(name = "profile_links", nullable = false, columnDefinition = "text[]")
private List<String> profileLinks = List.of();

@Enumerated(EnumType.STRING)
@Column(name = "signup_status")
@Setter
Expand Down Expand Up @@ -68,6 +76,7 @@ public void anonymizeForWithdrawal() {
this.gender = null;
this.birthDate = null;
this.bio = null;
this.profileLinks = List.of();
this.setDefaultProfileImageVariant(null);
this.setSignupStatus(SignupStatusType.WITHDRAWN);
this.softDelete();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

import static org.devkor.apu.saerok_server.global.shared.util.TransactionUtils.runAfterCommitOrNow;

Expand All @@ -23,6 +24,11 @@
public class UserProfileUpdateService {

private static final int MAX_BIO_LENGTH = 100;
private static final int MAX_PROFILE_LINKS = 3;
private static final int MAX_PROFILE_LINK_LENGTH = 100;
private static final Pattern URL_SCHEME = Pattern.compile("^[A-Za-z][A-Za-z0-9+.-]*:");
private static final Pattern HOST_WITH_PORT = Pattern.compile("^[^:/?#]+\\.[^:/?#]+:[0-9]+(?:[/?#]|$)");
private static final Pattern PROFILE_LINK_DOT = Pattern.compile("[^.]\\.[^.]");

private final NicknamePolicy nicknamePolicy;
private final UserRepository userRepository;
Expand Down Expand Up @@ -54,6 +60,30 @@ public void changeBio(User user, String bio) {
user.setBio(bio.isEmpty() ? null : bio);
}

public void changeProfileLinks(User user, List<String> profileLinks) {
if (profileLinks.size() > MAX_PROFILE_LINKS) {
throw new IllegalArgumentException("프로필 링크는 최대 " + MAX_PROFILE_LINKS + "개까지 등록할 수 있어요.");
}

List<String> links = profileLinks.stream()
.map(this::normalizeProfileLink)
.toList();
user.setProfileLinks(links);
}

private String normalizeProfileLink(String link) {
if (link == null || !PROFILE_LINK_DOT.matcher(link).find()) {
throw new IllegalArgumentException("링크 주소를 확인해 주세요. example.com처럼 입력할 수 있어요.");
}

boolean hasScheme = URL_SCHEME.matcher(link).find() && !HOST_WITH_PORT.matcher(link).find();
String normalizedLink = hasScheme ? link : "http://" + link;
if (normalizedLink.codePointCount(0, normalizedLink.length()) > MAX_PROFILE_LINK_LENGTH) {
throw new IllegalArgumentException("프로필 링크는 " + MAX_PROFILE_LINK_LENGTH + "자 이하로 입력해 주세요.");
}
return normalizedLink;
}

public void changeProfileImage(User user, String objectKey, String contentType) {
userProfileImageRepository.findByUserId(user.getId())
.ifPresentOrElse(
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/db/migration/V99__add_links_to_users.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE users
ADD COLUMN profile_links TEXT[] NOT NULL DEFAULT '{}';
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class UpdateUserProfile {
@Test
@DisplayName("닉네임만 변경하면 닉네임 변경 도메인 서비스 호출 및 응답 반영")
void nicknameOnly() {
user.setProfileLinks(List.of("http://example.com"));
given(userRepository.findById(42L)).willReturn(Optional.of(user));
doAnswer(invocation -> {
User u = invocation.getArgument(0);
Expand All @@ -93,12 +94,13 @@ void nicknameOnly() {
given(userProfileImageUrlService.getProfileImageUrlFor(user)).willReturn(null);
given(userProfileImageUrlService.getProfileThumbnailImageUrlFor(user)).willReturn(null);

UpdateUserProfileCommand cmd = new UpdateUserProfileCommand(42L, "newNick", null, null, null);
UpdateUserProfileCommand cmd = new UpdateUserProfileCommand(42L, "newNick", null, null, null, null);

UpdateUserProfileResponse res = sut.updateUserProfile(cmd);

assertThat(res.nickname()).isEqualTo("newNick");
assertThat(res.email()).isEqualTo("old@example.com");
assertThat(res.profileLinks()).containsExactly("http://example.com");
assertThat(res.profileImageUrl()).isNull();
assertThat(res.thumbnailProfileImageUrl()).isNull();

Expand All @@ -116,7 +118,7 @@ void badNickname_throwsBadRequest() {
doThrow(new IllegalArgumentException("정책 위반"))
.when(userProfileUpdateService).changeNickname(user, "bad");

UpdateUserProfileCommand cmd = new UpdateUserProfileCommand(42L, "bad", null, null, null);
UpdateUserProfileCommand cmd = new UpdateUserProfileCommand(42L, "bad", null, null, null, null);

assertThatThrownBy(() -> sut.updateUserProfile(cmd))
.isInstanceOf(BadRequestException.class)
Expand All @@ -128,11 +130,33 @@ void badNickname_throwsBadRequest() {
void userNotFound() {
given(userRepository.findById(999L)).willReturn(Optional.empty());

UpdateUserProfileCommand cmd = new UpdateUserProfileCommand(999L, "nick", null, null, null);
UpdateUserProfileCommand cmd = new UpdateUserProfileCommand(999L, "nick", null, null, null, null);

assertThatThrownBy(() -> sut.updateUserProfile(cmd))
.isInstanceOf(NotFoundException.class);
}

@Test
void emptyProfileLinksArePassedToUpdateService() {
given(userRepository.findById(42L)).willReturn(Optional.of(user));
var command = new UpdateUserProfileCommand(42L, null, null, List.of(), null, null);

assertThat(sut.updateUserProfile(command).profileLinks()).isEmpty();
verify(userProfileUpdateService).changeProfileLinks(user, List.of());
}

@Test
void invalidProfileLinksAreReportedAsBadRequest() {
var links = List.of("invalid");
given(userRepository.findById(42L)).willReturn(Optional.of(user));
doThrow(new IllegalArgumentException("잘못된 링크"))
.when(userProfileUpdateService).changeProfileLinks(user, links);
var command = new UpdateUserProfileCommand(42L, null, null, links, null, null);

assertThatThrownBy(() -> sut.updateUserProfile(command))
.isInstanceOf(BadRequestException.class)
.hasMessageContaining("잘못된 링크");
}
}

@Nested
Expand Down Expand Up @@ -225,6 +249,7 @@ class DeleteUserAccount {
void ok() {
long userId = 42L;
user.setBio("주말마다 탐조해요");
user.setProfileLinks(List.of("http://example.com"));
given(userRepository.findById(userId)).willReturn(Optional.of(user));

given(kakaoLink.getProvider()).willReturn(SocialProviderType.KAKAO);
Expand All @@ -243,6 +268,7 @@ void ok() {
assertThat(user.getSignupStatus()).isEqualTo(SignupStatusType.WITHDRAWN);
assertThat(user.getDeletedAt()).isNotNull();
assertThat(user.getBio()).isNull();
assertThat(user.getProfileLinks()).isEmpty();
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -118,6 +119,67 @@ void changeNickname_duplicateNickname() {
verify(userRepository).findByNickname(dupNick);
}

@Test
void changeProfileLinks_preservesOrderAndDuplicates() {
User user = new User();

userProfileUpdateService.changeProfileLinks(user,
List.of("https://example.com", "naver.com", "http://naver.com"));

assertEquals(List.of("https://example.com", "http://naver.com", "http://naver.com"), user.getProfileLinks());
}

@Test
void changeProfileLinks_addsDefaultSchemeToHostWithPort() {
User user = new User();

userProfileUpdateService.changeProfileLinks(user, List.of("example.com:8080/birds"));

assertEquals(List.of("http://example.com:8080/birds"), user.getProfileLinks());
}

@Test
void changeProfileLinks_emptyListClearsExistingLinks() {
User user = new User();
user.setProfileLinks(List.of("http://example.com"));

userProfileUpdateService.changeProfileLinks(user, List.of());

assertTrue(user.getProfileLinks().isEmpty());
}

@Test
void changeProfileLinks_validatesStoredLengthIncludingDefaultScheme() {
User user = new User();
String linkWithoutScheme = "a." + "b".repeat(91);
String normalizedLink = "http://" + linkWithoutScheme;

userProfileUpdateService.changeProfileLinks(user, List.of(linkWithoutScheme));
assertEquals(List.of(normalizedLink), user.getProfileLinks());
userProfileUpdateService.changeProfileLinks(user, user.getProfileLinks());
assertThrows(IllegalArgumentException.class,
() -> userProfileUpdateService.changeProfileLinks(user, List.of(linkWithoutScheme + "b")));
}

@Test
void changeProfileLinks_invalidListKeepsExistingLinks() {
User user = new User();
var existingLinks = List.of("https://example.com");
user.setProfileLinks(existingLinks);
List<List<String>> invalidLists = List.of(
List.of("a.com", "b.com", "c.com", "d.com"),
Arrays.asList("valid.com", null),
List.of("valid.com", ".invalid"),
List.of("valid.com", "invalid."),
List.of("valid.com", "invalid"));

for (var links : invalidLists) {
assertThrows(IllegalArgumentException.class,
() -> userProfileUpdateService.changeProfileLinks(user, links));
assertEquals(existingLinks, user.getProfileLinks());
}
}

@Test
@DisplayName("프로필 이미지 변경: 기존과 다르면 교체하고, 기존(원본+썸네일) 삭제")
void changeProfileImage_replaceAndDeleteAssociated() {
Expand Down
Loading