metatext/ServiceLayer/Sources/ServiceLayer/Entities/WebAuthSession.swift

53 lines
1.8 KiB
Swift
Raw Normal View History

2020-08-02 22:23:01 +00:00
// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
import AuthenticationServices
import Combine
2020-08-31 10:21:01 +00:00
public protocol WebAuthSession: AnyObject {
2020-08-02 22:23:01 +00:00
init(url URL: URL,
callbackURLScheme: String?,
completionHandler: @escaping WebAuthSessionCompletionHandler)
var presentationContextProvider: WebAuthPresentationContextProviding? { get set }
@discardableResult func start() -> Bool
}
2020-08-12 09:01:21 +00:00
extension WebAuthSession {
2020-08-02 22:23:01 +00:00
static func publisher(
url: URL,
callbackURLScheme: String?,
presentationContextProvider: WebAuthPresentationContextProviding) -> AnyPublisher<URL?, Error> {
Future<URL?, Error> { promise in
let webAuthSession = Self(
url: url,
callbackURLScheme: callbackURLScheme) { oauthCallbackURL, error in
if let error = error {
return promise(.failure(error))
}
return promise(.success(oauthCallbackURL))
}
webAuthSession.presentationContextProvider = presentationContextProvider
2020-09-01 07:33:49 +00:00
DispatchQueue.main.async {
webAuthSession.start()
}
2020-08-02 22:23:01 +00:00
}
.eraseToAnyPublisher()
}
}
class WebAuthSessionContextProvider: NSObject, ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
ASPresentationAnchor()
}
}
2020-08-31 10:21:01 +00:00
public typealias WebAuthSessionCompletionHandler = ASWebAuthenticationSession.CompletionHandler
public typealias WebAuthSessionError = ASWebAuthenticationSessionError
public typealias WebAuthPresentationContextProviding = ASWebAuthenticationPresentationContextProviding
public typealias LiveWebAuthSession = ASWebAuthenticationSession
2020-08-02 22:23:01 +00:00
2020-08-12 09:01:21 +00:00
extension LiveWebAuthSession: WebAuthSession {}