Skip to content

Commit

Permalink
Adds Auth tests to demo app for web worker environment functionality. (
Browse files Browse the repository at this point in the history
…#567)

This helps test that Auth API works as expected in that environment.
  • Loading branch information
bojeil-google authored Mar 16, 2018
1 parent df183a5 commit d3ec2e0
Show file tree
Hide file tree
Showing 4 changed files with 261 additions and 1 deletion.
55 changes: 55 additions & 0 deletions packages/auth/demo/public/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,58 @@ if ('serviceWorker' in navigator) {
console.log('Registration failed with ' + error.message);
});
}

var webWorker = null;
if (window.Worker) {
webWorker = new Worker('/web-worker.js');
/**
* Handles the incoming message from the web worker.
* @param {!Object} e The message event received.
*/
webWorker.onmessage = function(e) {
console.log('User data passed through web worker: ', e.data);
switch (e.data.type) {
case 'GET_USER_INFO':
alertSuccess(
'User data passed through web worker: ' + JSON.stringify(e.data));
break;
case 'RUN_TESTS':
if (e.data.status == 'success') {
alertSuccess('Web worker tests ran successfully!');
} else {
alertError('Error: ' + JSON.stringify(e.data.error));
}
break;
default:
return;
}
};
}

/**
* Asks the web worker, if supported in current browser, to return the user info
* corresponding to the currentUser as seen within the worker.
*/
function onGetCurrentUserDataFromWebWorker() {
if (webWorker) {
webWorker.postMessage({type: 'GET_USER_INFO'});
} else {
alertError('Error: Web workers are not supported in the current browser!');
}
}

/**
* Runs various Firebase Auth tests in a web worker environment and confirms the
* expected behavior. This is useful for manual testing in different browsers.
* @param {string} googleIdToken The Google ID token to sign in with.
*/
function runWebWorkerTests(googleIdToken) {
if (webWorker) {
webWorker.postMessage({
type: 'RUN_TESTS',
googleIdToken: googleIdToken
});
} else {
alertError('Error: Web workers are not supported in the current browser!');
}
}
12 changes: 12 additions & 0 deletions packages/auth/demo/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,15 @@

<div class="tab-content">
<div class="tab-pane active" id="auth-section">
<!-- Worker tests -->
<div class="group">Web Worker Testing</div>
<form class="form form-bordered no-submit">
<button class="btn btn-block btn-primary"
id="run-web-worker-tests">
Run Tests
</button>
</form>

<!-- Persistence-->
<div class="group">Auth State Persistence</div>
<form class="form form-bordered no-submit">
Expand Down Expand Up @@ -441,6 +450,9 @@
<button class="btn btn-block btn-default" id="refresh-token">
Refresh ID Token
</button>
<button class="btn btn-block btn-default" id="get-token-worker">
Get ID Token from Web Worker
</button>
<button class="btn btn-block btn-danger" id="sign-out">
Sign Out
</button>
Expand Down
21 changes: 20 additions & 1 deletion packages/auth/demo/public/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -1219,6 +1219,22 @@ function checkDatabaseAuthAccess() {
}


/** Runs all web worker tests if web workers are supported. */
function onRunWebWorkTests() {
if (!webWorker) {
alertError('Error: Web workers are not supported in the current browser!');
return;
}
var onError = function(error) {
alertError('Error: ' + error.code);
};
auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then(function(result) {
runWebWorkerTests(result.credential.idToken);
}, onError);
}


/**
* Initiates the application by setting event listeners on the various buttons.
*/
Expand All @@ -1236,7 +1252,7 @@ function initApp(){
// The action code for email verification or password reset
// can be passed in the url address as a parameter, and for convenience
// this preloads the input field.
populateActionCodes();
populateActionCodes();

// Allows to login the user if previously logged in.
if (auth.onIdTokenChanged) {
Expand Down Expand Up @@ -1356,6 +1372,7 @@ function initApp(){
$('#confirm-email-verification').click(onApplyActionCode);
$('#get-token').click(onGetIdToken);
$('#refresh-token').click(onRefreshToken);
$('#get-token-worker').click(onGetCurrentUserDataFromWebWorker);
$('#sign-out').click(onSignOut);

$('.popup-redirect-provider').click(onPopupRedirectProviderClick);
Expand All @@ -1375,6 +1392,8 @@ function initApp(){

$('#fetch-providers-for-email').click(onFetchProvidersForEmail);
$('#fetch-sign-in-methods-for-email').click(onFetchSignInMethodsForEmail);

$('#run-web-worker-tests').click(onRunWebWorkTests);
}

$(initApp);
174 changes: 174 additions & 0 deletions packages/auth/demo/public/web-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
/**
* @fileoverview Web worker for Firebase Auth test app application. The
* web worker tries to run operations on the Auth instance for testing purposes.
*/

importScripts('/dist/firebase-app.js');
importScripts('/dist/firebase-auth.js');
importScripts('config.js');

// Initialize the Firebase app in the web worker.
firebase.initializeApp(config);

/**
* Returns a promise that resolves with an ID token if available.
* @return {!Promise<?string>} The promise that resolves with an ID token if
* available. Otherwise, the promise resolves with null.
*/
var getIdToken = function() {
return new Promise(function(resolve, reject) {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
user.getIdToken().then(function(idToken) {
resolve(idToken);
}, function(error) {
resolve(null);
});
} else {
resolve(null);
}
});
}).catch(function(error) {
console.log(error);
});
};

/**
* Runs various Firebase Auth tests in a web worker environment and confirms the
* expected behavior. This is useful for manual testing in different browsers.
* @param {string} googleIdToken The Google ID token to sign in with.
* @return {!Promise<void>} A promise that resolves when all tests run
* successfully.
*/
var runWorkerTests = function(googleIdToken) {
var inMemoryPersistence = firebase.auth.Auth.Persistence.NONE;
var expectedDisplayName = 'Test User';
var oauthCredential = firebase.auth.GoogleAuthProvider.credential(
googleIdToken);
var provider = new firebase.auth.GoogleAuthProvider();
var OPERATION_NOT_SUPPORTED_CODE =
'auth/operation-not-supported-in-this-environment';
var email = 'user' + Math.floor(Math.random() * 10000000000).toString() +
'@example.com';
var pass = 'password';
return firebase.auth().setPersistence(inMemoryPersistence)
.then(function() {
firebase.auth().useDeviceLanguage();
return firebase.auth().signInAnonymously();
})
.then(function(user) {
if (!user.uid) {
throw new Error('signInAnonymously unexpectedly failed!');
}
return user.updateProfile({displayName: expectedDisplayName});
})
.then(function() {
if (firebase.auth().currentUser.displayName != expectedDisplayName) {
throw new Error('Profile update failed!');
}
return firebase.auth().currentUser.delete();
})
.then(function() {
if (firebase.auth().currentUser) {
throw new Error('currentUser.delete unexpectedly failed!');
}
return firebase.auth().createUserWithEmailAndPassword(email, pass);
})
.then(function(user) {
if (user.email != email) {
throw new Error(
'createUserWithEmailAndPassword unexpectedly failed!');
}
return firebase.auth().fetchProvidersForEmail(email);
}).then(function(providers) {
if (providers.length == 0 || providers[0] != 'password') {
throw new Error('fetchProvidersForEmail failed!');
}
return firebase.auth().signInWithEmailAndPassword(email, pass);
})
.then(function(user) {
if (user.email != email) {
throw new Error('signInWithEmailAndPassword unexpectedly failed!');
}
return user.delete();
})
.then(function() {
return firebase.auth().signInWithPopup(provider)
.catch(function(error) {
if (error.code != OPERATION_NOT_SUPPORTED_CODE) {
throw error;
}
});
})
.then(function() {
return firebase.auth().signInWithRedirect(provider)
.catch(function(error) {
if (error.code != OPERATION_NOT_SUPPORTED_CODE) {
throw error;
}
});
})
.then(function() {
return Promise.resolve().then(function() {
return new firebase.auth.RecaptchaVerifier('id');
}).then(function() {
throw new Error(
'RecaptchaVerifer instantiation succeeded unexpectedly!');
}).catch(function(error) {
if (error.code != OPERATION_NOT_SUPPORTED_CODE) {
throw error;
}
});
})
.then(function() {
return firebase.auth().signInAndRetrieveDataWithCredential(
oauthCredential);
})
.then(function(result) {
if (!result.user ||
!result.user.uid ||
!result.credential ||
!result.additionalUserInfo) {
throw new Error(
'signInAndRetrieveDataWithCredential unexpectedly failed!');
}
return firebase.auth().signOut();
})
.then(function() {
if (firebase.auth().currentUser) {
throw new Error('signOut unexpectedly failed!');
}
});
};

/**
* Handles the incoming message from the main script.
* @param {!Object} e The message event received.
*/
self.onmessage = function(e) {
if (e.data && e.data.type) {
var result = {type: e.data.type};
switch (e.data.type) {
case 'GET_USER_INFO':
getIdToken().then(function(idToken) {
result.idToken = idToken;
result.uid = firebase.auth().currentUser &&
firebase.auth().currentUser.uid;
self.postMessage(result);
});
break;
case 'RUN_TESTS':
runWorkerTests(e.data.googleIdToken).then(function() {
result.status = 'success';
self.postMessage(result);
}).catch(function(error) {
result.status = 'failure';
result.error = error;
self.postMessage(result);
});
break;
default:
self.postMessage({});
}
}
};

0 comments on commit d3ec2e0

Please sign in to comment.