Skip to content

Commit

Permalink
Merge pull request #12 from DDD-Community/feature/POLABO-108
Browse files Browse the repository at this point in the history
feat(POLABO-107): mvp 2차 개발
  • Loading branch information
dldmsql authored Aug 8, 2024
2 parents f370540 + 8829ccd commit fe4df57
Show file tree
Hide file tree
Showing 13 changed files with 95 additions and 116 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.UUID

@Tag(name = "Board API", description = "보드 관련 API")
@RestController
Expand All @@ -26,14 +27,14 @@ class BoardController(
보드를 생성합니다.
userId는 추후 회원가입 기능이 추가될 것을 대비한 것입니다. 지금은 null로 주세요.
userId 타입을 UUID -> Long으로 변경하였습니다. - 2024.08.03
userId 데이터는 백에서 채울 것입니다.!
""")
@PostMapping
fun create(@RequestBody request : BoardCreateRequest)
= run {
: ApplicationResponse<UUID> {
val user = SecurityContextHolder.getContext().authentication.principal as UserDto.Companion.Res
request.userId = user.id
ApplicationResponse.ok(this.boardService.create(request))
return ApplicationResponse.ok(this.boardService.create(request))
}

@Operation(summary = "보드 조회", description = """
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ import com.ddd.sonnypolabobe.domain.board.my.service.MyBoardService
import com.ddd.sonnypolabobe.domain.user.dto.UserDto
import com.ddd.sonnypolabobe.global.entity.PageDto
import com.ddd.sonnypolabobe.global.response.ApplicationResponse
import com.ddd.sonnypolabobe.global.util.DateConverter.convertToKst
import io.swagger.v3.oas.annotations.Operation
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime

@RestController
@RequestMapping("/api/v1/my/boards")
Expand All @@ -20,23 +18,13 @@ class MyBoardController(private val myBoardService : MyBoardService) {
""")
@GetMapping
fun getMyBoards(
@RequestParam page : Int,
@RequestParam(name = "page", defaultValue = "0") page : Int,
@RequestParam size : Int
) = ApplicationResponse.ok(
PageDto(
content = listOf(
MyBoardDto.Companion.PageListRes(
id = 1L,
title = "보드 제목",
createdAt = convertToKst(LocalDateTime.now()),
totalCount = 1L
)
),
page = page,
size = size,
total = 10
)
)
) : ApplicationResponse<PageDto<MyBoardDto.Companion.PageListRes>> {
val user = SecurityContextHolder.getContext().authentication.principal as UserDto.Companion.Res
return ApplicationResponse.ok(this.myBoardService.getMyBoards(user.id, page, size))
}


@Operation(
summary = "내 보드 이름 수정",
Expand All @@ -48,10 +36,10 @@ class MyBoardController(private val myBoardService : MyBoardService) {
fun updateMyBoard(
@PathVariable id : String,
@RequestBody request : MyBoardDto.Companion.MBUpdateReq
) = run {
) : ApplicationResponse<Nothing> {
val userId = SecurityContextHolder.getContext().authentication.principal as UserDto.Companion.Res
this.myBoardService.updateMyBoard(id, request, userId.id)
ApplicationResponse.ok()
return ApplicationResponse.ok()
}

@Operation(
Expand All @@ -63,9 +51,9 @@ class MyBoardController(private val myBoardService : MyBoardService) {
@DeleteMapping("/{id}")
fun deleteMyBoard(
@PathVariable id : String
) = run {
) : ApplicationResponse<Nothing> {
val userId = SecurityContextHolder.getContext().authentication.principal as UserDto.Companion.Res
this.myBoardService.deleteMyBoard(id, userId.id)
ApplicationResponse.ok()
return ApplicationResponse.ok()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@ class MyBoardDto {
)

data class PageListRes(
val id: Long,
val id: UUID,
val title: String,
@DateTimeFormat(pattern = "yyyy-MM-dd", iso = DateTimeFormat.ISO.DATE)
val createdAt: LocalDateTime,
val totalCount: Long
)

data class GetOneRes(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package com.ddd.sonnypolabobe.domain.board.my.service

import com.ddd.sonnypolabobe.domain.board.my.dto.MyBoardDto
import com.ddd.sonnypolabobe.domain.board.repository.BoardJooqRepository
import com.ddd.sonnypolabobe.global.entity.PageDto
import com.ddd.sonnypolabobe.global.util.UuidConverter
import org.springframework.stereotype.Service
import sun.jvm.hotspot.debugger.Page

@Service
class MyBoardService(private val boardJooqRepository: BoardJooqRepository) {
Expand All @@ -24,4 +26,12 @@ class MyBoardService(private val boardJooqRepository: BoardJooqRepository) {
}
this.boardJooqRepository.delete(UuidConverter.stringToUUID(id))
}

fun getMyBoards(userId: Long, page: Int, size: Int): PageDto<MyBoardDto.Companion.PageListRes> {
val data = this.boardJooqRepository.findAllByUserId(userId, page, size)
val totalCount = this.boardJooqRepository.selectTotalCountByUserId(userId)
val totalPage = totalCount.toInt() / size + 1

return PageDto(data, totalCount, totalPage, size)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ interface BoardJooqRepository {
fun findById(id: UUID): MyBoardDto.Companion.GetOneRes?
fun updateTitle(id: UUID, title: String)
fun delete(id: UUID)
fun findAllByUserId(userId: Long, page: Int, size: Int): List<MyBoardDto.Companion.PageListRes>
fun selectTotalCountByUserId(userId: Long): Long
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,40 @@ class BoardJooqRepositoryImpl(
.where(jBoard.ID.eq(UuidConverter.uuidToByteArray(id)))
.execute()
}

override fun findAllByUserId(
userId: Long,
page: Int,
size: Int
): List<MyBoardDto.Companion.PageListRes> {
val jBoard = Board.BOARD
val data = this.dslContext.select(
jBoard.ID,
jBoard.TITLE,
jBoard.CREATED_AT
)
.from(jBoard)
.where(jBoard.USER_ID.eq(userId).and(jBoard.YN.eq(1)).and(jBoard.ACTIVEYN.eq(1)))
.orderBy(jBoard.CREATED_AT.desc())
.limit(size)
.offset(page * size)
.fetch()

return data.map {
MyBoardDto.Companion.PageListRes(
id = UuidConverter.byteArrayToUUID(it.get("id", ByteArray::class.java)!!),
title = it.get("title", String::class.java)!!,
createdAt = it.get("created_at", LocalDateTime::class.java)!!,
)
}
}

override fun selectTotalCountByUserId(userId: Long): Long {
val jBoard = Board.BOARD
return this.dslContext
.selectCount()
.from(jBoard)
.where(jBoard.USER_ID.eq(userId).and(jBoard.YN.eq(1)).and(jBoard.ACTIVEYN.eq(1)))
.fetchOne(0, Long::class.java) ?: 0L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import com.ddd.sonnypolabobe.domain.board.controller.dto.BoardCreateRequest
import com.ddd.sonnypolabobe.domain.board.controller.dto.BoardGetResponse
import com.ddd.sonnypolabobe.domain.board.repository.BoardJooqRepository
import com.ddd.sonnypolabobe.domain.polaroid.controller.dto.PolaroidGetResponse
import com.ddd.sonnypolabobe.global.exception.ApplicationException
import com.ddd.sonnypolabobe.global.exception.CustomErrorCode
import com.ddd.sonnypolabobe.global.util.S3Util
import com.ddd.sonnypolabobe.global.util.UuidConverter
import org.springframework.beans.factory.annotation.Value
Expand All @@ -17,9 +19,8 @@ class BoardService(
@Value("\${limit.count}")
private val limit: Int
) {
fun create(request: BoardCreateRequest): UUID? {
return this.boardJooqRepository.insertOne(request)?.let { UuidConverter.byteArrayToUUID(it) }
}
fun create(request: BoardCreateRequest): UUID = this.boardJooqRepository.insertOne(request)?.let { UuidConverter.byteArrayToUUID(it) }
?: throw ApplicationException(CustomErrorCode.BOARD_CREATED_FAILED)

fun getById(id: String): List<BoardGetResponse> {
return id.run {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.ddd.sonnypolabobe.domain.oauth.controller

import com.ddd.sonnypolabobe.domain.oauth.service.OauthService
import com.ddd.sonnypolabobe.domain.user.dto.UserDto
import com.ddd.sonnypolabobe.global.response.ApplicationResponse
import io.swagger.v3.oas.annotations.Operation
import org.springframework.http.HttpHeaders
Expand All @@ -11,17 +12,16 @@ import org.springframework.web.bind.annotation.*
@RequestMapping("/api/v1/oauth")
class OauthController(private val oauthService: OauthService) {

@Operation(summary = "카카오 소셜 로그인", description = """
카카오 소셜 로그인을 진행합니다.
인가 코드를 파라미터로 넘겨주세요.
@Operation(summary = "회원가입/로그인", description = """
회원가입/로그인을 진행합니다.
이미 가입된 회원이라면 로그인을 진행하고, 가입되지 않은 회원이라면 회원가입을 진행합니다.
""")
@GetMapping("/sign-in")
fun login(@RequestParam(name = "code") code : String) = ApplicationResponse.ok(this.oauthService.signIn(code))
@PostMapping("/sign-in")
fun signIn(@RequestBody request: UserDto.Companion.CreateReq)
= ApplicationResponse.ok(this.oauthService.signIn(request))

@PutMapping("/re-issue")
fun reIssue(
@RequestHeader(name = "Authorization", required = true) header: String
) = run {
ApplicationResponse.ok(this.oauthService.reIssue(header))
}
) = ApplicationResponse.ok(this.oauthService.reIssue(header))
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,75 +20,13 @@ import org.springframework.web.reactive.function.BodyInserters

@Service
class OauthService(
private val webClient : WebClientUtil,
private val objectMapper: ObjectMapper,
@Value("\${spring.security.oauth2.client.registration.kakao.client-id}") private val clientId : String,
@Value("\${spring.security.oauth2.client.registration.kakao.redirect-uri}") private val redirectUri : String,
@Value("\${spring.security.oauth2.client.registration.kakao.client-secret}") private val clientSecret : String,
private val userRepository : UserJooqRepository,
private val jwtUtil: JwtUtil,
private val userTokenRepository: UserTokenJooqRepository
) {

fun getAccessToken(code: String) : KakaoDto.Companion.Token {

//요청 본문
val params: MultiValueMap<String, String> = LinkedMultiValueMap()
params.add("grant_type", "authorization_code")
params.add("client_id", clientId)
params.add("redirect_uri", redirectUri)
params.add("code", code)
params.add("client_secret", clientSecret)

logger().error("params : $params")
// 요청 보내기 및 응답 수신
val response = webClient.create("https://kauth.kakao.com")
.post()
.uri("/oauth/token")
.header("Content-type", "application/x-www-form-urlencoded")
.body(BodyInserters.fromFormData(params))
.retrieve()
.bodyToMono(String::class.java)
.block()


return try {
this.objectMapper.readValue(response, KakaoDto.Companion.Token::class.java)
} catch (e: Exception) {
throw RuntimeException(e)
}
}

fun getKakaoInfo(accessToken: String): KakaoDto.Companion.UserInfo {

// 요청 보내기 및 응답 수신
val response = webClient.create("https://kapi.kakao.com")
.post()
.uri("/v2/user/me")
.header("Content-type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer $accessToken")
.retrieve()
.bodyToMono(String::class.java)
.block()

return try {
this.objectMapper.readValue(response, KakaoDto.Companion.UserInfo::class.java)
} catch (e: Exception) {
throw RuntimeException(e)
}
}

@Transactional
fun signIn(code: String): UserDto.Companion.TokenRes {
val token = getAccessToken(code)
val userInfo = getKakaoInfo(token.access_token)

// DB에 저장
val request = UserDto.Companion.CreateReq(
nickName = userInfo.kakao_account.profile.nickname,
email = userInfo.kakao_account.email
)

fun signIn(request: UserDto.Companion.CreateReq): UserDto.Companion.TokenRes {
this.userRepository.findByEmail(request.email)?.let {
val tokenRequest = UserDto.Companion.CreateTokenReq(
id = it.id,
Expand All @@ -112,8 +50,8 @@ class OauthService(
// 토큰 생성
val tokenRequest = UserDto.Companion.CreateTokenReq(
id = userId,
email = userInfo.kakao_account.email,
nickName = userInfo.kakao_account.profile.nickname
email = request.email,
nickName = request.nickName
)

val tokenRes = this.jwtUtil.generateAccessToken(tokenRequest)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,19 @@ class UserController(
""")
@PutMapping("/nickname")
fun updateNickname(@RequestBody request: UserDto.Companion.UpdateReq)
= run {
: ApplicationResponse<Nothing> {
val userInfoFromToken = SecurityContextHolder.getContext().authentication.principal as UserDto.Companion.Res
this.userService.updateProfile(request, userInfoFromToken.id)
ApplicationResponse.ok()
return ApplicationResponse.ok()
}

@Operation(summary = "프로필 조회", description = """
프로필을 조회합니다.
""")
@GetMapping("/profile")
fun getProfile() = run {
fun getProfile() : ApplicationResponse<UserDto.Companion.ProfileRes> {
val userInfoFromToken = SecurityContextHolder.getContext().authentication.principal as UserDto.Companion.Res
ApplicationResponse.ok(this.userService.findById(userInfoFromToken.id))
return ApplicationResponse.ok(this.userService.findById(userInfoFromToken.id))
}

@Operation(summary = "회원 탈퇴", description = """
Expand All @@ -47,9 +47,9 @@ class UserController(
사유가 '기타'인 경우에만 reason 필드를 채워주세요.
""")
@PutMapping("/withdraw")
fun withdraw(@RequestBody request: UserDto.Companion.WithdrawReq) = run {
fun withdraw(@RequestBody request: UserDto.Companion.WithdrawReq) : ApplicationResponse<Nothing> {
val userInfoFromToken = SecurityContextHolder.getContext().authentication.principal as UserDto.Companion.Res
this.userService.withdraw(request, userInfoFromToken.id)
ApplicationResponse.ok()
return ApplicationResponse.ok()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class SecurityConfig(
it.requestMatchers("/api/v1/file/**").permitAll()
it.requestMatchers("/api/v1/oauth/sign-in", "/api/v1/oauth/re-issue").permitAll()
it.requestMatchers("/health", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
it.requestMatchers("/api/v1/boards/{id}").permitAll()
it.requestMatchers("/api/v1/boards/{id}", "/api/v1/polaroids/{id}", "/api/v1/boards/{boardId}/polaroids").permitAll()
it.anyRequest().authenticated()
}
.exceptionHandling{
Expand Down
13 changes: 7 additions & 6 deletions src/main/kotlin/com/ddd/sonnypolabobe/global/entity/PageDto.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.ddd.sonnypolabobe.global.entity

data class PageDto(
val page: Int,
val size: Int,
val total: Int,
val content: List<Any>
)

data class PageDto<T>(
val data: List<T>,
val totalCount: Long,
val totalPage: Int,
val currentPage: Int
)
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,7 @@ enum class CustomErrorCode(
JWT_ILLEGAL_ARGUMENT(HttpStatus.UNAUTHORIZED, "JWT005", "잘못된 인자입니다."),
JWT_SIGNATURE(HttpStatus.UNAUTHORIZED, "JWT006", "잘못된 서명입니다."),

// board
BOARD_CREATED_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "BOARD001", "보드 생성에 실패했습니다."),

}

0 comments on commit fe4df57

Please sign in to comment.