Skip to content

Commit

Permalink
feat: 인터셉터 구현(#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
sozohoy committed Mar 1, 2024
1 parent aac2807 commit 25b3aa6
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions SUWIKI/SUWIKI/Core/Network/Interceptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,23 @@ final class BaseInterceptor: RequestInterceptor {

let keychainManager = KeychainManager.shared


/// 변수에 urlRequest를 복사하지 말고 refresh 토큰일경우 그대로 한번 보내보자
func adapt(
_ urlRequest: URLRequest,
for session: Session,
completion: @escaping (Result<URLRequest, Error>) -> Void
) {
var request = urlRequest
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let accessToken = keychainManager.read(token: .AccessToken) {
request.setValue(accessToken, forHTTPHeaderField: "Authorization")
if request.url?.absoluteString.contains("/refresh") == false {
if let accessToken = keychainManager.read(token: .AccessToken) {
request.setValue(accessToken, forHTTPHeaderField: "Authorization")
}
} else {
if let refreshToken = keychainManager.read(token: .RefreshToken) {
request.setValue(refreshToken, forHTTPHeaderField: "Authorization")
}
}
completion(.success(request))
}
Expand All @@ -32,9 +40,12 @@ final class BaseInterceptor: RequestInterceptor {
dueTo error: Error,
completion: @escaping (RetryResult) -> Void
) {
guard let refreshToken = keychainManager.read(token: .RefreshToken), request.response?.statusCode == 401 else {
return completion(.doNotRetryWithError(error))
guard let refreshToken = keychainManager.read(token: .RefreshToken),
request.response?.statusCode == 401 else {
completion(.doNotRetryWithError(error))
return
}

let target = APITarget.User.refresh(DTO.RefreshRequest(authorization: refreshToken))
APIProvider.requestRefreshToken(DTO.RefreshResponse.self, target: target) { [weak self] response in
switch response.result {
Expand All @@ -44,8 +55,8 @@ final class BaseInterceptor: RequestInterceptor {
completion(.doNotRetry)
return
}
self.keychainManager.create(token: .AccessToken, value: tokens.accessToken)
self.keychainManager.create(token: .RefreshToken, value: tokens.refreshToken)
self.keychainManager.create(token: .AccessToken, value: tokens.AccessToken)
self.keychainManager.create(token: .RefreshToken, value: tokens.RefreshToken)
completion(.retry)
case .failure:
completion(.doNotRetryWithError(error))
Expand Down

0 comments on commit 25b3aa6

Please sign in to comment.