66 lines
2.7 KiB
Swift
66 lines
2.7 KiB
Swift
//
|
|
// LoginController.swift
|
|
// MastoSearchCore
|
|
//
|
|
// Created by Shadowfacts on 7/3/22.
|
|
//
|
|
|
|
import Foundation
|
|
import AuthenticationServices
|
|
|
|
public class LoginController {
|
|
private init() {}
|
|
|
|
public static let shared = LoginController()
|
|
|
|
private var authSession: ASWebAuthenticationSession?
|
|
|
|
public func logIn(with instanceURL: URL, presentationContextProvider: ASWebAuthenticationPresentationContextProviding, completion: @escaping () -> Void) {
|
|
LocalData.account = LocalData.AccountInfo(instanceURL: instanceURL, clientID: nil, clientSecret: nil, accessToken: nil)
|
|
|
|
APIController.shared.register { response in
|
|
guard case .success(let registration) = response else {
|
|
fatalError()
|
|
}
|
|
|
|
LocalData.account!.clientID = registration.client_id
|
|
LocalData.account!.clientSecret = registration.client_secret
|
|
|
|
var authorizeComponents = URLComponents(url: instanceURL, resolvingAgainstBaseURL: false)!
|
|
authorizeComponents.path = "/oauth/authorize"
|
|
authorizeComponents.queryItems = [
|
|
URLQueryItem(name: "client_id", value: LocalData.account!.clientID),
|
|
URLQueryItem(name: "response_type", value: "code"),
|
|
URLQueryItem(name: "scope", value: APIController.shared.scopes),
|
|
URLQueryItem(name: "redirect_uri", value: APIController.shared.redirectURI),
|
|
]
|
|
|
|
self.authSession = ASWebAuthenticationSession(url: authorizeComponents.url!, callbackURLScheme: "mastosearch", completionHandler: { url, error in
|
|
guard error == nil,
|
|
let url = url,
|
|
let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
|
|
let item = components.queryItems?.first(where: { $0.name == "code" }),
|
|
let authCode = item.value else {
|
|
fatalError()
|
|
}
|
|
|
|
APIController.shared.getAccessToken(authCode: authCode) { response in
|
|
guard case .success(let settings) = response else {
|
|
fatalError()
|
|
}
|
|
|
|
LocalData.account!.accessToken = settings.access_token
|
|
|
|
DispatchQueue.main.async {
|
|
completion()
|
|
}
|
|
}
|
|
})
|
|
DispatchQueue.main.async {
|
|
self.authSession!.presentationContextProvider = presentationContextProvider
|
|
self.authSession!.start()
|
|
}
|
|
}
|
|
}
|
|
}
|