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

Enable access for token refresh #31

Merged
merged 15 commits into from
Jun 10, 2022
Merged
Changes from 2 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
15 changes: 11 additions & 4 deletions Sources/Twift.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Combine
public class Twift: NSObject, ObservableObject {
/// The type of authentication access for this Twift instance
public private(set) var authenticationType: AuthenticationType
public private(set) var oauthUser: OAuth2User?
emin-grbo marked this conversation as resolved.
Show resolved Hide resolved

internal let decoder: JSONDecoder
internal let encoder: JSONEncoder
Expand Down Expand Up @@ -70,9 +71,11 @@ public class Twift: NSObject, ObservableObject {
return encoder
}

/// Refreshes the OAuth 2.0 token, optionally forcing a refresh even if the token is still valid
/// - Parameter onlyIfExpired: Set to false to force the token to refresh even if it hasn't yet expired.
public func refreshOAuth2AccessToken(onlyIfExpired: Bool = true) async throws {
/// Refreshes the OAuth 2.0 token, optionally forcing a refresh even if the token is still valid
/// - Parameters:
/// - onlyIfExpired: Set to false to force the token to refresh even if it hasn't yet expired.
/// - onRefresh: An optional callback method to be called after successful token refresh.
public func refreshOAuth2AccessToken(onlyIfExpired: Bool = true, onRefresh: ((OAuth2User)-> Void)? = nil) async throws {
emin-grbo marked this conversation as resolved.
Show resolved Hide resolved
guard case AuthenticationType.oauth2UserAuth(let oauthUser) = self.authenticationType else {
throw TwiftError.WrongAuthenticationType(needs: .oauth2UserAuth)
}
Expand Down Expand Up @@ -106,6 +109,10 @@ public class Twift: NSObject, ObservableObject {
var refreshedOAuthUser = try JSONDecoder().decode(OAuth2User.self, from: data)
refreshedOAuthUser.clientId = clientId

self.authenticationType = .oauth2UserAuth(refreshedOAuthUser)
self.authenticationType = .oauth2UserAuth(refreshedOAuthUser)
self.oauthUser = refreshedOAuthUser
emin-grbo marked this conversation as resolved.
Show resolved Hide resolved

guard let completion = onRefresh else { return }
completion(refreshedOAuthUser)
}
}