Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] 관심 목록 변경 API #76

Merged
merged 7 commits into from
Aug 7, 2023
Merged
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 @@ -48,6 +48,7 @@ class WebSecurityConfig(
c.requestMatchers("/users/nickname").permitAll()
c.requestMatchers("/users/eid").permitAll()
c.requestMatchers("/users/reissue").permitAll()
c.requestMatchers("/users/password-reset").permitAll()
c.anyRequest().authenticated()
}
.apply(JwtSecurityConfig(jwtUtils, redisTemplate))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ enum class BaseResponseCode(status: HttpStatus, message: String) {
NOT_EXIST_EMAIL(HttpStatus.BAD_REQUEST, "해당 이메일로 가입한 사용자를 찾을 수 없습니다."),
INVALID_PASSWORD(HttpStatus.BAD_REQUEST, "사용자의 비밀번호가 일치하지 않습니다."),
NOT_FOUND_USER(HttpStatus.NOT_FOUND, "사용자를 찾을 수 없습니다."),
INVALID_PHONE(HttpStatus.BAD_REQUEST, "사용자의 휴대폰 번호와 일치하지 않습니다."),
NOT_FOUND_EID(HttpStatus.NOT_FOUND, "사업자를 찾을 수 없습니다."),
NOT_EMPTY_EID(HttpStatus.BAD_REQUEST, "사업자 정보를 입력해주세요. "),
INVALID_EID(HttpStatus.BAD_REQUEST, "정상 사업자가 아닙니다. (휴업자 or 폐업자)"),
DUPLICATE_PASSWORD(HttpStatus.BAD_REQUEST, "사용자의 비밀번호와 변경하려는 비밀번호가 동일합니다."),

// User - type
INVALID_USER_TYPE_NAME(HttpStatus.BAD_REQUEST, "올바르지 않은 사용자 역할입니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class ProductService(
var interestCategoryList: MutableList<Category> = ArrayList()
if(category.isEmpty()) {
// 유저의 관심목록
val userInterestList = userInterestRepository.findByUser(user);
val userInterestList = userInterestRepository.findByUserAndStatus(user, ACTIVE_STATUS);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요거 status 확인이 필요한 것 같아서 userInterestRepository method 변경하는 김에 한번에 변경해뒀슴니당
@sojungpp

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고맘머(하트

interestCategoryList = userInterestList.stream().map { ui -> ui.category }.toList()
} else {
interestCategoryList.add(Category.getCategoryByName(category))
Expand Down
30 changes: 30 additions & 0 deletions src/main/kotlin/com/psr/psr/user/controller/UserController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,35 @@ class UserController(
return BaseResponse(userService.reissueToken(tokenDto))
}

/**
* 비밀번호 변경화면 with Token
*/
@PatchMapping("/password-change")
@ResponseBody
fun changePassword(@AuthenticationPrincipal userAccount: UserAccount, @RequestBody @Validated passwordReq: ChangePasswordReq) : BaseResponse<Any>{
userService.changePassword(userAccount.getUser(), passwordReq)
return BaseResponse(BaseResponseCode.SUCCESS)
}

/**
* 비밀번호 재설정 except Token
*/
@PatchMapping("/password-reset")
@ResponseBody
fun resetPassword(@RequestBody @Validated resetPasswordReq: ResetPasswordReq) : BaseResponse<Any>{
userService.resetPassword(resetPasswordReq)
return BaseResponse(BaseResponseCode.SUCCESS)
}

/**
* 관심 목록 변경
*/
@PatchMapping("/watchlists")
@ResponseBody
fun patchWatchLists(@AuthenticationPrincipal userAccount: UserAccount, @RequestBody @Validated userInterestListReq: UserInterestListReq) : BaseResponse<Any>{
userService.patchWatchLists(userAccount.getUser(), userInterestListReq)
return BaseResponse(BaseResponseCode.SUCCESS)
}


}
19 changes: 19 additions & 0 deletions src/main/kotlin/com/psr/psr/user/dto/ChangePasswordReq.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.psr.psr.user.dto

import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Pattern

data class ChangePasswordReq (
@field:NotBlank
@field:Pattern(
regexp = "^.*(?=^.{8,15}\$)(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#\$%^&+=]).*\$",
message = "비밀번호를 숫자, 문자, 특수문자 포함 8~15자리 이내로 입력해주세요"
)
val currentPassword: String,
@field:NotBlank
@field:Pattern(
regexp = "^.*(?=^.{8,15}\$)(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#\$%^&+=]).*\$",
message = "비밀번호를 숫자, 문자, 특수문자 포함 8~15자리 이내로 입력해주세요"
)
val password: String
)
23 changes: 23 additions & 0 deletions src/main/kotlin/com/psr/psr/user/dto/ResetPasswordReq.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.psr.psr.user.dto

import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Pattern

data class ResetPasswordReq (
@field:NotBlank(message = "이메일을 입력해주세요.")
@field:Email(message = "올바르지 않은 이메일 형식입니다.")
val email: String,
@field:NotBlank(message = "휴대폰을 입력해주세요.")
@field:Pattern(
regexp = "^01([0|1|6|7|8|9])-?([0-9]{3,4})-?([0-9]{4})\$",
message = "올바르지 않은 휴대폰 형식입니다."
)
val phone: String,
@field:NotBlank(message = "비밀번호를 입력해주세요.")
@field:Pattern(
regexp = "^.*(?=^.{8,15}\$)(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#\$%^&+=]).*\$",
message = "비밀번호를 숫자, 문자, 특수문자 포함 8~15자리 이내로 입력해주세요"
)
val password: String
)
5 changes: 5 additions & 0 deletions src/main/kotlin/com/psr/psr/user/dto/UserInterestListReq.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.psr.psr.user.dto

data class UserInterestListReq (
val interestList: List<UserInterestReq>
)
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,19 @@ class UserAssembler {
nickname = signUpReq.nickname)
}

fun toInterestEntity(user: User, signUpReq: SignUpReq): List<UserInterest> {
fun toInterestListEntity(user: User, signUpReq: SignUpReq): List<UserInterest> {
return signUpReq.interestList.stream()
.map { i ->
UserInterest(category = Category.getCategoryByName(i.category),
user = user)
}.collect(Collectors.toList())
}

fun toInterestEntity(user: User, category: Category): UserInterest {
return UserInterest(user = user,
category = category)
}

fun toBusinessEntity(user: User, signUpReq: SignUpReq): BusinessInfo {
val format = DateTimeFormatter.ofPattern("yyyyMMdd")
return BusinessInfo(user = user,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.psr.psr.user.repository

import com.psr.psr.user.entity.Category
import com.psr.psr.user.entity.User
import com.psr.psr.user.entity.UserInterest
import org.springframework.data.jpa.repository.JpaRepository
Expand All @@ -8,6 +9,7 @@ import org.springframework.stereotype.Repository
@Repository
interface UserInterestRepository: JpaRepository<UserInterest, Long> {

fun findByUser(user: User): List<UserInterest>
fun findByUserAndStatus(user: User, status: String): List<UserInterest>
fun findByUserAndCategory(user: User, category: Category): UserInterest ?

}
56 changes: 55 additions & 1 deletion src/main/kotlin/com/psr/psr/user/service/UserService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import com.psr.psr.global.jwt.utils.JwtUtils
import com.psr.psr.user.dto.*
import com.psr.psr.user.dto.assembler.UserAssembler
import com.psr.psr.user.dto.eidReq.BusinessListRes
import com.psr.psr.user.entity.Category
import com.psr.psr.user.entity.Type
import com.psr.psr.user.entity.User
import com.psr.psr.user.repository.BusinessInfoRepository
Expand Down Expand Up @@ -67,7 +68,7 @@ class UserService(
signUpReq.password = encodedPassword
// user 저장
val user = userRepository.save(userAssembler.toEntity(signUpReq))
userInterestRepository.saveAll(userAssembler.toInterestEntity(user, signUpReq))
userInterestRepository.saveAll(userAssembler.toInterestListEntity(user, signUpReq))

// 사업자인경우
if (user.type == Type.ENTREPRENEUR){
Expand All @@ -80,6 +81,7 @@ class UserService(
}

// 로그인
@Transactional
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

추가하지 못했던 Transactional 추가,, 🌞

fun login(loginReq: LoginReq) : TokenDto{
val user = userRepository.findByEmail(loginReq.email).orElseThrow{BaseException(NOT_EXIST_EMAIL)}
if(!passwordEncoder.matches(loginReq.password, user.password)) throw BaseException(INVALID_PASSWORD)
Expand Down Expand Up @@ -180,4 +182,56 @@ class UserService(
// token 생성
return jwtUtils.createToken(authentication, user.type)
}

// 비밀번호 변경
@Transactional
fun changePassword(user: User, passwordReq: ChangePasswordReq) {
// 현재 비밀번호 일치 여부
if(!passwordEncoder.matches(passwordReq.currentPassword, user.password)) throw BaseException(INVALID_PASSWORD)
// 현재 비밀번호와 변경하려는 비밀번호 일치 여부
if(passwordReq.currentPassword == passwordReq.password) throw BaseException(DUPLICATE_PASSWORD)

// 비밀번호 변경
user.password = passwordEncoder.encode(passwordReq.password)
userRepository.save(user)
}

// 비밀번호 재설정
@Transactional
fun resetPassword(passwordReq: ResetPasswordReq) {
val user = userRepository.findByEmail(passwordReq.email).orElseThrow{BaseException(NOT_EXIST_EMAIL)}
if(user.phone != passwordReq.phone) throw BaseException(INVALID_PHONE)
if(passwordEncoder.matches(passwordReq.password, user.password)) throw BaseException(DUPLICATE_PASSWORD)

// 비밀번호 변경
user.password = passwordEncoder.encode(passwordReq.password)
userRepository.save(user)
}

// 관심 목록 변경
@Transactional
fun patchWatchLists(user: User, userInterestListReq: UserInterestListReq) {
val reqLists = userInterestListReq.interestList.map { i -> Category.getCategoryByName(i.category) }
if(reqLists.isEmpty() || reqLists.size > 3) throw BaseException(INVALID_USER_INTEREST_COUNT)
val userWatchLists = userInterestRepository.findByUserAndStatus(user, ACTIVE_STATUS)
val categoryLists = userWatchLists.map { c -> c.category }

// 사용자 관심 목록에 최근 추가한 리스트(REQUEST) 관심 목록이 없다면? => 저장
reqLists.stream()
.forEach { interest ->
if(!categoryLists.contains(interest)) {
// 과거에 삭제했던 경우 / 새롭게 생성하는 경우
val interestE = userInterestRepository.findByUserAndCategory(user, interest)?: userAssembler.toInterestEntity(user, interest)
interestE.status = ACTIVE_STATUS
userInterestRepository.save(interestE)
}
}

// 최근 추가한 리스트(REQUEST)에 사용자 관심 목록이 없다면? => 삭제
userWatchLists.stream()
.forEach { interest ->
// todo: cascade 적용 후 모두 삭제 되었는지 확인 필요
if(!reqLists.contains(interest.category)) userInterestRepository.delete(interest)
}
}
Comment on lines +219 to +236
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

스크린샷 2023-08-07 오전 2 24 56

다음과 같이 리스트 확인 후 수정하는 로직을 구상해보았슴니당

출처 클릭

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이렇게 깔끔하게 가능하군요!!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋다줍줍

}
Loading