Skip to content

Commit

Permalink
[#73] 토큰 재발급 구현중,,(어려움)
Browse files Browse the repository at this point in the history
  • Loading branch information
00yhsp committed Feb 15, 2024
1 parent 31d7755 commit 717abe0
Show file tree
Hide file tree
Showing 9 changed files with 174 additions and 21 deletions.
8 changes: 8 additions & 0 deletions Spon-us.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@
DF498F2C2B7CDDB200ADE078 /* MyAnnouncementsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF498F2B2B7CDDB200ADE078 /* MyAnnouncementsViewModel.swift */; };
DF498F2E2B7DF4F600ADE078 /* LogoutModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF498F2D2B7DF4F500ADE078 /* LogoutModel.swift */; };
DF498F302B7DF50200ADE078 /* LogoutViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF498F2F2B7DF50200ADE078 /* LogoutViewModel.swift */; };
DF692B162B7E39BD00BF9B75 /* RefreshTokenManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF692B152B7E39BD00BF9B75 /* RefreshTokenManager.swift */; };
DF692B182B7E3DA700BF9B75 /* RefreshTokenModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF692B172B7E3DA700BF9B75 /* RefreshTokenModel.swift */; };
DF90A5AB2B64EB5500BC54D0 /* TermsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF90A5AA2B64EB5500BC54D0 /* TermsView.swift */; };
DF90A5AD2B664E5A00BC54D0 /* ProcessingPolicyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF90A5AC2B664E5A00BC54D0 /* ProcessingPolicyView.swift */; };
DF90A5B02B664E9600BC54D0 /* GatherAndUsageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF90A5AF2B664E9600BC54D0 /* GatherAndUsageView.swift */; };
Expand Down Expand Up @@ -208,6 +210,8 @@
DF498F2B2B7CDDB200ADE078 /* MyAnnouncementsViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MyAnnouncementsViewModel.swift; sourceTree = "<group>"; };
DF498F2D2B7DF4F500ADE078 /* LogoutModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogoutModel.swift; sourceTree = "<group>"; };
DF498F2F2B7DF50200ADE078 /* LogoutViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogoutViewModel.swift; sourceTree = "<group>"; };
DF692B152B7E39BD00BF9B75 /* RefreshTokenManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefreshTokenManager.swift; sourceTree = "<group>"; };
DF692B172B7E3DA700BF9B75 /* RefreshTokenModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefreshTokenModel.swift; sourceTree = "<group>"; };
DF90A5AA2B64EB5500BC54D0 /* TermsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TermsView.swift; sourceTree = "<group>"; };
DF90A5AC2B664E5A00BC54D0 /* ProcessingPolicyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProcessingPolicyView.swift; sourceTree = "<group>"; };
DF90A5AF2B664E9600BC54D0 /* GatherAndUsageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GatherAndUsageView.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -302,6 +306,7 @@
10025B422B7C139300DCCC5A /* ReceivedOffer */,
10025B352B7B7B8700DCCC5A /* SendOffer */,
107D6E672B7A821D005B6261 /* MyPage */,
DF692B172B7E3DA700BF9B75 /* RefreshTokenModel.swift */,
);
path = Model;
sourceTree = "<group>";
Expand Down Expand Up @@ -515,6 +520,7 @@
3B81BCBD2B62312C0067E9CB /* Product.storekit */,
3B81BCBF2B6231680067E9CB /* ProductList.plist */,
DF498F262B79B45D00ADE078 /* KeyChainManager.swift */,
DF692B152B7E39BD00BF9B75 /* RefreshTokenManager.swift */,
);
path = Manager;
sourceTree = "<group>";
Expand Down Expand Up @@ -723,6 +729,7 @@
100D38B62B4EF51E00498977 /* SavedView.swift in Sources */,
80FA31692B5EB9490076453B /* NewPostView.swift in Sources */,
100D38B82B4EF54100498977 /* CategoryView.swift in Sources */,
DF692B162B7E39BD00BF9B75 /* RefreshTokenManager.swift in Sources */,
3BD26D062B62342C0035FE80 /* ChargerInfoView.swift in Sources */,
3BFC8D1B2B54D46D000D6006 /* MultiImagePicker.swift in Sources */,
3B36F0A62B6FEC2F0000ACFB /* Order.swift in Sources */,
Expand Down Expand Up @@ -756,6 +763,7 @@
100A1E322B73485800AAC1E8 /* SponusAPI.swift in Sources */,
807BF83F2B51BCD400A659B9 /* SearchView.swift in Sources */,
806AF86A2B79DBD0008F7F62 /* CategoryModel.swift in Sources */,
DF692B182B7E3DA700BF9B75 /* RefreshTokenModel.swift in Sources */,
DF90A5AB2B64EB5500BC54D0 /* TermsView.swift in Sources */,
DF498F272B79B45D00ADE078 /* KeyChainManager.swift in Sources */,
3B36F0A12B6FEBF60000ACFB /* Utils.swift in Sources */,
Expand Down
60 changes: 60 additions & 0 deletions Spon-us/Helper/Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import Foundation
import UIKit
import SwiftUI
import Alamofire
import Moya

extension UINavigationController: ObservableObject, UIGestureRecognizerDelegate {
override open func viewDidLoad() {
Expand Down Expand Up @@ -126,3 +128,61 @@ func changeToKorean(category: String? = nil, type: String? = nil) -> String? {
}
return nil
}

//final class AuthInterceptor: RequestInterceptor {
//
// static let shared = AuthInterceptor()
// let provider = MoyaProvider<SponusAPI>(plugins: [NetworkLoggerPlugin()])
// private init() {}
//
// func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
//// guard urlRequest.url?.absoluteString.hasPrefix(Config.baseURL) == true,
//// let accessToken = UserManager.shared.accessToken,
//// let refreshToken = UserManager.shared.refreshToken
//// else {
//// completion(.success(urlRequest))
//// return
//// }
////
//// var urlRequest = urlRequest
//// urlRequest.setValue(accessToken, forHTTPHeaderField: "accessToken")
//// urlRequest.setValue(refreshToken, forHTTPHeaderField: "refreshToken")
//// print("adator 적용 \(urlRequest.headers)")
// print("adapt")
// completion(.success(urlRequest))
// }
//
// func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
// print("retry 진입")
// guard let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401
// else {
// completion(.doNotRetryWithError(error))
// return
// }
//
//
// provider.request(.getRenewToken) { result in
// switch result {
// case let .success(response):
// switch response.statusCode {
// case 200:
// print(response.statusCode)
// print("success")
// let renewResponse = try? response.map(RefreshTokenModel200.self)
// saveAccessToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "userID Error", accessToken: renewResponse?.content.accessToken ?? "renewAccessTokenError")
// saveRefreshToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "userID Error", refreshToken: renewResponse?.content.refreshToken ?? "renewRefreshTokenError")
// print(renewResponse as Any)
// completion(.retry)
// default:
// print("failed")
// print("token renew error")
// print(response.statusCode)
// print(response.data)
// }
// case let .failure(response):
// completion(.doNotRetryWithError(error))
// }
// }
// }
//}
//
37 changes: 37 additions & 0 deletions Spon-us/Manager/RefreshTokenManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//
// RefreshTokenManager.swift
// Spon-us
//
// Created by 박현수 on 2/15/24.
//

import Foundation
import Moya

func renewToken() {
let provider = MoyaProvider<SponusAPI>(plugins: [NetworkLoggerPlugin()])

provider.request(.getRenewToken) { result in
switch result {
case let .success(response):
switch response.statusCode {
case 200:
print(response.statusCode)
print("success")
let renewResponse = try? response.map(RefreshTokenModel200.self)
saveAccessToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "userID Error", accessToken: renewResponse?.content.accessToken ?? "renewAccessTokenError")
saveRefreshToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "userID Error", refreshToken: renewResponse?.content.refreshToken ?? "renewRefreshTokenError")
print(renewResponse as Any)

default:
print("failed")
print("token renew error")
print(response.statusCode)
print(response.data)
}
case let .failure(response):
print(response.errorDescription)
print("renew error")
}
}
}
32 changes: 18 additions & 14 deletions Spon-us/Model/Portfolio/MyAnnouncementsViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,28 @@ class MyAnnouncementsViewModel: ObservableObject {
provider.request(.getMyAnnouncements) { result in
switch result {
case .success(let response):
if let jsonString = String(data: response.data, encoding: .utf8) {
print("서버 응답 JSON 데이터: \(jsonString)")
}

do {
let myAnnouncements = try JSONDecoder().decode(MyAnnouncementsModel.self, from: response.data)
DispatchQueue.main.async {
self.myAnnouncementsContents = myAnnouncements.content
self.isLoading = false
print(self.myAnnouncementsContents)
}
} catch {
print("JSON 디코딩 오류: \(error)")
print(response.statusCode)
if response.data.isEmpty {
renewToken()
}
print(response.data)
if let jsonString = String(data: response.data, encoding: .utf8) {
print("서버 응답 JSON 데이터: \(jsonString)")
}
do {
let myAnnouncements = try JSONDecoder().decode(MyAnnouncementsModel.self, from: response.data)
DispatchQueue.main.async {
self.myAnnouncementsContents = myAnnouncements.content
self.isLoading = false
print(self.myAnnouncementsContents)
}
} catch {
print("JSON 디코딩 오류: \(error)")
}
case .failure(let error):
print(error)
}
}
}

}
21 changes: 21 additions & 0 deletions Spon-us/Model/RefreshTokenModel.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//
// RefreshTokenModel.swift
// Spon-us
//
// Created by 박현수 on 2/15/24.
//

import Foundation

struct RefreshTokenContent: Codable {
let accessToken, refreshToken: String
}

struct RefreshTokenModel200: Codable {
let statusCode, message: String
let content: RefreshTokenContent
}

struct RefreshTokenModel401: Codable {
let statusCode, message: String
}
19 changes: 18 additions & 1 deletion Spon-us/SponusAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ enum SponusAPI {
case getOrganization(organizationId: Int)
case getReceived(announcementId: Int)
case getMyAnnouncements
case getRenewToken
}

extension SponusAPI: TargetType {
Expand Down Expand Up @@ -62,7 +63,8 @@ extension SponusAPI: TargetType {
return "/api/v1/proposes/received"
case .getMyAnnouncements:
return "/api/v1/announcements/me/opened"

case .getRenewToken:
return "/api/v1/auth/reissue"
}
}

Expand Down Expand Up @@ -96,6 +98,8 @@ extension SponusAPI: TargetType {
return .get
case .getMyAnnouncements:
return .get
case .getRenewToken:
return .get
}
}

Expand Down Expand Up @@ -160,6 +164,8 @@ extension SponusAPI: TargetType {
return Data()
case .getMyAnnouncements:
return Data()
case .getRenewToken:
return Data()
}
}

Expand Down Expand Up @@ -253,6 +259,8 @@ extension SponusAPI: TargetType {
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
case .getMyAnnouncements:
return .requestPlain
case .getRenewToken:
return .requestPlain
}
}

Expand Down Expand Up @@ -291,6 +299,15 @@ extension SponusAPI: TargetType {
return ["Authorization": "Bearer \(loadAccessToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "loadAccessToken Error"))"]
case .getMyAnnouncements:
return ["Authorization": "Bearer \(loadAccessToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "loadAccessToken Error"))"]
case .getRenewToken:
return ["Authorization": "Bearer \(loadAccessToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "loadAccessToken Error"))",
"RefreshToken": "\(loadRefreshToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? "loadRefreshToken Error"))"]
}
}
}

//extension SponusAPI {
// var validationType: ValidationType {
// return .successCodes
// }
//}
4 changes: 4 additions & 0 deletions Spon-us/View/Home/HomeView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,10 @@ struct HomeView: View {
notificationItem
})
.font(.English03)
.onAppear() {
print("Access: \(loadAccessToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? ""))")
print("Access: \(loadRefreshToken(userID: UserDefaults.standard.string(forKey: "loginAccount") ?? ""))")
}
}
}
}
8 changes: 4 additions & 4 deletions Spon-us/View/Portfolio/Portfolio.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ struct Portfolio: View {
@State var activeToProgressingDetail = false
@State var activeToCompletedDetail = false

@State private var currentDialogID = 0
@State private var currentConfirmationDialogID: UUID?
@State private var currentToTopID: UUID?
@State private var currentProgressingID: UUID?
Expand Down Expand Up @@ -473,12 +474,14 @@ struct Portfolio: View {

Button() {
showingPublishingConfirmationDialog = true
currentDialogID = cell.id
// currentConfirmationDialogID = dummy.id
} label: {
Image(.icMore).resizable().frame(width: 40, height: 40).border(.sponusGrey100)
}
.confirmationDialog("ic_more", isPresented: $showingPublishingConfirmationDialog, titleVisibility: .hidden, actions: {
Button("수정하기") {

activeNavLinkToEdit = true
showingPublishingConfirmationDialog = false

Expand Down Expand Up @@ -535,9 +538,6 @@ struct Portfolio: View {
}
)
}



}
}
}.scrollIndicators(.hidden)
Expand Down Expand Up @@ -848,7 +848,7 @@ struct Portfolio: View {
// if let index = dummyData.firstIndex(where: { $0.id == currentConfirmationDialogID }) {
// ModifyView(post: dummyData[index])
// }
EditPostView(popup: .constant(false))
EditPostView(announcementID: currentDialogID, popup: .constant(false))
}
.navigationDestination(isPresented: $activeNavLinkToMakeReport) {
MakeReportView(rootIsActive: self.$rootIsActive)
Expand Down
6 changes: 4 additions & 2 deletions Spon-us/View/ReceivedOffer/EditPostView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import SwiftUI
import PhotosUI

struct EditPostView: View {

@State var announcementID: Int?
@State private var postTitle = ""
@State private var selectedImages: [UIImage] = []
@State private var postSelectedCategory = ""
Expand All @@ -31,7 +31,7 @@ struct EditPostView: View {
VStack(spacing: 0) {
ScrollView {
VStack(alignment: .leading, spacing: 16){

SponUsPostCell(text: "공고 제목", isComplete: $postTitle)

TextField("ex. 스포대학교 대학생 협찬", text: $postTitle)
Expand Down Expand Up @@ -132,6 +132,8 @@ struct EditPostView: View {
.navigationBarItems(leading: CustomBackButton())
.onDisappear{
print("disappear")
}.onAppear() {
print(announcementID as Any)
}
// }
}
Expand Down

0 comments on commit 717abe0

Please sign in to comment.