This commit is contained in:
Chris Bianca 2017-08-22 17:29:21 +01:00
commit 7ea92751a9
5 changed files with 96 additions and 96 deletions

View File

@ -581,7 +581,7 @@ class RNFirebaseAuth extends ReactContextBaseJavaModule {
// Reset the verification Id // Reset the verification Id
mVerificationId = null; mVerificationId = null;
PhoneAuthProvider.getInstance(firebaseAuth).verifyPhoneNumber(phoneNumber, 120, TimeUnit.SECONDS, PhoneAuthProvider.getInstance(firebaseAuth).verifyPhoneNumber(phoneNumber, 60, TimeUnit.SECONDS,
mReactContext.getCurrentActivity(), new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { mReactContext.getCurrentActivity(), new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override @Override
public void onVerificationCompleted(final PhoneAuthCredential phoneAuthCredential) { public void onVerificationCompleted(final PhoneAuthCredential phoneAuthCredential) {
@ -596,7 +596,7 @@ class RNFirebaseAuth extends ReactContextBaseJavaModule {
event.putMap("user", user); event.putMap("user", user);
event.putString("type", "user"); event.putString("type", "user");
event.putString("appName", appName); event.putString("appName", appName);
event.putString("appName", phoneAuthCredential.getSmsCode()); event.putString("smsCode", phoneAuthCredential.getSmsCode());
event.putString("phoneAuthRequestKey", phoneAuthRequestKey); event.putString("phoneAuthRequestKey", phoneAuthRequestKey);
Utils.sendEvent(mReactContext, "phone_auth_event", event); Utils.sendEvent(mReactContext, "phone_auth_event", event);
} }
@ -618,6 +618,7 @@ class RNFirebaseAuth extends ReactContextBaseJavaModule {
@Override @Override
public void onVerificationFailed(FirebaseException e) { public void onVerificationFailed(FirebaseException e) {
Log.d(TAG, "signInWithPhoneNumber:verification:failed");
WritableMap event = Arguments.createMap(); WritableMap event = Arguments.createMap();
WritableMap error = getJSError(e); WritableMap error = getJSError(e);
event.putMap("error", error); event.putMap("error", error);
@ -650,6 +651,9 @@ class RNFirebaseAuth extends ReactContextBaseJavaModule {
FirebaseApp firebaseApp = FirebaseApp.getInstance(appName); FirebaseApp firebaseApp = FirebaseApp.getInstance(appName);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(firebaseApp); FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(firebaseApp);
// Log.d(TAG, "_confirmVerificationCode:verificationId: " + verificationId);
// Log.d(TAG, "_confirmVerificationCode:verificationCode: " + verificationCode);
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode); PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);
firebaseAuth.signInWithCredential(credential) firebaseAuth.signInWithCredential(credential)
@ -657,7 +661,7 @@ class RNFirebaseAuth extends ReactContextBaseJavaModule {
@Override @Override
public void onComplete(@NonNull Task<AuthResult> task) { public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) { if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:onComplete:success"); Log.d(TAG, "_confirmVerificationCode:signInWithCredential:onComplete:success");
WritableMap event = Arguments.createMap(); WritableMap event = Arguments.createMap();
WritableMap user = firebaseUserToMap(task.getResult().getUser()); WritableMap user = firebaseUserToMap(task.getResult().getUser());
event.putMap("user", user); event.putMap("user", user);
@ -668,7 +672,7 @@ class RNFirebaseAuth extends ReactContextBaseJavaModule {
promiseWithUser(task.getResult().getUser(), promise); promiseWithUser(task.getResult().getUser(), promise);
} else { } else {
Exception exception = task.getException(); Exception exception = task.getException();
Log.e(TAG, "signInWithCredential:onComplete:failure", exception); Log.e(TAG, "_confirmVerificationCode:signInWithCredential:onComplete:failure", exception);
WritableMap event = Arguments.createMap(); WritableMap event = Arguments.createMap();
WritableMap error = getJSError(exception); WritableMap error = getJSError(exception);
event.putMap("error", error); event.putMap("error", error);

View File

@ -382,12 +382,12 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
* @param key * @param key
* @param path * @param path
* @param modifiers * @param modifiers
* @param eventName * @param eventType
* @param promise * @param promise
*/ */
@ReactMethod @ReactMethod
public void once(String appName, String key, String path, ReadableArray modifiers, String eventName, Promise promise) { public void once(String appName, String key, String path, ReadableArray modifiers, String eventType, Promise promise) {
getInternalReferenceForApp(appName, key, path, modifiers).once(eventName, promise); getInternalReferenceForApp(appName, key, path, modifiers).once(eventType, promise);
} }
/** /**
@ -400,7 +400,6 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
public void on(String appName, ReadableMap props) { public void on(String appName, ReadableMap props) {
getInternalReferenceForApp(appName, props) getInternalReferenceForApp(appName, props)
.on( .on(
this,
props.getString("eventType"), props.getString("eventType"),
props.getMap("registration") props.getMap("registration")
); );

View File

@ -82,7 +82,8 @@ class RNFirebaseDatabaseReference {
} }
/** /**
* TODO * Remove an event listener by key, will remove either a ValueEventListener or
* a ChildEventListener
* *
* @param eventRegistrationKey * @param eventRegistrationKey
*/ */
@ -204,28 +205,27 @@ class RNFirebaseDatabaseReference {
/** /**
* Handles a React Native JS '.on(..)' request and initializes listeners. * Handles a React Native JS '.on(..)' request and initializes listeners.
* *
* @param database
* @param registration * @param registration
*/ */
void on(RNFirebaseDatabase database, String eventType, ReadableMap registration) { void on(String eventType, ReadableMap registration) {
if (eventType.equals("value")) { if (eventType.equals("value")) {
addValueEventListener(registration, database); addValueEventListener(registration);
} else { } else {
addChildEventListener(registration, eventType, database); addChildEventListener(registration, eventType);
} }
} }
/** /**
* Handles a React Native JS 'once' request. * Handles a React Native JS 'once' request.
* *
* @param eventName * @param eventType
* @param promise * @param promise
*/ */
void once(String eventName, Promise promise) { void once(String eventType, Promise promise) {
if (eventName.equals("value")) { if (eventType.equals("value")) {
addOnceValueEventListener(promise); addOnceValueEventListener(promise);
} else { } else {
addChildOnceEventListener(eventName, promise); addChildOnceEventListener(eventType, promise);
} }
} }
@ -235,9 +235,8 @@ class RNFirebaseDatabaseReference {
* *
* @param registration * @param registration
* @param eventType * @param eventType
* @param database
*/ */
private void addChildEventListener(final ReadableMap registration, final String eventType, final RNFirebaseDatabase database) { private void addChildEventListener(final ReadableMap registration, final String eventType) {
final String eventRegistrationKey = registration.getString("eventRegistrationKey"); final String eventRegistrationKey = registration.getString("eventRegistrationKey");
final String registrationCancellationKey = registration.getString("registrationCancellationKey"); final String registrationCancellationKey = registration.getString("registrationCancellationKey");
@ -286,11 +285,9 @@ class RNFirebaseDatabaseReference {
* Add a native .on('value',.. ) event listener. * Add a native .on('value',.. ) event listener.
* *
* @param registration * @param registration
* @param database
*/ */
private void addValueEventListener(final ReadableMap registration, final RNFirebaseDatabase database) { private void addValueEventListener(final ReadableMap registration) {
final String eventRegistrationKey = registration.getString("eventRegistrationKey"); final String eventRegistrationKey = registration.getString("eventRegistrationKey");
final String registrationCancellationKey = registration.getString("registrationCancellationKey");
if (!hasEventListener(eventRegistrationKey)) { if (!hasEventListener(eventRegistrationKey)) {
ValueEventListener valueEventListener = new ValueEventListener() { ValueEventListener valueEventListener = new ValueEventListener() {

View File

@ -5,9 +5,9 @@ import com.android.build.OutputFile
project.ext.react = [ project.ext.react = [
// whether to bundle JS and assets in staging mode // whether to bundle JS and assets in staging mode
bundleInDebug : true, bundleInDebug : false,
jsBundleDirDebug: "$buildDir/intermediates/assets/debug", jsBundleDirDebug : "$buildDir/intermediates/assets/debug",
nodeExecutableAndArgs : ["/usr/local/bin/node"] nodeExecutableAndArgs: ["/usr/local/bin/node"]
] ]
apply from: "../../node_modules/react-native/react.gradle" apply from: "../../node_modules/react-native/react.gradle"

View File

@ -1,91 +1,91 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import { View, Button, Text } from 'react-native'; import { View, Button, Text, TextInput, Image } from 'react-native';
import sinon from 'sinon';
import 'should-sinon';
import Promise from 'bluebird';
import firebase from './firebase'; import fb from './firebase';
import DatabaseContents from './tests/support/DatabaseContents'; const firebase = fb.native;
const successImageUri = 'https://cdn.pixabay.com/photo/2015/06/09/16/12/icon-803718_1280.png';
export default class HomeScreen extends Component { export default class PhoneAuthTest extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
timeTaken: '', user: null,
message: '',
codeInput: '',
phoneNumber: '+44',
confirmResult: null,
}; };
} }
clickMe = () => { signIn = () => {
this.setState({ timeTaken: 'Running...' }); const { phoneNumber } = this.state;
let start = null; this.setState({ message: 'Sending code ...' });
Promise.all([
firebase.native.database().ref('tests/types').set(DatabaseContents.DEFAULT),
firebase.native.database().ref('tests/priority').setWithPriority({
foo: 'bar',
}, 666),
firebase.native.database().ref('tests/query').set(DatabaseContents.QUERY),
]).then(() => {
start = Date.now();
return Promise.each(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => {
// Setup
const ref = firebase.native.database().ref(`tests/types/${dataRef}`);
const currentDataValue = DatabaseContents.DEFAULT[dataRef];
const callbackA = sinon.spy(); firebase.auth()
const callbackB = sinon.spy(); .signInWithPhoneNumber(phoneNumber)
.onCodeSent(confirmResult => this.setState({ confirmResult, message: 'Code has been sent!' }))
.then(user => this.setState({ user: user.toJSON() }))
.catch(console.error);
};
// Test confirmCode = () => {
const { codeInput, confirmResult } = this.state;
await new Promise((resolve) => { if (confirmResult && codeInput.length) {
ref.on('value', (snapshot) => { confirmResult.confirm(codeInput)
callbackA(snapshot.val()); .then(() => this.setState({ message: 'Code Confirmed!' }))
resolve(); .catch(error => this.setState({ message: `Code Confirm Error: ${error.message}` }));
}); }
});
await new Promise((resolve) => {
ref.on('value', (snapshot) => {
callbackB(snapshot.val());
resolve();
});
});
callbackA.should.be.calledWith(currentDataValue);
callbackA.should.be.calledOnce();
callbackB.should.be.calledWith(currentDataValue);
callbackB.should.be.calledOnce();
const newDataValue = DatabaseContents.NEW[dataRef];
await ref.set(newDataValue);
await new Promise((resolve) => {
setTimeout(() => resolve(), 5);
});
callbackA.should.be.calledWith(newDataValue);
callbackB.should.be.calledWith(newDataValue);
callbackA.should.be.calledTwice();
callbackB.should.be.calledTwice();
// Tear down
ref.off('value');
return Promise.resolve();
});
}).then(() => {
this.setState({ timeTaken: `Took ${Date.now() - start}` });
}).catch(console.error);
}; };
render() { render() {
const { message, user, codeInput, confirmResult, phoneNumber } = this.state;
return ( return (
<View style={{ marginTop: 15, backgroundColor: '#000' }}> <View style={{ flex: 1 }}>
<Button title="Run Test" onPress={this.clickMe} /> {!user && !confirmResult ? (
<Text style={{ color: '#fff' }}>{this.state.timeTaken || ''}</Text> <View style={{ padding: 25 }}>
<Text>Enter phone number:</Text>
<TextInput
autoFocus
style={{ height: 40, marginTop: 15, marginBottom: 15 }}
onChangeText={value => this.setState({ phoneNumber: value })}
placeholder={'Phone number ... '}
value={phoneNumber}
/>
<Button title="Sign In" color="green" onPress={this.signIn} />
</View>
) : null}
{message.length ? (
<Text style={{ padding: 5, backgroundColor: '#000', color: '#fff' }}>{message}</Text>) : null}
{!user && confirmResult ? (
<View style={{ marginTop: 25, padding: 25 }}>
<Text>Enter verification code below:</Text>
<TextInput
autoFocus
style={{ height: 40, marginTop: 15, marginBottom: 15 }}
onChangeText={value => this.setState({ codeInput: value })}
placeholder={'Code ... '}
value={codeInput}
/>
<Button title="Confirm Code" color="#841584" onPress={this.confirmCode} />
</View>
) : null}
{ user ? (
<View
style={{
padding: 15,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#77dd77',
flex: 1,
}}
>
<Image source={{ uri: successImageUri }} style={{ width: 100, height: 100, marginBottom: 25 }} />
<Text style={{ fontSize: 25 }}>Signed In!</Text>
<Text>{JSON.stringify(user)}</Text>
</View>
) : null}
</View> </View>
); );
} }