Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import Foundation
import RxSwift
import Firebase
extension FIRAuth {
public enum AuthProvider {
case emailPassword(String, String)
case facebook(String)
case google(String, String)
case twitter(String, String)
case github(String)
var credential: FIRAuthCredential {
switch self {
case .emailPassword(let email, let password):
return FIREmailPasswordAuthProvider.credential(withEmail: email, password: password)
case .facebook(let accessToken):
return FIRFacebookAuthProvider.credential(withAccessToken: accessToken)
case .google(let idToken, let accessToken):
return FIRGoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)
case .twitter(let token, let secret):
return FIRTwitterAuthProvider.credential(withToken: token, secret: secret)
case .github(let token):
return FIRGitHubAuthProvider.credential(withToken: token)
}
}
}
public enum AuthError: Error {
case notInitialized
}
}
extension Reactive where Base: FIRAuth {
private static func parseUserResponse(_ observer: @escaping (SingleEvent<FIRUser>) -> Void) -> (FIRUser?, Error?) -> Void {
return { user, error in
if let user = user {
observer(.success(user))
} else if let error = error {
observer(.error(error))
}
}
}
public static func signIn(withEmail email: String, password: String) -> Single<FIRUser> {
return Single.create { observer in
if let auth = FIRAuth.auth() {
auth.signIn(withEmail: email, password: password, completion: parseUserResponse(observer))
} else {
observer(.error(FIRAuth.AuthError.notInitialized))
}
return Disposables.create()
}
}
public static func signIn(authProvider: FIRAuth.AuthProvider) -> Single<FIRUser> {
return Single.create { observer in
if let auth = FIRAuth.auth() {
auth.signIn(with: authProvider.credential, completion: parseUserResponse(observer))
} else {
observer(.error(FIRAuth.AuthError.notInitialized))
}
return Disposables.create()
}
}
public static func signIn(withCustomToken customToken: String) -> Single<FIRUser> {
return Single.create { observer in
if let auth = FIRAuth.auth() {
auth.signIn(withCustomToken: customToken, completion: parseUserResponse(observer))
} else {
observer(.error(FIRAuth.AuthError.notInitialized))
}
return Disposables.create()
}
}
public static func signInAnonymously() -> Single<FIRUser> {
return Single.create { observer in
if let auth = FIRAuth.auth() {
auth.signInAnonymously(completion: parseUserResponse(observer))
} else {
observer(.error(FIRAuth.AuthError.notInitialized))
}
return Disposables.create()
}
}
public static func signOut() -> Completable {
return Completable.create { observer in
if let auth = FIRAuth.auth() {
do {
try auth.signOut()
observer(.completed)
} catch let error {
observer(.error(error))
}
} else {
observer(.error(FIRAuth.AuthError.notInitialized))
}
return Disposables.create()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment