Skip to content

Instantly share code, notes, and snippets.

@AppWerft
Created October 25, 2018 13:49
Show Gist options
  • Save AppWerft/ee828894847d5510a3c8257be9f4085b to your computer and use it in GitHub Desktop.
Save AppWerft/ee828894847d5510a3c8257be9f4085b to your computer and use it in GitHub Desktop.
package firebase.auth;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.telephony.TelephonyManager;
@Kroll.module(parentModule = TitaniumFirebaseAuthModule.class)
public class SMSModule extends TitaniumFirebaseAuthModule {
private PhoneAuthProvider.OnVerificationStateChangedCallbacks verifyPhoneNumberCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Log.d(TitaniumFirebaseAuthModule.LCAT,
"onVerificationComplarg0eted");
signInWithPhoneAuthCredential(credential);
if (validatePhoneNumberCallback != null) {
KrollDict event = new KrollDict();
event.put("success", true);
event.put("smsCode", credential.getSmsCode());
event.put("provider", credential.getProvider());
validatePhoneNumberCallback.callAsync(getKrollObject(), event);
}
}
@Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Log.d(LCAT, "onCodeSent");
resendToken = token;
KrollDict event = new KrollDict();
event.put("success", true);
event.put("verificationId", verificationId);
event.put("resendToken", new ResendTokenProxy(token));
event.put("success", true);
if (validatePhoneNumberCallback != null)
validatePhoneNumberCallback.callAsync(getKrollObject(), event);
if (onCodeSentCallback != null)
onCodeSentCallback.callAsync(getKrollObject(), event);
}
@Override
public void onCodeAutoRetrievalTimeOut(String verificationId) {
KrollDict event = new KrollDict();
event.put("message", "codeAutoRetrievalTimeOut");
event.put("verificationId", verificationId);
event.put("success", false);
if (onErrorCallback != null)
onErrorCallback.callAsync(getKrollObject(), event);
if (validatePhoneNumberCallback != null) {
validatePhoneNumberCallback.callAsync(getKrollObject(), event);
}
}
@Override
public void onVerificationFailed(FirebaseException e) {
KrollDict event = new KrollDict();
event.put("error", true);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
event.put("message", "Invalid request");
} else if (e instanceof FirebaseTooManyRequestsException) {
event.put("message",
"The SMS quota for the project has been exceeded");
} else {
event.put("message", e.getMessage());
}
Log.d(LCAT, event.toString());
if (onErrorCallback != null)
onErrorCallback.callAsync(getKrollObject(), event);
if (validatePhoneNumberCallback != null) {
validatePhoneNumberCallback.callAsync(getKrollObject(), event);
}
}
};
@Kroll.constant
public static final String LCAT = "☎ ️" + TitaniumFirebaseAuthModule.LCAT;
private KrollFunction onCodeSentCallback;
private KrollFunction onErrorCallback;
private KrollFunction onVerificationCompletedCallback;
private PhoneAuthProvider.ForceResendingToken resendToken;
private String phoneNumber = "";
private int timeout = 60000;
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private PhoneAuthProvider phoneAuthProvider = PhoneAuthProvider
.getInstance(firebaseAuth);
private KrollFunction authStateDidChangeCallback;
private KrollFunction validatePhoneNumberCallback;
private KrollFunction signInWithSMSCodeCallback;
public SMSModule() {
super();
}
@Kroll.onAppCreate
public static void onAppCreate(TiApplication app) {
}
@Override
public void onStart(Activity activity) {
Log.d(LCAT, "onStart of TitaniumFirebaseAuth.Module.SMS");
super.onStart(activity);
}
/* Start verifying by phone number SMS */
@Kroll.method
public void validatePhoneNumber(String phoneNumber, KrollFunction callback) {
validatePhoneNumberCallback = callback;
this.phoneNumber = phoneNumber;
doVerifyPhoneNumber();
}
@Kroll.method
public void signInWithSMSCode(String code, String verificationId,
KrollFunction callback) {
signInWithSMSCodeCallback = callback;
signInWithPhoneAuthCredential(PhoneAuthProvider.getCredential(
verificationId, code));
}
@Kroll.method
public void verifyPhoneNumber(KrollDict opts) {
if (opts.containsKeyAndNotNull("phoneNumber")) {
phoneNumber = opts.getString("phoneNumber");
}
if (opts.containsKeyAndNotNull("timeout")) {
timeout = opts.getInt("timeout");
}
if (opts.containsKeyAndNotNull("oncodesent")) {
Object o = opts.get("oncodesent");
if (o instanceof KrollFunction) {
onCodeSentCallback = (KrollFunction) o;
} else
Log.w(LCAT, "oncodesent is not JS-function");
} else
Log.w(LCAT, "oncodesent is not defined");
if (opts.containsKeyAndNotNull("onverificationcompleted")) {
Object o = opts.get("onverificationcompleted");
if (o instanceof KrollFunction) {
onVerificationCompletedCallback = (KrollFunction) o;
} else
Log.w(LCAT, "onverificationcompleted is not JS-function");
} else
Log.w(LCAT, "onverificationcompleted is not defined");
if (opts.containsKeyAndNotNull("onerror")) {
Object o = opts.get("onerror");
if (o instanceof KrollFunction) {
onErrorCallback = (KrollFunction) o;
} else
Log.w(LCAT, "onerror is not JS-function");
} else
Log.w(LCAT, "onerror is not defined");
doVerifyPhoneNumber();
}
private void doVerifyPhoneNumber() {
Log.d(LCAT, "PROVIDER_ID=" + PhoneAuthProvider.PROVIDER_ID);
if (phoneAuthProvider != null) {
phoneAuthProvider.verifyPhoneNumber(//
phoneNumber, //
timeout, //
TimeUnit.MILLISECONDS,//
TiApplication.getInstance().getCurrentActivity(), //
verifyPhoneNumberCallbacks);
} else
Log.d(LCAT, "phoneAuthProvider is null");
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
Activity activity = TiApplication.getInstance().getCurrentActivity();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(
activity, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
KrollDict event = new KrollDict();
if (task.isSuccessful()) {
event.put("success", true);
event.put("user", UserModule
.dictionaryFromUser(task.getResult()
.getUser()));
sendBack(event);
if (signInWithSMSCodeCallback != null)
signInWithSMSCodeCallback.callAsync(
getKrollObject(), event);
} else {
Log.w(LCAT, "signInWithCredential:failure",
task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
if (signInWithSMSCodeCallback != null) {
event.put("success", false);
event.put("error", task.getException()
.getMessage());
signInWithSMSCodeCallback.callAsync(
getKrollObject(), event);
}
}
}
}
});
}
@Kroll.method
public void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(
verificationId, code);
signInWithPhoneAuthCredential(credential);
}
@Kroll.method
public void resendVerificationCode(String phoneNumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(phoneNumber,
60, // Timeout
TimeUnit.SECONDS, // Unit of timeout
TiApplication.getInstance().getCurrentActivity(),
verifyPhoneNumberCallbacks, // OnVerificationStateChangedCallbacks
resendToken); // ForceResendingToken from callbacks
}
@Kroll.method
public void testPhoneAutoRetrieve(String phoneNumber, String smsCode) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
// FirebaseAuthSettings firebaseAuthSettings =
// firebaseAuth.getFirebaseAuthSettings();
// Configure faking the auto-retrieval with the whitelisted numbers.
// firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber,
// smsCode);
PhoneAuthProvider phoneAuthProvider = PhoneAuthProvider.getInstance();
phoneAuthProvider.verifyPhoneNumber(phoneNumber, 60L, TimeUnit.SECONDS,
TiApplication.getAppCurrentActivity(), /* activity */
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(
PhoneAuthCredential credential) {
// Instant verification is applied and a credential is
// directly returned.
// ...
}
// [START_EXCLUDE]
@Override
public void onVerificationFailed(FirebaseException e) {
}
// [END_EXCLUDE]
});
// [END auth_test_phone_auto]
}
@Kroll.method
public void testPhoneVerify(String phoneNumber, String smsCode) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(phoneNumber,
30L /* timeout */, TimeUnit.SECONDS,
TiApplication.getAppCurrentActivity(),
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onCodeSent(
String verificationId,
PhoneAuthProvider.ForceResendingToken forceResendingToken) {
// Save the verification id somewhere
// The corresponding whitelisted code above should be
// used to complete sign-in.
Log.i(LCAT, "");
}
@Override
public void onVerificationCompleted(
PhoneAuthCredential phoneAuthCredential) {
Log.i(LCAT, "");
// Sign in with the credential
// ...
}
@Override
public void onVerificationFailed(FirebaseException e) {
Log.i(LCAT, "");
// ...
}
});
}
private void sendBack(KrollDict event) {
KrollFunction onverificationcompleted = (KrollFunction) getProperty("onverificationcompleted");
if (onverificationcompleted != null) {
onverificationcompleted.call(getKrollObject(),
new Object[] { event });
}
if (this.hasListeners("verificationcompleted")) {
this.fireEvent("verificationcompleted", event);
}
if (onVerificationCompletedCallback != null) {
onVerificationCompletedCallback.call(getKrollObject(),
new Object[] { event });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment