AuthorizationManager.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import AuthenticationServices
  2. import Combine
  3. import Swinject
  4. protocol AuthorizationManager {
  5. var isAuthorized: Bool { get }
  6. var authorizationPublisher: AnyPublisher<Bool, Never> { get }
  7. func authorize(credentials: ASAuthorizationAppleIDCredential) -> AnyPublisher<Void, Never>
  8. func logout()
  9. }
  10. final class BaseAuthorizationManager: AuthorizationManager, Injectable {
  11. private let isAuthorizedSubject = CurrentValueSubject<Bool, Never>(false)
  12. var authorizationPublisher: AnyPublisher<Bool, Never> { isAuthorizedSubject.eraseToAnyPublisher() }
  13. var isAuthorized: Bool { isAuthorizedSubject.value }
  14. private var lifetime = Set<AnyCancellable>()
  15. @Injected() private var keychain: Keychain!
  16. init(resolver: Resolver) {
  17. injectServices(resolver)
  18. }
  19. func authorize(credentials _: ASAuthorizationAppleIDCredential) -> AnyPublisher<Void, Never> {
  20. isAuthorizedSubject.send(true)
  21. // TODO: send data to server
  22. return Just(()).eraseToAnyPublisher()
  23. }
  24. func logout() {
  25. keychain.removeObject(forKey: Login.Config.credentialsKey).publisher
  26. .sink(
  27. receiveCompletion: { _ in
  28. self.isAuthorizedSubject.send(false)
  29. },
  30. receiveValue: {}
  31. )
  32. .store(in: &lifetime)
  33. }
  34. }