Skip to content

Commit

Permalink
[UPDATE] update error base
Browse files Browse the repository at this point in the history
  • Loading branch information
jihoi-kang committed Nov 17, 2023
1 parent a76af2b commit 1a802c1
Show file tree
Hide file tree
Showing 20 changed files with 203 additions and 236 deletions.
22 changes: 11 additions & 11 deletions src/main/kotlin/healthiee/rest/domain/auth/api/AuthApiController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import healthiee.rest.domain.auth.dto.request.CodeLoginRequest
import healthiee.rest.domain.auth.dto.request.RegisterRequest
import healthiee.rest.domain.auth.dto.response.AuthResponse
import healthiee.rest.domain.auth.dto.response.VerifyCodeResponse
import healthiee.rest.lib.response.BaseResponse
import healthiee.rest.domain.common.dto.base.Response
import healthiee.rest.domain.auth.service.AuthService
import jakarta.validation.Valid
import org.springframework.http.HttpStatus
Expand All @@ -31,35 +31,35 @@ class AuthApiController(
) {

@PostMapping("")
fun auth(@Valid @RequestBody request: AuthRequest): ResponseEntity<BaseResponse<AuthResponse>> {
fun auth(@Valid @RequestBody request: AuthRequest): ResponseEntity<Response<AuthResponse>> {
return ResponseEntity.ok(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
data = authService.auth(request),
)
)
}

@PostMapping("login")
fun codeLogin(@Valid @RequestBody request: CodeLoginRequest): ResponseEntity<BaseResponse<AuthenticationDto>> {
fun codeLogin(@Valid @RequestBody request: CodeLoginRequest): ResponseEntity<Response<AuthenticationDto>> {
val authentication = authService.codeLogin(request)

return ResponseEntity.ok()
.headers {
it.set("Set-Cookie", createCookie(authentication.refreshToken).toString())
}
.body(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
data = AuthenticationDto(authentication.memberId, authentication.token),
)
)
}

@GetMapping("verify/{code}")
fun verifyCode(@PathVariable("code") code: UUID): ResponseEntity<BaseResponse<VerifyCodeResponse>> {
fun verifyCode(@PathVariable("code") code: UUID): ResponseEntity<Response<VerifyCodeResponse>> {
return ResponseEntity.ok(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
data = authService.verifyCode(code)
)
Expand All @@ -73,15 +73,15 @@ class AuthApiController(
fun register(
@Valid @RequestPart("data") request: RegisterRequest,
@RequestPart("image") image: MultipartFile?,
): ResponseEntity<BaseResponse<AuthenticationDto>> {
): ResponseEntity<Response<AuthenticationDto>> {
val authentication = authService.register(request, image)

return ResponseEntity.ok(
).headers {
it.set("Set-Cookie", createCookie(authentication.refreshToken).toString())
}
.body(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
data = AuthenticationDto(authentication.memberId, authentication.token)
)
Expand All @@ -91,7 +91,7 @@ class AuthApiController(
@PostMapping("refresh")
fun refreshToken(
@RequestHeader(value = "cookie") cookie: String,
): ResponseEntity<BaseResponse<AuthenticationDto>> {
): ResponseEntity<Response<AuthenticationDto>> {
val refreshToken = cookie.substring(13)
val authentication = authService.refreshToken(refreshToken)

Expand All @@ -101,7 +101,7 @@ class AuthApiController(
it.set("Set-Cookie", createCookie(authentication.refreshToken).toString())
}
.body(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
data = AuthenticationDto(authentication.memberId, authentication.token)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package healthiee.rest.domain.auth.dto.request

import com.fasterxml.jackson.annotation.JsonProperty
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotNull

data class AuthRequest(
@field:Email(message = "The value must be email format")
@field:NotNull(message = "The value must not be null")
@JsonProperty("email")
private val _email: String?,
) {
Expand Down
64 changes: 33 additions & 31 deletions src/main/kotlin/healthiee/rest/domain/auth/service/AuthService.kt
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
package healthiee.rest.domain.auth.service

import healthiee.rest.domain.auth.entity.EmailAuth
import healthiee.rest.domain.auth.entity.Token
import healthiee.rest.domain.common.entity.media.MediaType
import healthiee.rest.domain.hashtag.entity.Hashtag
import healthiee.rest.domain.member.entity.Member
import healthiee.rest.domain.auth.dto.AuthenticationTempDto
import healthiee.rest.domain.auth.dto.request.AuthRequest
import healthiee.rest.domain.auth.dto.request.CodeLoginRequest
import healthiee.rest.domain.auth.dto.request.RegisterRequest
import healthiee.rest.domain.auth.dto.response.AuthResponse
import healthiee.rest.domain.auth.dto.response.VerifyCodeResponse
import healthiee.rest.domain.auth.entity.EmailAuth
import healthiee.rest.domain.auth.entity.Token
import healthiee.rest.domain.auth.repository.EmailAuthRepository
import healthiee.rest.domain.auth.repository.TokenRepository
import healthiee.rest.domain.common.entity.media.MediaType
import healthiee.rest.domain.hashtag.entity.Hashtag
import healthiee.rest.domain.hashtag.repository.HashtagRepository
import healthiee.rest.domain.member.entity.Member
import healthiee.rest.domain.member.repository.MemberRepository
import healthiee.rest.lib.authority.JwtTokenProvider
import healthiee.rest.lib.authority.TokenType
import healthiee.rest.lib.error.ApiException
import healthiee.rest.lib.error.ApplicationErrorCode.FORBIDDEN_INVALID_REFRESH_TOKEN
import healthiee.rest.lib.error.ApplicationErrorCode.NOT_FOUND_CODE
import healthiee.rest.lib.error.ApplicationErrorCode.NOT_FOUND_MEMBER
import healthiee.rest.lib.error.ErrorCode.FORBIDDEN
import healthiee.rest.lib.error.ErrorCode.NOT_FOUND
import healthiee.rest.lib.mail.model.MailBuilderParams
import healthiee.rest.lib.mail.model.MailSenderParams
import healthiee.rest.lib.mail.sender.MailSender
import healthiee.rest.lib.mail.template.MailBuilder
import healthiee.rest.lib.uploader.MediaDomainType
import healthiee.rest.lib.uploader.S3Uploader
import healthiee.rest.domain.auth.repository.EmailAuthRepository
import healthiee.rest.domain.auth.repository.TokenRepository
import healthiee.rest.domain.hashtag.repository.HashtagRepository
import healthiee.rest.domain.member.repository.MemberRepository
import org.springframework.data.repository.findByIdOrNull
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
Expand Down Expand Up @@ -77,14 +76,14 @@ class AuthService(
@Transactional
fun codeLogin(request: CodeLoginRequest): AuthenticationTempDto {
val findEmailAuth = emailAuthRepository.findByCode(request.code)
findEmailAuth ?: throw ApiException(NOT_FOUND_CODE)
if (findEmailAuth.disabled) throw ApiException(NOT_FOUND_CODE)
findEmailAuth ?: throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")
if (findEmailAuth.disabled) throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")

val diff = Duration.between(findEmailAuth.createdDate, LocalDateTime.now())
if (diff.toHours() >= 24) throw ApiException(NOT_FOUND_CODE)
if (diff.toHours() >= 24) throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")

val findMember = memberRepository.findByEmail(findEmailAuth.email)
findMember ?: throw ApiException(NOT_FOUND_MEMBER)
findMember ?: throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")

authenticationManager.authenticate(
UsernamePasswordAuthenticationToken(findMember.id, findMember.nickname)
Expand All @@ -108,23 +107,26 @@ class AuthService(

fun verifyCode(code: UUID): VerifyCodeResponse {
val findEmailAuth = emailAuthRepository.findByCode(code)
findEmailAuth ?: throw ApiException(NOT_FOUND_CODE)
if (findEmailAuth.disabled) throw ApiException(NOT_FOUND_CODE)
findEmailAuth ?: throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")
if (findEmailAuth.disabled) throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")

val diff = Duration.between(findEmailAuth.createdDate, LocalDateTime.now())
if (diff.toHours() >= 24) throw ApiException(NOT_FOUND_CODE)
if (diff.toHours() >= 24) throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")

return VerifyCodeResponse(findEmailAuth.email)
}

@Transactional
fun register(request: RegisterRequest, image: MultipartFile?): AuthenticationTempDto {
val findEmailAuth =
emailAuthRepository.findByCode(UUID.fromString(request.code)) ?: throw ApiException(NOT_FOUND_CODE)
if (findEmailAuth.disabled) throw ApiException(NOT_FOUND_CODE)
emailAuthRepository.findByCode(UUID.fromString(request.code)) ?: throw ApiException(
NOT_FOUND,
"인증 코드를 찾을 수 없습니다"
)
if (findEmailAuth.disabled) throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")

val diff = Duration.between(findEmailAuth.createdDate, LocalDateTime.now())
if (diff.toHours() >= 24) throw ApiException(NOT_FOUND_CODE)
if (diff.toHours() >= 24) throw ApiException(NOT_FOUND, "인증 코드를 찾을 수 없습니다")

var profileUrl: String? = null
if (image != null && !image.isEmpty) {
Expand Down Expand Up @@ -182,28 +184,28 @@ class AuthService(
fun refreshToken(refreshToken: String): AuthenticationTempDto {
val type: String = jwtTokenProvider.extractClaim(refreshToken) {
it.get("type", String::class.java)
} ?: throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
} ?: throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
val tokenId: String = jwtTokenProvider.extractClaim(refreshToken) {
it.get("tokenId", String::class.java)
} ?: throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
} ?: throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
val memberId: String = jwtTokenProvider.extractUsername(refreshToken)
?: throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
?: throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
val rotationCounter: Int = jwtTokenProvider.extractClaim(refreshToken) {
it.get("rotationCounter", Integer::class.java)
}?.toInt() ?: throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
}?.toInt() ?: throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")

if (type != TokenType.REFRESH_TOKEN.name.lowercase()) {
throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
}

val findMember = memberRepository.findByIdOrNull(UUID.fromString(memberId))
?: throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
?: throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
val findToken = tokenRepository.findByIdIncludeMember(UUID.fromString(tokenId))
?: throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
if (findToken.blocked) throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
?: throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
if (findToken.blocked) throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
if (findToken.rotationCounter != rotationCounter) {
findToken.block()
throw ApiException(FORBIDDEN_INVALID_REFRESH_TOKEN)
throw ApiException(FORBIDDEN, "유효하지 않는 토큰입니다")
}

findToken.increaseRotationCounter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package healthiee.rest.domain.code.api
import healthiee.rest.domain.code.dto.CodeDto
import healthiee.rest.domain.code.dto.request.SaveCodeRequest
import healthiee.rest.domain.code.dto.request.UpdateCodeRequest
import healthiee.rest.lib.response.BaseResponse
import healthiee.rest.domain.common.dto.base.Response
import healthiee.rest.domain.code.service.CodeService
import jakarta.validation.Valid
import org.springframework.http.HttpStatus
Expand All @@ -26,10 +26,10 @@ class CodeApiController(

@PostMapping("")
@PreAuthorize("hasRole('ADMIN')")
fun save(@RequestBody @Valid request: SaveCodeRequest): ResponseEntity<BaseResponse<Any>> {
fun save(@RequestBody @Valid request: SaveCodeRequest): ResponseEntity<Response<Any>> {
codeService.save(request)
return ResponseEntity.ok(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
message = "코드 생성이 완료되었습니다"
)
Expand All @@ -38,9 +38,9 @@ class CodeApiController(

@GetMapping("")
@PreAuthorize("hasRole('ADMIN') or hasRole('MEMBER')")
fun findAll(): ResponseEntity<BaseResponse<List<CodeDto>>> {
fun findAll(): ResponseEntity<Response<List<CodeDto>>> {
return ResponseEntity.ok(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
data = codeService.findAll(),
)
Expand All @@ -52,10 +52,10 @@ class CodeApiController(
fun update(
@PathVariable("codeId") codeId: Long,
@RequestBody @Valid request: UpdateCodeRequest,
): ResponseEntity<BaseResponse<Any>> {
): ResponseEntity<Response<Any>> {
codeService.update(codeId, request)
return ResponseEntity.ok(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
message = "코드 수정이 완료되었습니다"
)
Expand All @@ -64,10 +64,10 @@ class CodeApiController(

@DeleteMapping("{codeId}")
@PreAuthorize("hasRole('ADMIN')")
fun delete(@PathVariable("codeId") codeId: Long): ResponseEntity<BaseResponse<Any>> {
fun delete(@PathVariable("codeId") codeId: Long): ResponseEntity<Response<Any>> {
codeService.delete(codeId)
return ResponseEntity.ok(
BaseResponse(
Response(
code = HttpStatus.OK.value(),
message = "코드 삭제가 완료되었습니다"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package healthiee.rest.domain.code.repository

import com.querydsl.core.types.dsl.BooleanExpression
import healthiee.rest.domain.code.entity.Code
import healthiee.rest.domain.code.QCode.code
import healthiee.rest.domain.code.entity.QCode.code
import healthiee.rest.lib.querydsl.QuerydslRepositorySupport
import org.springframework.stereotype.Repository

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import healthiee.rest.domain.code.dto.request.SaveCodeRequest
import healthiee.rest.domain.code.dto.request.UpdateCodeRequest
import healthiee.rest.domain.code.dto.toDto
import healthiee.rest.domain.code.entity.Code
import healthiee.rest.lib.error.ApiException
import healthiee.rest.lib.error.ApplicationErrorCode.NOT_FOUND_CODE
import healthiee.rest.domain.code.repository.CodeRepository
import healthiee.rest.lib.error.ApiException
import healthiee.rest.lib.error.ErrorCode.NOT_FOUND
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
Expand All @@ -29,12 +29,12 @@ class CodeService(

fun findById(id: Long): CodeDto {
return codeRepository.findByIdOrNull(id)?.toDto()
?: throw ApiException(NOT_FOUND_CODE)
?: throw ApiException(NOT_FOUND, "코드를 찾을 수 없습니다")
}

@Transactional
fun update(id: Long, request: UpdateCodeRequest) {
val findCode = codeRepository.findByIdOrNull(id) ?: throw ApiException(NOT_FOUND_CODE)
val findCode = codeRepository.findByIdOrNull(id) ?: throw ApiException(NOT_FOUND, "코드를 찾을 수 없습니다")
findCode.changeCode(request.name, request.active)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package healthiee.rest.lib.response
package healthiee.rest.domain.common.dto.base

import java.time.LocalDateTime

data class BaseResponse<T>(
data class Response<T>(
val code: Int,
val data: T? = null,
val message: String? = null,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package healthiee.rest.domain.common.dto
package healthiee.rest.domain.common.dto.media

import healthiee.rest.domain.common.entity.media.MediaType
import healthiee.rest.domain.post.entity.PostMedia
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package healthiee.rest.domain.follow.service

import healthiee.rest.domain.follow.entity.Follow
import healthiee.rest.domain.follow.repository.FollowQueryRepository
import healthiee.rest.domain.follow.repository.FollowRepository
import healthiee.rest.domain.member.entity.Member
import healthiee.rest.lib.error.ApiException
import healthiee.rest.lib.error.ApplicationErrorCode.BAD_REQUEST_ALREADY_EXIST_FOLLOW
import healthiee.rest.lib.error.ApplicationErrorCode.NOT_FOUND_FOLLOW
import healthiee.rest.domain.follow.repository.FollowRepository
import healthiee.rest.domain.follow.repository.FollowQueryRepository
import healthiee.rest.lib.error.ErrorCode.BAD_REQUEST
import healthiee.rest.lib.error.ErrorCode.NOT_FOUND
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

Expand All @@ -20,15 +20,15 @@ class FollowService(
@Transactional
fun follow(member: Member, targetMember: Member) {
val findFollow = queryRepository.findByMember(member.id, targetMember.id)
findFollow?.let { throw ApiException(BAD_REQUEST_ALREADY_EXIST_FOLLOW) }
findFollow?.let { throw ApiException(BAD_REQUEST, "이미 팔로우를 한 이력이 있습니다") }

followRepository.save(Follow.createFollow(member, targetMember))
}

@Transactional
fun unfollow(member: Member, targetMember: Member) {
val findFollow = queryRepository.findByMember(member.id, targetMember.id)
?: throw ApiException(NOT_FOUND_FOLLOW)
?: throw ApiException(NOT_FOUND, "팔로우한 이력이 없습니다")

findFollow.delete()
}
Expand Down
Loading

0 comments on commit 1a802c1

Please sign in to comment.