nativescript-plugin-firebase-ssi
Version:
1,034 lines (1,033 loc) • 105 kB
JavaScript
"use strict";
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var application = require("tns-core-modules/application/application");
var platform_1 = require("tns-core-modules/platform");
var firebase_common_1 = require("./firebase-common");
var firebaseFunctions = require("./functions/functions");
var firebaseMessaging = require("./messaging/messaging");
var utils_1 = require("./utils");
var nonce_util_ios_1 = require("./utils/nonce-util-ios");
firebase_common_1.firebase._gIDAuthentication = null;
firebase_common_1.firebase._cachedDynamicLink = null;
firebase_common_1.firebase._configured = false;
firebase_common_1.firebase._currentNonce = null;
var useExternalPushProvider = NSBundle.mainBundle.infoDictionary.objectForKey("UseExternalPushProvider") === true;
var initializeArguments;
var DocumentSnapshot = (function (_super) {
__extends(DocumentSnapshot, _super);
function DocumentSnapshot(snapshot) {
var _this = _super.call(this, snapshot.documentID, snapshot.exists, utils_1.firebaseUtils.toJsObject(snapshot.data()), firebase_common_1.firebase.firestore._getDocumentReference(snapshot.reference)) || this;
_this.snapshot = snapshot;
_this.metadata = {
fromCache: _this.snapshot.metadata.fromCache,
hasPendingWrites: _this.snapshot.metadata.pendingWrites
};
_this.ios = snapshot;
return _this;
}
return DocumentSnapshot;
}(firebase_common_1.DocumentSnapshot));
firebase_common_1.firebase.authStateListener = null;
firebase_common_1.firebase.addOnMessageReceivedCallback = firebaseMessaging.addOnMessageReceivedCallback;
firebase_common_1.firebase.addOnPushTokenReceivedCallback = firebaseMessaging.addOnPushTokenReceivedCallback;
firebase_common_1.firebase.registerForPushNotifications = firebaseMessaging.registerForPushNotifications;
firebase_common_1.firebase.unregisterForPushNotifications = firebaseMessaging.unregisterForPushNotifications;
firebase_common_1.firebase.getCurrentPushToken = firebaseMessaging.getCurrentPushToken;
firebase_common_1.firebase.registerForInteractivePush = firebaseMessaging.registerForInteractivePush;
firebase_common_1.firebase.subscribeToTopic = firebaseMessaging.subscribeToTopic;
firebase_common_1.firebase.unsubscribeFromTopic = firebaseMessaging.unsubscribeFromTopic;
firebase_common_1.firebase.areNotificationsEnabled = firebaseMessaging.areNotificationsEnabled;
firebase_common_1.firebase.functions = firebaseFunctions;
NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(UIApplicationDidFinishLaunchingNotification, null, NSOperationQueue.mainQueue, function (appNotification) {
if (!firebase_common_1.firebase._configured) {
firebase_common_1.firebase._configured = true;
if (typeof (FIRApp) !== "undefined") {
FIRApp.configure();
}
}
});
firebase_common_1.firebase.addAppDelegateMethods = function (appDelegate) {
if (typeof (FIRMessaging) !== "undefined" || useExternalPushProvider || typeof (FBSDKApplicationDelegate) !== "undefined") {
appDelegate.prototype.applicationDidFinishLaunchingWithOptions = function (application, launchOptions) {
if (launchOptions) {
var remoteNotification = launchOptions.objectForKey(UIApplicationLaunchOptionsRemoteNotificationKey);
if (remoteNotification) {
firebaseMessaging.handleRemoteNotification(application, remoteNotification);
}
}
if (typeof (FBSDKApplicationDelegate) !== "undefined") {
FBSDKApplicationDelegate.sharedInstance.applicationDidFinishLaunchingWithOptions(application, launchOptions);
}
return true;
};
}
if (typeof (FBSDKApplicationDelegate) !== "undefined" || typeof (GIDSignIn) !== "undefined" || typeof (FIRDynamicLink) !== "undefined") {
appDelegate.prototype.applicationOpenURLSourceApplicationAnnotation = function (application, url, sourceApplication, annotation) {
var result = false;
if (typeof (FBSDKApplicationDelegate) !== "undefined") {
result = FBSDKApplicationDelegate.sharedInstance.applicationOpenURLSourceApplicationAnnotation(application, url, sourceApplication, annotation);
}
if (typeof (GIDSignIn) !== "undefined") {
result = result || GIDSignIn.sharedInstance().handleURL(url);
}
if (typeof (FIRDynamicLink) !== "undefined") {
var dynamicLink = FIRDynamicLinks.dynamicLinks().dynamicLinkFromCustomSchemeURL(url);
if (dynamicLink) {
console.log("Dynamic link from " + sourceApplication + ", URL: " + dynamicLink.url.absoluteString);
firebase_common_1.firebase._cachedDynamicLink = {
url: dynamicLink.url.absoluteString,
minimumAppVersion: dynamicLink.minimumAppVersion
};
result = true;
}
}
return result;
};
}
if (typeof (FBSDKApplicationDelegate) !== "undefined" || typeof (GIDSignIn) !== "undefined" || typeof (FIRDynamicLink) !== "undefined") {
appDelegate.prototype.applicationOpenURLOptions = function (application, url, options) {
var result = false;
if (typeof (FBSDKApplicationDelegate) !== "undefined") {
result = FBSDKApplicationDelegate.sharedInstance.applicationOpenURLSourceApplicationAnnotation(application, url, options.valueForKey(UIApplicationOpenURLOptionsSourceApplicationKey), options.valueForKey(UIApplicationOpenURLOptionsAnnotationKey));
}
if (typeof (GIDSignIn) !== "undefined") {
result = result || GIDSignIn.sharedInstance().handleURL(url);
}
if (typeof (FIRDynamicLink) !== "undefined") {
var dynamicLinks = FIRDynamicLinks.dynamicLinks();
var dynamicLink = dynamicLinks.dynamicLinkFromCustomSchemeURL(url);
if (dynamicLink && dynamicLink.url !== null) {
if (firebase_common_1.firebase._dynamicLinkCallback) {
firebase_common_1.firebase._dynamicLinkCallback({
url: dynamicLink.url.absoluteString,
minimumAppVersion: dynamicLink.minimumAppVersion
});
}
else {
firebase_common_1.firebase._cachedDynamicLink = {
url: dynamicLink.url.absoluteString,
minimumAppVersion: dynamicLink.minimumAppVersion
};
}
result = true;
}
}
return result;
};
}
if (typeof (FIRDynamicLink) !== "undefined") {
appDelegate.prototype.applicationContinueUserActivityRestorationHandler = function (application, userActivity, restorationHandler) {
var result = false;
if (userActivity.webpageURL) {
var fAuth_1 = (typeof (FIRAuth) !== "undefined") ? FIRAuth.auth() : undefined;
if (fAuth_1 && fAuth_1.isSignInWithEmailLink(userActivity.webpageURL.absoluteString)) {
var rememberedEmail_1 = firebase_common_1.firebase.getRememberedEmailForEmailLinkLogin();
if (rememberedEmail_1 !== undefined) {
if (fAuth_1.currentUser) {
var onCompletionLink = function (result, error) {
if (error) {
fAuth_1.signInWithEmailLinkCompletion(rememberedEmail_1, userActivity.webpageURL.absoluteString, function (authData, error) {
if (!error) {
firebase_common_1.firebase.notifyAuthStateListeners({
loggedIn: true,
user: toLoginResult(authData.user)
});
}
});
}
else {
firebase_common_1.firebase.notifyAuthStateListeners({
loggedIn: true,
user: toLoginResult(result.user)
});
}
};
var fIRAuthCredential = FIREmailAuthProvider.credentialWithEmailLink(rememberedEmail_1, userActivity.webpageURL.absoluteString);
fAuth_1.currentUser.linkWithCredentialCompletion(fIRAuthCredential, onCompletionLink);
}
else {
fAuth_1.signInWithEmailLinkCompletion(rememberedEmail_1, userActivity.webpageURL.absoluteString, function (authData, error) {
if (error) {
console.log(error.localizedDescription);
}
else {
firebase_common_1.firebase.notifyAuthStateListeners({
loggedIn: true,
user: toLoginResult(authData.user)
});
}
});
}
}
result = true;
}
else {
result = FIRDynamicLinks.dynamicLinks().handleUniversalLinkCompletion(userActivity.webpageURL, function (dynamicLink, error) {
if (dynamicLink !== null && dynamicLink.url !== null) {
if (firebase_common_1.firebase._dynamicLinkCallback) {
firebase_common_1.firebase._dynamicLinkCallback({
url: dynamicLink.url.absoluteString,
minimumAppVersion: dynamicLink.minimumAppVersion
});
}
else {
firebase_common_1.firebase._cachedDynamicLink = {
url: dynamicLink.url.absoluteString,
minimumAppVersion: dynamicLink.minimumAppVersion
};
}
}
});
}
}
return result;
};
}
if (typeof (FIRMessaging) !== "undefined" || useExternalPushProvider) {
firebaseMessaging.addBackgroundRemoteNotificationHandler(appDelegate);
}
};
firebase_common_1.firebase.fetchSignInMethodsForEmail = function (email) {
return new Promise(function (resolve, reject) {
try {
if (typeof (email) !== "string") {
reject("A parameter representing an email address is required.");
return;
}
FIRAuth.auth().fetchSignInMethodsForEmailCompletion(email, function (methodsNSArray, error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve(utils_1.firebaseUtils.toJsObject(methodsNSArray));
}
});
}
catch (ex) {
console.log("Error in firebase.fetchSignInMethodsForEmail: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.addOnDynamicLinkReceivedCallback = function (callback) {
return new Promise(function (resolve, reject) {
try {
if (typeof (FIRDynamicLink) === "undefined") {
reject("Set 'dynamic_links' to 'true' in firebase.nativescript.json and remove the platforms/ios folder");
return;
}
firebase_common_1.firebase._dynamicLinkCallback = callback;
if (firebase_common_1.firebase._cachedDynamicLink !== null) {
callback(firebase_common_1.firebase._cachedDynamicLink);
firebase_common_1.firebase._cachedDynamicLink = null;
}
resolve();
}
catch (ex) {
console.log("Error in firebase.addOnDynamicLinkReceivedCallback: " + ex);
reject(ex);
}
});
};
if (typeof (FIRMessaging) !== "undefined" || useExternalPushProvider) {
firebaseMessaging.prepAppDelegate();
}
function getAppDelegate() {
if (application.ios.delegate === undefined) {
var UIApplicationDelegateImpl = (function (_super) {
__extends(UIApplicationDelegateImpl, _super);
function UIApplicationDelegateImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
UIApplicationDelegateImpl = __decorate([
ObjCClass(UIApplicationDelegate)
], UIApplicationDelegateImpl);
return UIApplicationDelegateImpl;
}(UIResponder));
application.ios.delegate = UIApplicationDelegateImpl;
}
return application.ios.delegate;
}
firebase_common_1.firebase.addAppDelegateMethods(getAppDelegate());
firebase_common_1.firebase.getCallbackData = function (type, snapshot) {
return {
type: type,
key: snapshot.key,
value: utils_1.firebaseUtils.toJsObject(snapshot.value)
};
};
firebase_common_1.firebase.init = function (arg) {
return new Promise(function (resolve, reject) {
if (firebase_common_1.firebase.initialized) {
reject("Firebase already initialized");
return;
}
firebase_common_1.firebase.initialized = true;
try {
try {
if (typeof (FIRServerValue) !== "undefined") {
firebase_common_1.firebase.ServerValue = {
TIMESTAMP: FIRServerValue.timestamp()
};
}
}
catch (ignore) {
}
arg = arg || {};
initializeArguments = arg;
if (FIROptions && FIROptions.defaultOptions() !== null) {
FIROptions.defaultOptions().deepLinkURLScheme = NSBundle.mainBundle.bundleIdentifier;
}
if (typeof (FIRAnalytics) !== "undefined" && FIRAnalytics.setAnalyticsCollectionEnabled) {
FIRAnalytics.setAnalyticsCollectionEnabled(arg.analyticsCollectionEnabled !== false);
}
if (!firebase_common_1.firebase._configured) {
firebase_common_1.firebase._configured = true;
if (typeof (FIRApp) !== "undefined") {
FIRApp.configure();
}
}
if (arg.crashlyticsCollectionEnabled && typeof (Crashlytics) !== "undefined") {
Fabric.with(NSArray.arrayWithObject(Crashlytics.class()));
}
if (typeof (FIRDatabase) !== "undefined") {
if (arg.persist) {
FIRDatabase.database().persistenceEnabled = true;
}
}
if (typeof (FIRFirestore) !== "undefined") {
if (arg.persist === false) {
var fIRFirestoreSettings = FIRFirestoreSettings.new();
fIRFirestoreSettings.persistenceEnabled = false;
FIRFirestore.firestore().settings = fIRFirestoreSettings;
}
}
if (typeof (FIRAuth) !== "undefined") {
if (arg.iOSEmulatorFlush) {
try {
FIRAuth.auth().signOut();
}
catch (signOutErr) {
console.log("Sign out of Firebase error: " + signOutErr);
}
}
if (arg.onAuthStateChanged) {
firebase_common_1.firebase.authStateListener = function (auth, user) {
arg.onAuthStateChanged({
loggedIn: user !== null,
user: toLoginResult(user)
});
};
FIRAuth.auth().addAuthStateDidChangeListener(firebase_common_1.firebase.authStateListener);
}
if (!firebase_common_1.firebase.authStateListener) {
firebase_common_1.firebase.authStateListener = function (auth, user) {
firebase_common_1.firebase.notifyAuthStateListeners({
loggedIn: user !== null,
user: toLoginResult(user)
});
};
FIRAuth.auth().addAuthStateDidChangeListener(firebase_common_1.firebase.authStateListener);
}
}
if (arg.onDynamicLinkCallback !== undefined) {
firebase_common_1.firebase.addOnDynamicLinkReceivedCallback(arg.onDynamicLinkCallback);
}
if (typeof (FBSDKAppEvents) !== "undefined") {
FBSDKAppEvents.activateApp();
}
if (typeof (FIRMessaging) !== "undefined") {
firebaseMessaging.initFirebaseMessaging(arg);
}
if (arg.storageBucket) {
if (typeof (FIRStorage) === "undefined") {
reject("Uncomment Storage in the plugin's Podfile first");
return;
}
firebase_common_1.firebase.storageBucket = FIRStorage.storage().referenceForURL(arg.storageBucket);
}
resolve(typeof (FIRDatabase) !== "undefined" ? FIRDatabase.database().reference() : undefined);
}
catch (ex) {
console.log("Error in firebase.init: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.getRemoteConfig = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (typeof (FIRRemoteConfig) === "undefined") {
reject("Uncomment RemoteConfig in the plugin's Podfile first");
return;
}
if (arg.properties === undefined) {
reject("Argument 'properties' is missing");
return;
}
var firebaseRemoteConfig_1 = FIRRemoteConfig.remoteConfig();
firebaseRemoteConfig_1.configSettings = new FIRRemoteConfigSettings({ developerModeEnabled: arg.developerMode || false });
var dic = NSMutableDictionary.new();
for (var p in arg.properties) {
var prop = arg.properties[p];
if (prop.default !== undefined) {
dic.setObjectForKey(prop.default, prop.key);
}
}
firebaseRemoteConfig_1.setDefaults(dic);
var onCompletion = function (remoteConfigFetchStatus, error) {
if (remoteConfigFetchStatus === 1 ||
remoteConfigFetchStatus === 3) {
var activated = firebaseRemoteConfig_1.activateFetched();
var result = {
lastFetch: firebaseRemoteConfig_1.lastFetchTime,
throttled: remoteConfigFetchStatus === 3,
properties: {}
};
for (var p in arg.properties) {
var prop = arg.properties[p];
var key = prop.key;
var value = firebaseRemoteConfig_1.configValueForKey(key).stringValue;
result.properties[key] = firebase_common_1.firebase.strongTypeify(value);
}
resolve(result);
}
else {
reject(error ? error.localizedDescription : "Unknown error, fetch status: " + remoteConfigFetchStatus);
}
};
var expirationDuration = arg.cacheExpirationSeconds || 43200;
firebaseRemoteConfig_1.fetchWithExpirationDurationCompletionHandler(expirationDuration, onCompletion);
}
catch (ex) {
console.log("Error in firebase.getRemoteConfig: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.getCurrentUser = function (arg) {
return new Promise(function (resolve, reject) {
try {
var fAuth = FIRAuth.auth();
if (fAuth === null) {
reject("Run init() first!");
return;
}
var user = fAuth.currentUser;
if (user) {
resolve(toLoginResult(user));
}
else {
reject();
}
}
catch (ex) {
console.log("Error in firebase.getCurrentUser: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.sendEmailVerification = function (actionCodeSettings) {
return new Promise(function (resolve, reject) {
try {
var fAuth = FIRAuth.auth();
if (fAuth === null) {
reject("Run init() first!");
return;
}
var user = fAuth.currentUser;
if (user) {
var onCompletion = function (error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve(true);
}
};
if (actionCodeSettings) {
var firActionCodeSettings = FIRActionCodeSettings.new();
if (actionCodeSettings.handleCodeInApp !== undefined) {
firActionCodeSettings.handleCodeInApp = actionCodeSettings.handleCodeInApp;
}
if (actionCodeSettings.url) {
firActionCodeSettings.URL = NSURL.URLWithString(actionCodeSettings.url);
}
if (actionCodeSettings.iOS) {
if (actionCodeSettings.iOS.bundleId) {
firActionCodeSettings.setIOSBundleID(actionCodeSettings.iOS.bundleId);
}
if (actionCodeSettings.iOS.dynamicLinkDomain) {
firActionCodeSettings.dynamicLinkDomain = actionCodeSettings.iOS.dynamicLinkDomain;
}
}
if (actionCodeSettings.android && actionCodeSettings.android.packageName) {
firActionCodeSettings.setAndroidPackageNameInstallIfNotAvailableMinimumVersion(actionCodeSettings.android.packageName, actionCodeSettings.android.installApp, actionCodeSettings.android.minimumVersion || null);
}
user.sendEmailVerificationWithActionCodeSettingsCompletion(firActionCodeSettings, onCompletion);
}
else {
user.sendEmailVerificationWithCompletion(onCompletion);
}
}
else {
reject("Log in first");
}
}
catch (ex) {
console.log("Error in firebase.sendEmailVerification: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.logout = function (arg) {
return new Promise(function (resolve, reject) {
try {
FIRAuth.auth().signOut();
firebase_common_1.firebase.currentAdditionalUserInfo = null;
if (typeof (GIDSignIn) !== "undefined") {
GIDSignIn.sharedInstance().disconnect();
}
if (typeof (FBSDKLoginManager) !== "undefined") {
FBSDKLoginManager.alloc().logOut();
}
resolve();
}
catch (ex) {
console.log("Error in firebase.logout: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.unlink = function (providerId) {
return new Promise(function (resolve, reject) {
try {
var user = FIRAuth.auth().currentUser;
if (!user) {
reject("Not logged in");
return;
}
user.unlinkFromProviderCompletion(providerId, function (user, error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve(user);
}
});
}
catch (ex) {
console.log("Error in firebase.logout: " + ex);
reject(ex);
}
});
};
function toLoginResult(user, additionalUserInfo) {
if (!user) {
return null;
}
if (additionalUserInfo) {
firebase_common_1.firebase.currentAdditionalUserInfo = additionalUserInfo;
}
var providers = [];
if (user.providerData) {
for (var i = 0, l = user.providerData.count; i < l; i++) {
var firUserInfo = user.providerData.objectAtIndex(i);
var pid = firUserInfo.valueForKey("providerID");
if (pid === "facebook.com" && typeof (FBSDKAccessToken) !== "undefined") {
providers.push({ id: pid, token: FBSDKAccessToken.currentAccessToken ? FBSDKAccessToken.currentAccessToken.tokenString : null });
}
else if (pid === "google.com" && typeof (GIDSignIn) !== "undefined" && GIDSignIn.sharedInstance() && GIDSignIn.sharedInstance().currentUser) {
var gidCurrentIdToken = GIDSignIn.sharedInstance().currentUser.authentication.idToken;
providers.push({ id: pid, token: gidCurrentIdToken });
}
else if (pid === "apple.com") {
}
else {
providers.push({ id: pid });
}
}
}
var loginResult = {
uid: user.uid,
anonymous: user.anonymous,
isAnonymous: user.anonymous,
providers: providers,
photoURL: user.photoURL ? user.photoURL.absoluteString : null,
email: user.email,
emailVerified: user.emailVerified,
displayName: user.displayName,
phoneNumber: user.phoneNumber,
refreshToken: user.refreshToken,
metadata: {
creationTimestamp: user.metadata.creationDate,
lastSignInTimestamp: user.metadata.lastSignInDate
},
getIdToken: function (forceRefresh) { return new Promise(function (resolve, reject) {
firebase_common_1.firebase.getAuthToken({ forceRefresh: forceRefresh })
.then(function (result) { return resolve(result.token); })
.catch(reject);
}); },
getIdTokenResult: function (forceRefresh) { return new Promise(function (resolve, reject) {
firebase_common_1.firebase.getAuthToken({ forceRefresh: forceRefresh })
.then(function (result) { return resolve(result); })
.catch(reject);
}); },
sendEmailVerification: function (actionCodeSettings) { return firebase_common_1.firebase.sendEmailVerification(actionCodeSettings); }
};
if (firebase_common_1.firebase.currentAdditionalUserInfo) {
loginResult.additionalUserInfo = {
providerId: firebase_common_1.firebase.currentAdditionalUserInfo.providerID,
username: firebase_common_1.firebase.currentAdditionalUserInfo.username,
isNewUser: firebase_common_1.firebase.currentAdditionalUserInfo.newUser,
profile: utils_1.firebaseUtils.toJsObject(firebase_common_1.firebase.currentAdditionalUserInfo.profile)
};
}
return loginResult;
}
firebase_common_1.firebase.getAuthToken = function (arg) {
return new Promise(function (resolve, reject) {
try {
var fAuth = FIRAuth.auth();
if (fAuth === null) {
reject("Run init() first!");
return;
}
var user = fAuth.currentUser;
if (user) {
user.getIDTokenResultForcingRefreshCompletion(arg.forceRefresh, function (result, error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve({
token: result.token,
claims: utils_1.firebaseUtils.toJsObject(result.claims),
signInProvider: result.signInProvider,
expirationTime: utils_1.firebaseUtils.toJsObject(result.expirationDate),
issuedAtTime: utils_1.firebaseUtils.toJsObject(result.issuedAtDate),
authTime: utils_1.firebaseUtils.toJsObject(result.authDate)
});
}
});
}
else {
reject("Log in first");
}
}
catch (ex) {
console.log("Error in firebase.getAuthToken: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.login = function (arg) {
return new Promise(function (resolve, reject) {
try {
var onCompletionWithAuthResult_1 = function (authResult, error) {
if (error) {
if (typeof (GIDSignIn) !== "undefined") {
GIDSignIn.sharedInstance().disconnect();
}
reject(error.localizedDescription);
}
else {
resolve(toLoginResult(authResult && authResult.user, authResult && authResult.additionalUserInfo));
firebase_common_1.firebase.notifyAuthStateListeners({
loggedIn: true,
user: toLoginResult(authResult.user)
});
}
};
var fAuth_2 = FIRAuth.auth();
if (fAuth_2 === null) {
reject("Run init() first!");
return;
}
firebase_common_1.firebase.moveLoginOptionsToObjects(arg);
if (arg.type === firebase_common_1.firebase.LoginType.ANONYMOUS) {
fAuth_2.signInAnonymouslyWithCompletion(onCompletionWithAuthResult_1);
}
else if (arg.type === firebase_common_1.firebase.LoginType.PASSWORD) {
if (!arg.passwordOptions || !arg.passwordOptions.email || !arg.passwordOptions.password) {
reject("Auth type PASSWORD requires an 'passwordOptions.email' and 'passwordOptions.password' argument");
return;
}
var fIRAuthCredential_1 = FIREmailAuthProvider.credentialWithEmailPassword(arg.passwordOptions.email, arg.passwordOptions.password);
if (fAuth_2.currentUser) {
var onCompletionLink = function (authData, error) {
if (error) {
log("--- linking error: " + error.localizedDescription);
fAuth_2.signInWithCredentialCompletion(fIRAuthCredential_1, onCompletionWithAuthResult_1);
}
else {
onCompletionWithAuthResult_1(authData, error);
}
};
fAuth_2.currentUser.linkWithCredentialCompletion(fIRAuthCredential_1, onCompletionLink);
}
else {
fAuth_2.signInWithEmailPasswordCompletion(arg.passwordOptions.email, arg.passwordOptions.password, onCompletionWithAuthResult_1);
}
}
else if (arg.type === firebase_common_1.firebase.LoginType.EMAIL_LINK) {
if (!arg.emailLinkOptions || !arg.emailLinkOptions.email) {
reject("Auth type EMAIL_LINK requires an 'emailLinkOptions.email' argument");
return;
}
if (!arg.emailLinkOptions.url) {
reject("Auth type EMAIL_LINK requires an 'emailLinkOptions.url' argument");
return;
}
var firActionCodeSettings = FIRActionCodeSettings.new();
firActionCodeSettings.URL = NSURL.URLWithString(arg.emailLinkOptions.url);
firActionCodeSettings.handleCodeInApp = true;
firActionCodeSettings.setIOSBundleID(arg.emailLinkOptions.iOS ? arg.emailLinkOptions.iOS.bundleId : NSBundle.mainBundle.bundleIdentifier);
firActionCodeSettings.setAndroidPackageNameInstallIfNotAvailableMinimumVersion(arg.emailLinkOptions.android ? arg.emailLinkOptions.android.packageName : NSBundle.mainBundle.bundleIdentifier, arg.emailLinkOptions.android ? arg.emailLinkOptions.android.installApp || false : false, arg.emailLinkOptions.android ? arg.emailLinkOptions.android.minimumVersion || "1" : "1");
fAuth_2.sendSignInLinkToEmailActionCodeSettingsCompletion(arg.emailLinkOptions.email, firActionCodeSettings, function (error) {
if (error) {
reject(error.localizedDescription);
return;
}
firebase_common_1.firebase.rememberEmailForEmailLinkLogin(arg.emailLinkOptions.email);
resolve();
});
}
else if (arg.type === firebase_common_1.firebase.LoginType.PHONE) {
if (!arg.phoneOptions || !arg.phoneOptions.phoneNumber) {
reject("Auth type PHONE requires a 'phoneOptions.phoneNumber' argument");
return;
}
FIRPhoneAuthProvider.provider().verifyPhoneNumberUIDelegateCompletion(arg.phoneOptions.phoneNumber, null, function (verificationID, error) {
if (error) {
reject(error.localizedDescription);
return;
}
firebase_common_1.firebase.requestPhoneAuthVerificationCode(function (userResponse) {
if (userResponse === undefined) {
reject("Prompt was canceled");
return;
}
var fIRAuthCredential = FIRPhoneAuthProvider.provider().credentialWithVerificationIDVerificationCode(verificationID, userResponse);
if (fAuth_2.currentUser) {
var onCompletionLink = function (authData, error) {
if (error) {
fAuth_2.signInWithCredentialCompletion(fIRAuthCredential, onCompletionWithAuthResult_1);
}
else {
onCompletionWithAuthResult_1(authData, error);
}
};
fAuth_2.currentUser.linkWithCredentialCompletion(fIRAuthCredential, onCompletionLink);
}
else {
fAuth_2.signInWithCredentialCompletion(fIRAuthCredential, onCompletionWithAuthResult_1);
}
}, arg.phoneOptions.verificationPrompt);
});
}
else if (arg.type === firebase_common_1.firebase.LoginType.CUSTOM) {
if (!arg.customOptions || (!arg.customOptions.token && !arg.customOptions.tokenProviderFn)) {
reject("Auth type CUSTOM requires a 'customOptions.token' or 'customOptions.tokenProviderFn' argument");
return;
}
if (arg.customOptions.token) {
fAuth_2.signInWithCustomTokenCompletion(arg.customOptions.token, onCompletionWithAuthResult_1);
}
else if (arg.customOptions.tokenProviderFn) {
arg.customOptions.tokenProviderFn()
.then(function (token) {
fAuth_2.signInWithCustomTokenCompletion(token, onCompletionWithAuthResult_1);
}, function (error) {
reject(error);
});
}
}
else if (arg.type === firebase_common_1.firebase.LoginType.FACEBOOK) {
if (typeof (FBSDKLoginManager) === "undefined") {
reject("Facebook SDK not installed - see Podfile");
return;
}
var onFacebookCompletion = function (fbSDKLoginManagerLoginResult, error) {
if (error) {
console.log("Facebook login error " + error);
reject(error.localizedDescription);
}
else if (fbSDKLoginManagerLoginResult.isCancelled) {
reject("login cancelled");
}
else {
var fIRAuthCredential_2 = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken.tokenString);
if (fAuth_2.currentUser) {
var onCompletionLink = function (authData, error) {
if (error) {
log("--- linking error: " + error.localizedDescription);
fAuth_2.signInWithCredentialCompletion(fIRAuthCredential_2, onCompletionWithAuthResult_1);
}
else {
onCompletionWithAuthResult_1(authData);
}
};
fAuth_2.currentUser.linkWithCredentialCompletion(fIRAuthCredential_2, onCompletionLink);
}
else {
fAuth_2.signInWithCredentialCompletion(fIRAuthCredential_2, onCompletionWithAuthResult_1);
}
}
};
var fbSDKLoginManager = FBSDKLoginManager.new();
var scopes = ["public_profile", "email"];
if (arg.facebookOptions && arg.facebookOptions.scopes) {
scopes = arg.facebookOptions.scopes;
}
fbSDKLoginManager.logInWithPermissionsFromViewControllerHandler(scopes, null, onFacebookCompletion);
}
else if (arg.type === firebase_common_1.firebase.LoginType.APPLE) {
if (parseInt(platform_1.device.osVersion) < 13) {
reject("Sign in with Apple requires iOS 13 or higher. You're running iOS " + platform_1.device.osVersion);
return;
}
firebase_common_1.firebase._currentNonce = nonce_util_ios_1.getNonce(32);
var sha256Nonce = nonce_util_ios_1.Sha256(firebase_common_1.firebase._currentNonce);
var appleIDProvider = ASAuthorizationAppleIDProvider.new();
var appleIDRequest = appleIDProvider.createRequest();
var scopes_1 = [ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
if (arg.appleOptions && arg.appleOptions.scopes) {
scopes_1 = [];
arg.appleOptions.scopes.forEach(function (scope) {
if (scope === "name") {
scopes_1.push(ASAuthorizationScopeFullName);
}
else if (scope === "email") {
scopes_1.push(ASAuthorizationScopeEmail);
}
else {
console.log("Unknown scope: " + scope);
}
});
}
appleIDRequest.requestedScopes = scopes_1;
appleIDRequest.nonce = sha256Nonce;
var authorizationController = ASAuthorizationController.alloc().initWithAuthorizationRequests([appleIDRequest]);
var delegate = ASAuthorizationControllerDelegateImpl.createWithOwnerAndResolveReject(_this, resolve, reject);
CFRetain(delegate);
authorizationController.delegate = delegate;
authorizationController.presentationContextProvider = ASAuthorizationControllerPresentationContextProvidingImpl.createWithOwnerAndCallback(_this);
authorizationController.performRequests();
}
else if (arg.type === firebase_common_1.firebase.LoginType.GOOGLE) {
if (typeof (GIDSignIn) === "undefined") {
reject("Google Sign In not installed - see Podfile");
return;
}
var sIn = GIDSignIn.sharedInstance();
sIn.presentingViewController = arg.ios && arg.ios.controller ? arg.ios.controller : application.ios.rootController;
sIn.clientID = FIRApp.defaultApp().options.clientID;
if (arg.googleOptions && arg.googleOptions.hostedDomain) {
sIn.hostedDomain = arg.googleOptions.hostedDomain;
}
if (arg.googleOptions && arg.googleOptions.scopes) {
sIn.scopes = arg.googleOptions.scopes;
}
var delegate_1 = GIDSignInDelegateImpl.new().initWithCallback(function (user, error) {
if (error === null) {
firebase_common_1.firebase._gIDAuthentication = user.authentication;
var fIRAuthCredential_3 = FIRGoogleAuthProvider.credentialWithIDTokenAccessToken(firebase_common_1.firebase._gIDAuthentication.idToken, firebase_common_1.firebase._gIDAuthentication.accessToken);
if (fAuth_2.currentUser) {
var onCompletionLink = function (user, error) {
if (error) {
fAuth_2.signInWithCredentialCompletion(fIRAuthCredential_3, onCompletionWithAuthResult_1);
}
else {
onCompletionWithAuthResult_1(user);
}
};
fAuth_2.currentUser.linkWithCredentialCompletion(fIRAuthCredential_3, onCompletionLink);
}
else {
fAuth_2.signInWithCredentialCompletion(fIRAuthCredential_3, onCompletionWithAuthResult_1);
}
}
else {
reject(error.localizedDescription);
}
CFRelease(delegate_1);
delegate_1 = undefined;
});
CFRetain(delegate_1);
sIn.delegate = delegate_1;
sIn.signIn();
}
else {
reject("Unsupported auth type: " + arg.type);
}
}
catch (ex) {
console.log("Error in firebase.login: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.reauthenticate = function (arg) {
return new Promise(function (resolve, reject) {
try {
var fAuth = FIRAuth.auth();
if (fAuth === null) {
reject("Run init() first!");
return;
}
var user = fAuth.currentUser;
if (user === null) {
reject("no current user");
return;
}
firebase_common_1.firebase.moveLoginOptionsToObjects(arg);
var authCredential = null;
if (arg.type === firebase_common_1.firebase.LoginType.PASSWORD) {
if (!arg.passwordOptions || !arg.passwordOptions.email || !arg.passwordOptions.password) {
reject("Auth type PASSWORD requires an 'passwordOptions.email' and 'passwordOptions.password' argument");
return;
}
authCredential = FIREmailAuthProvider.credentialWithEmailPassword(arg.passwordOptions.email, arg.passwordOptions.password);
}
else if (arg.type === firebase_common_1.firebase.LoginType.GOOGLE) {
if (!firebase_common_1.firebase._gIDAuthentication) {
reject("Not currently logged in with Google");
return;
}
authCredential = FIRGoogleAuthProvider.credentialWithIDTokenAccessToken(firebase_common_1.firebase._gIDAuthentication.idToken, firebase_common_1.firebase._gIDAuthentication.accessToken);
}
else if (arg.type === firebase_common_1.firebase.LoginType.FACEBOOK) {
if (!FBSDKAccessToken.currentAccessToken) {
reject("Not currently logged in with Facebook");
return;
}
authCredential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken.tokenString);
}
if (authCredential === null) {
reject("arg.type should be one of LoginType.PASSWORD | LoginType.GOOGLE | LoginType.FACEBOOK");
return;
}
var onCompletion = function (authResult, error) {
if (error) {
reject(error.localizedDescription);
}
else {
firebase_common_1.firebase.notifyAuthStateListeners({
loggedIn: true,
user: toLoginResult(authResult.user)
});
resolve(toLoginResult(authResult && authResult.user, authResult && authResult.additionalUserInfo));
}
};
user.reauthenticateWithCredentialCompletion(authCredential, onCompletion);
}
catch (ex) {
console.log("Error in firebase.reauthenticate: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.reloadUser = function () {
return new Promise(function (resolve, reject) {
try {
var user = FIRAuth.auth().currentUser;
if (user === null) {
reject("no current user");
return;
}
var onCompletion = function (error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve();
}
};
user.reloadWithCompletion(onCompletion);
}
catch (ex) {
console.log("Error in firebase.reloadUser: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.sendPasswordResetEmail = function (email) {
return new Promise(function (resolve, reject) {
try {
var onCompletion = function (error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve();
}
};
FIRAuth.auth().sendPasswordResetWithEmailCompletion(email, onCompletion);
}
catch (ex) {
console.log("Error in firebase.sendPasswordResetEmail: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.updateEmail = function (newEmail) {
return new Promise(function (resolve, reject) {
try {
var onCompletion = function (error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve();
}
};
var user = FIRAuth.auth().currentUser;
if (user === null) {
reject("no current user");
}
else {
user.updateEmailCompletion(newEmail, onCompletion);
}
}
catch (ex) {
console.log("Error in firebase.updateEmail: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.updatePassword = function (newPassword) {
return new Promise(function (resolve, reject) {
try {
var onCompletion = function (error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve();
}
};
var user = FIRAuth.auth().currentUser;
if (user === null) {
reject("no current user");
}
else {
user.updatePasswordCompletion(newPassword, onCompletion);
}
}
catch (ex) {
console.log("Error in firebase.updatePassword: " + ex);
reject(ex);
}
});
};
firebase_common_1.firebase.createUser = function (arg) {
return new Promise(function (resolve, reject) {
try {
var onCompletion = function (authResult, error) {
if (error) {
reject(error.localizedDescription);
}
else {
resolve(toLoginResult(authResult.user, authResult.additionalUserInfo));