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

Release #316

Merged
merged 3 commits into from
Jan 10, 2025
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
7 changes: 6 additions & 1 deletion api/src/main/kotlin/filter/ErrorWebFilter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.wafflestudio.snu4t.filter

import com.fasterxml.jackson.databind.ObjectMapper
import com.wafflestudio.snu4t.common.exception.ErrorType
import com.wafflestudio.snu4t.common.exception.EvServiceProxyException
import com.wafflestudio.snu4t.common.exception.Snu4tException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
Expand All @@ -26,9 +27,13 @@ class ErrorWebFilter(
): Mono<Void> {
return chain.filter(exchange)
.onErrorResume { throwable ->
val errorBody: ErrorBody
val errorBody: Any
val httpStatusCode: HttpStatusCode
when (throwable) {
is EvServiceProxyException -> {
httpStatusCode = throwable.statusCode
errorBody = throwable.errorBody
}
is Snu4tException -> {
httpStatusCode = throwable.error.httpStatus
errorBody = makeErrorBody(throwable)
Expand Down
6 changes: 6 additions & 0 deletions api/src/main/kotlin/handler/AuthHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ class AuthHandler(
userService.loginKakao(socialLoginRequest)
}

suspend fun loginAppleLegacy(req: ServerRequest): ServerResponse =
handle(req) {
val socialLoginRequest: SocialLoginRequest = req.awaitBodyOrNull() ?: throw ServerWebInputException("Invalid body")
userService.loginApple(socialLoginRequest)
}

suspend fun loginApple(req: ServerRequest): ServerResponse =
handle(req) {
val socialLoginRequest: SocialLoginRequest = req.awaitBodyOrNull() ?: throw ServerWebInputException("Invalid body")
Expand Down
44 changes: 44 additions & 0 deletions api/src/main/kotlin/handler/EvServiceHandler.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.wafflestudio.snu4t.handler

import com.wafflestudio.snu4t.evaluation.service.EvService
import com.wafflestudio.snu4t.middleware.SnuttRestApiDefaultMiddleware
import kotlinx.coroutines.reactor.awaitSingleOrNull
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.bodyToMono

@Component
class EvServiceHandler(
private val evService: EvService,
snuttRestApiDefaultMiddleware: SnuttRestApiDefaultMiddleware,
) : ServiceHandler(snuttRestApiDefaultMiddleware) {
suspend fun handleGet(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.GET)
}

suspend fun handlePost(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.POST)
}

suspend fun handleDelete(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.DELETE)
}

suspend fun handlePatch(req: ServerRequest) =
handle(req) {
val body = req.bodyToMono<String>().awaitSingleOrNull() ?: ""
evService.handleRouting(req.userId, req.pathVariable("requestPath"), req.queryParams(), body, HttpMethod.PATCH)
}

suspend fun getMyLatestLectures(req: ServerRequest) =
handle(req) {
evService.getMyLatestLectures(req.userId, req.queryParams())
}
}
13 changes: 13 additions & 0 deletions api/src/main/kotlin/handler/UserHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,13 @@ class UserHandler(
userService.attachSocial(user, socialLoginRequest, AuthProvider.KAKAO)
}

suspend fun attachApple(req: ServerRequest): ServerResponse =
handle(req) {
val user = req.getContext().user!!
val socialLoginRequest: SocialLoginRequest = req.awaitBody()
userService.attachSocial(user, socialLoginRequest, AuthProvider.APPLE)
}

suspend fun detachFacebook(req: ServerRequest): ServerResponse =
handle(req) {
val user = req.getContext().user!!
Expand All @@ -141,6 +148,12 @@ class UserHandler(
userService.detachSocial(user, AuthProvider.KAKAO)
}

suspend fun detachApple(req: ServerRequest): ServerResponse =
handle(req) {
val user = req.getContext().user!!
userService.detachSocial(user, AuthProvider.APPLE)
}

suspend fun checkAuthProviders(req: ServerRequest): ServerResponse =
handle(req) {
val user = req.getContext().user!!
Expand Down
15 changes: 15 additions & 0 deletions api/src/main/kotlin/router/MainRouter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.wafflestudio.snu4t.handler.ConfigHandler
import com.wafflestudio.snu4t.handler.CoursebookHandler
import com.wafflestudio.snu4t.handler.DeviceHandler
import com.wafflestudio.snu4t.handler.EvHandler
import com.wafflestudio.snu4t.handler.EvServiceHandler
import com.wafflestudio.snu4t.handler.FeedbackHandler
import com.wafflestudio.snu4t.handler.FriendHandler
import com.wafflestudio.snu4t.handler.FriendTableHandler
Expand Down Expand Up @@ -68,6 +69,7 @@ class MainRouter(
private val tagHandler: TagHandler,
private val feedbackHandler: FeedbackHandler,
private val staticPageHandler: StaticPageHandler,
private val evServiceHandler: EvServiceHandler,
) {
@Bean
fun healthCheck() =
Expand All @@ -86,6 +88,7 @@ class MainRouter(
POST("/login/facebook", authHandler::loginFacebook)
POST("/login/google", authHandler::loginGoogle)
POST("/login/kakao", authHandler::loginKakao)
POST("/login_apple", authHandler::loginAppleLegacy)
POST("/login/apple", authHandler::loginApple)
POST("/logout", authHandler::logout)
POST("/password/reset/email/check", authHandler::getMaskedEmail)
Expand Down Expand Up @@ -114,9 +117,11 @@ class MainRouter(
POST("/facebook", userHandler::attachFacebook)
POST("/google", userHandler::attachGoogle)
POST("/kakao", userHandler::attachKakao)
POST("/apple", userHandler::attachApple)
DELETE("/facebook", userHandler::detachFacebook)
DELETE("/google", userHandler::detachGoogle)
DELETE("/kakao", userHandler::detachKakao)
DELETE("/apple", userHandler::detachApple)
}
"/users".nest {
GET("/me", userHandler::getUserMe)
Expand Down Expand Up @@ -296,6 +301,16 @@ class MainRouter(
GET("/ev/lectures/{lectureId}/summary", evHandler::getLectureEvaluationSummary)
}

@Bean
fun evServiceRouter() =
v1CoRouter {
GET("/ev-service/v1/users/me/lectures/latest", evServiceHandler::getMyLatestLectures)
GET("/ev-service/{*requestPath}", evServiceHandler::handleGet)
POST("/ev-service/{*requestPath}", evServiceHandler::handlePost)
DELETE("/ev-service/{*requestPath}", evServiceHandler::handleDelete)
PATCH("/ev-service/{*requestPath}", evServiceHandler::handlePatch)
}

@Bean
@CoursebookDocs
fun coursebookRouter() =
Expand Down
24 changes: 24 additions & 0 deletions api/src/main/kotlin/router/docs/AuthDocs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,30 @@ import org.springframework.web.bind.annotation.RequestMethod
],
),
),
RouterOperation(
path = "/v1/auth/login/apple",
method = [RequestMethod.POST],
produces = [MediaType.APPLICATION_JSON_VALUE],
operation =
Operation(
operationId = "loginApple",
requestBody =
RequestBody(
content = [
Content(
schema = Schema(implementation = SocialLoginRequest::class),
mediaType = MediaType.APPLICATION_JSON_VALUE,
),
],
),
responses = [
ApiResponse(
responseCode = "200",
content = [Content(schema = Schema(implementation = LoginResponse::class))],
),
],
),
),
RouterOperation(
path = "/v1/auth/logout",
method = [RequestMethod.POST],
Expand Down
39 changes: 39 additions & 0 deletions api/src/main/kotlin/router/docs/UserDocs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,30 @@ import org.springframework.web.bind.annotation.RequestMethod
],
),
),
RouterOperation(
path = "/v1/user/apple",
method = [RequestMethod.POST],
produces = [MediaType.APPLICATION_JSON_VALUE],
operation =
Operation(
operationId = "attachApple",
requestBody =
RequestBody(
content = [
Content(
schema = Schema(implementation = SocialLoginRequest::class),
mediaType = MediaType.APPLICATION_JSON_VALUE,
),
],
),
responses = [
ApiResponse(
responseCode = "200",
content = [Content(schema = Schema(implementation = TokenResponse::class))],
),
],
),
),
RouterOperation(
path = "/v1/user/facebook",
method = [RequestMethod.DELETE],
Expand Down Expand Up @@ -364,5 +388,20 @@ import org.springframework.web.bind.annotation.RequestMethod
],
),
),
RouterOperation(
path = "/v1/user/apple",
method = [RequestMethod.DELETE],
produces = [MediaType.APPLICATION_JSON_VALUE],
operation =
Operation(
operationId = "detachApple",
responses = [
ApiResponse(
responseCode = "200",
content = [Content(schema = Schema(implementation = TokenResponse::class))],
),
],
),
),
)
annotation class UserDocs
2 changes: 2 additions & 0 deletions api/src/test/kotlin/timetable/TimetableIntegTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.wafflestudio.snu4t.timetable
import BaseIntegTest
import com.ninjasquad.springmockk.MockkBean
import com.wafflestudio.snu4t.evaluation.repository.SnuttEvRepository
import com.wafflestudio.snu4t.evaluation.service.EvService
import com.wafflestudio.snu4t.fixture.TimetableFixture
import com.wafflestudio.snu4t.fixture.UserFixture
import com.wafflestudio.snu4t.handler.RequestContext
Expand All @@ -25,6 +26,7 @@ import timetables.dto.TimetableBriefDto
class TimetableIntegTest(
@MockkBean private val mockMiddleware: SnuttRestApiDefaultMiddleware,
@MockkBean private val mockSnuttEvRepository: SnuttEvRepository,
@MockkBean private val evService: EvService,
val mainRouter: MainRouter,
val timetableFixture: TimetableFixture,
val userFixture: UserFixture,
Expand Down
25 changes: 21 additions & 4 deletions core/src/main/kotlin/auth/apple/AppleClient.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.wafflestudio.snu4t.auth.apple

import com.fasterxml.jackson.databind.ObjectMapper
import com.wafflestudio.snu4t.auth.OAuth2Client
import com.wafflestudio.snu4t.auth.OAuth2UserResponse
import com.wafflestudio.snu4t.common.exception.InvalidAppleLoginTokenException
import com.wafflestudio.snu4t.common.extension.get
import io.jsonwebtoken.Jwts
import org.springframework.http.client.reactive.ReactorClientHttpConnector
Expand All @@ -18,6 +20,7 @@ import java.util.Base64
@Component("APPLE")
class AppleClient(
webClientBuilder: WebClient.Builder,
private val objectMapper: ObjectMapper,
) : OAuth2Client {
private val webClient =
webClientBuilder.clientConnector(
Expand All @@ -35,9 +38,9 @@ class AppleClient(
override suspend fun getMe(token: String): OAuth2UserResponse? {
val jwtHeader = extractJwtHeader(token)
val appleJwk =
webClient.get<List<AppleJwk>>(uri = APPLE_JWK_URI).getOrNull()
?.find {
it.kid == jwtHeader.keyId && it.alg == jwtHeader.algorithm
webClient.get<Map<String, List<AppleJwk>>>(uri = APPLE_JWK_URI).getOrNull()
?.get("keys")?.find {
it.kid == jwtHeader.kid && it.alg == jwtHeader.alg
} ?: return null
val publicKey = convertJwkToPublicKey(appleJwk)
val jwtPayload = verifyAndDecodeToken(token, publicKey)
Expand All @@ -51,7 +54,16 @@ class AppleClient(
)
}

private suspend fun extractJwtHeader(token: String) = Jwts.parser().parseClaimsJws(token).header
private suspend fun extractJwtHeader(token: String): AppleJwtHeader {
val headerJson = Base64.getDecoder().decode(token.substringBefore(".")).toString(Charsets.UTF_8)
val headerMap = objectMapper.readValue(headerJson, Map::class.java)
val kid = headerMap["kid"] as? String ?: throw InvalidAppleLoginTokenException
val alg = headerMap["alg"] as? String ?: throw InvalidAppleLoginTokenException
return AppleJwtHeader(
kid = kid,
alg = alg,
)
}

private suspend fun convertJwkToPublicKey(jwk: AppleJwk): PublicKey {
val modulus = BigInteger(1, Base64.getUrlDecoder().decode(jwk.n))
Expand All @@ -65,3 +77,8 @@ class AppleClient(
publicKey: PublicKey,
) = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).body
}

private data class AppleJwtHeader(
val kid: String,
val alg: String,
)
1 change: 1 addition & 0 deletions core/src/main/kotlin/common/exception/ErrorType.kt
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ enum class ErrorType(
UPDATE_APP_VERSION(HttpStatus.BAD_REQUEST, 40021, "앱 버전을 업데이트해주세요.", "앱 버전을 업데이트해주세요."),

SOCIAL_CONNECT_FAIL(HttpStatus.UNAUTHORIZED, 40100, "소셜 로그인에 실패했습니다.", "소셜 로그인에 실패했습니다."),
INVALID_APPLE_LOGIN_TOKEN(HttpStatus.UNAUTHORIZED, 40101, "유효하지 않은 애플 로그인 토큰입니다.", "소셜 로그인에 실패했습니다."),

TIMETABLE_NOT_FOUND(HttpStatus.NOT_FOUND, 40400, "timetable_id가 유효하지 않습니다", "존재하지 않는 시간표입니다."),
PRIMARY_TIMETABLE_NOT_FOUND(HttpStatus.NOT_FOUND, 40401, "timetable_id가 유효하지 않습니다", "대표 시간표가 존재하지 않습니다."),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.wafflestudio.snu4t.common.exception

import org.springframework.http.HttpStatusCode

class EvServiceProxyException(
val statusCode: HttpStatusCode,
val errorBody: Map<String, Any?>,
) : RuntimeException()
2 changes: 2 additions & 0 deletions core/src/main/kotlin/common/exception/Snu4tException.kt
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ object UpdateAppVersionException : Snu4tException(ErrorType.UPDATE_APP_VERSION)

object SocialConnectFailException : Snu4tException(ErrorType.SOCIAL_CONNECT_FAIL)

object InvalidAppleLoginTokenException : Snu4tException(ErrorType.INVALID_APPLE_LOGIN_TOKEN)

object NoUserFcmKeyException : Snu4tException(ErrorType.NO_USER_FCM_KEY)

object InvalidRegistrationForPreviousSemesterCourseException :
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ interface CoursebookRepository : CoroutineCrudRepository<Coursebook, String> {
suspend fun findFirstByOrderByYearDescSemesterDesc(): Coursebook

suspend fun findAllByOrderByYearDescSemesterDesc(): List<Coursebook>

suspend fun findTop3ByOrderByYearDescSemesterDesc(): List<Coursebook>
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ interface CoursebookService {
suspend fun getLatestCoursebook(): Coursebook

suspend fun getCoursebooks(): List<Coursebook>

suspend fun getLastTwoCourseBooksBeforeCurrent(): List<Coursebook>
}

@Service
class CoursebookServiceImpl(private val coursebookRepository: CoursebookRepository) : CoursebookService {
override suspend fun getLatestCoursebook(): Coursebook = coursebookRepository.findFirstByOrderByYearDescSemesterDesc()

override suspend fun getCoursebooks(): List<Coursebook> = coursebookRepository.findAllByOrderByYearDescSemesterDesc()

override suspend fun getLastTwoCourseBooksBeforeCurrent(): List<Coursebook> =
coursebookRepository.findTop3ByOrderByYearDescSemesterDesc().slice(
1..2,
)
}
25 changes: 25 additions & 0 deletions core/src/main/kotlin/evaluation/dto/EvLectureInfoDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.wafflestudio.snu4t.evaluation.dto

import com.fasterxml.jackson.annotation.JsonProperty
import com.wafflestudio.snu4t.common.enum.Semester
import com.wafflestudio.snu4t.timetables.data.TimetableLecture

data class EvLectureInfoDto(
val year: Int,
val semester: Int,
val instructor: String?,
@JsonProperty("course_number")
val courseNumber: String?,
)

fun EvLectureInfoDto(
timetableLecture: TimetableLecture,
year: Int,
semester: Semester,
): EvLectureInfoDto =
EvLectureInfoDto(
year = year,
semester = semester.value,
instructor = timetableLecture.instructor,
courseNumber = timetableLecture.courseNumber,
)
Loading
Loading