/** * Delete a model from your project. * * @param {string} modelId The ID of the model you want to delete. */ const deleteModel = async (modelId) => { await ml.deleteModel(modelId); }
/** Get profile endpoint. */ app.get('/profile', function (req, res) { // Get session cookie. const sessionCookie = req.cookies.session || ''; // Get the session cookie and verify it. In this case, we are verifying if the // Firebase session was revoked, user deleted/disabled, etc. admin.auth().verifySessionCookie(sessionCookie, true /** check if revoked. */) .then(function(decodedClaims) { // Serve content for signed in user. return serveContentForUser('/profile', req, res, decodedClaims); }).catch(function(error) { // Force user to login. res.redirect('/'); }); });
/** * List the models in your project. * * @param {string=} filter An optional filter string to limit your results. See * https://firebase.google.com/docs/ml-kit/manage-hosted-models#list_your_projects_models */ const listModels = async (filter = null) => { let listOptions = filter == null ? {} : { filter: filter }; let models; // `listModels()` returns a page token if there are additional pages of // results that weren't returned by the request. We'll keep making requests // with the tokens until we've printed everything. let pageToken = null; do { if (pageToken) listOptions.pageToken = pageToken; ({models, pageToken} = await ml.listModels(listOptions)); for (const model of models) { const tags = model.tags == null ? '' : model.tags.join(", "); console.log(`${model.displayName}\t\t${model.modelId}\t ${tags}`); } } while (pageToken != null); }
/** * Send an email listing the top posts every Sunday. */ function startWeeklyTopPostEmailer() { // Run this job every Sunday at 2:30pm. schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function () { // List the top 5 posts. // [START top_posts_query] const topPostsRef = firebase.database().ref('/posts').orderByChild('starCount').limitToLast(5); // [END top_posts_query] const allUserRef = firebase.database().ref('/users'); Promise.all([topPostsRef.once('value'), allUserRef.once('value')]).then(function(resp) { const topPosts = resp[0].val(); const allUsers = resp[1].val(); const emailText = createWeeklyTopPostsEmailHtml(topPosts); sendWeeklyTopPostEmail(allUsers, emailText); }).catch(function(error) { console.log('Failed to start weekly top posts emailer:', error); }); }); console.log('Weekly top posts emailer started...'); }
/** * Upload a TensorFlow Lite model to your project and publish it. * * @param {string} tflite Path to the tflite file you want to upload. * @param {string} displayName A name to identify the model in your Firebase * project. This is the name you use from your app to load the model. * @param {?Array<string>=} tags Optional tags to help with model management. */ const uploadModel = async (tflite, displayName, tags = null) => { console.log('Uploading model to Cloud Storage...'); const files = await storageBucket.upload(tflite); const bucket = files[0].metadata.bucket; const name = files[0].metadata.name; const gcsUri = `gs://${bucket}/${name}`; const modelSpec = { displayName: displayName, tfliteModel: { gcsTfliteUri: gcsUri }, }; if (tags != null) { modelSpec.tags = tags; } const model = await ml.createModel(modelSpec); await ml.publishModel(model.modelId); const tagList = model.tags == null ? '' : model.tags.join(", "); console.log('Model uploaded and published:'); console.log(`${model.displayName}\t\t${model.modelId}\t ${tagList}`); }
/** User delete endpoint. */ app.get('/delete', function (req, res) { const sessionCookie = req.cookies.session || ''; res.clearCookie('session'); if (sessionCookie) { // Verify user and then delete the user. admin.auth().verifySessionCookie(sessionCookie, true).then(function(decodedClaims) { return admin.auth().deleteUser(decodedClaims.sub); }) .then(function() { // Redirect to login page on success. res.redirect('/'); }) .catch(function() { // Redirect to login page on error. res.redirect('/'); }); } else { // Redirect to login page when no session cookie available. res.redirect('/'); } });
/** * Checks if a user is signed in and if so, redirects to profile page. * @param {string} url The URL to check if signed in. * @return {function} The middleware function to run. */ function checkIfSignedIn(url) { return function(req, res, next) { if (req.url == url) { const sessionCookie = req.cookies.session || ''; // User already logged in. Redirect to profile page. admin.auth().verifySessionCookie(sessionCookie).then(function(decodedClaims) { res.redirect('/profile'); }).catch(function(error) { next(); }); } else { next(); } } }
/** User signout endpoint. */ app.get('/logout', function (req, res) { // Clear cookie. const sessionCookie = req.cookies.session || ''; res.clearCookie('session'); // Revoke session too. Note this will revoke all user sessions. if (sessionCookie) { admin.auth().verifySessionCookie(sessionCookie, true).then(function(decodedClaims) { return admin.auth().revokeRefreshTokens(decodedClaims.sub); }) .then(function() { // Redirect to login page on success. res.redirect('/'); }) .catch(function() { // Redirect to login page on error. res.redirect('/'); }); } else { // Redirect to login page when no session cookie available. res.redirect('/'); } });
/** * Delete a model from your project. * * @param {string} modelId The ID of the model you want to delete. */ const deleteModel = async (modelId) => { await ml.deleteModel(modelId); }
/** Get profile endpoint. */ app.get('/profile', function (req, res) { // Get session cookie. const sessionCookie = req.cookies.session || ''; // Get the session cookie and verify it. In this case, we are verifying if the // Firebase session was revoked, user deleted/disabled, etc. admin.auth().verifySessionCookie(sessionCookie, true /** check if revoked. */) .then(function(decodedClaims) { // Serve content for signed in user. return serveContentForUser('/profile', req, res, decodedClaims); }).catch(function(error) { // Force user to login. res.redirect('/'); }); });
/** * Checks if a user is signed in and if so, redirects to profile page. * @param {string} url The URL to check if signed in. * @return {function} The middleware function to run. */ function checkIfSignedIn(url) { return function(req, res, next) { if (req.url == url) { const sessionCookie = req.cookies.session || ''; // User already logged in. Redirect to profile page. admin.auth().verifySessionCookie(sessionCookie).then(function(decodedClaims) { res.redirect('/profile'); }).catch(function(error) { next(); }); } else { next(); } } }
/** * List the models in your project. * * @param {string=} filter An optional filter string to limit your results. See * https://firebase.google.com/docs/ml-kit/manage-hosted-models#list_your_projects_models */ const listModels = async (filter = null) => { let listOptions = filter == null ? {} : { filter: filter }; let models; // `listModels()` returns a page token if there are additional pages of // results that weren't returned by the request. We'll keep making requests // with the tokens until we've printed everything. let pageToken = null; do { if (pageToken) listOptions.pageToken = pageToken; ({models, pageToken} = await ml.listModels(listOptions)); for (const model of models) { const tags = model.tags == null ? '' : model.tags.join(", "); console.log(`${model.displayName}\t\t${model.modelId}\t ${tags}`); } } while (pageToken != null); }
/** * Send an email listing the top posts every Sunday. */ function startWeeklyTopPostEmailer() { // Run this job every Sunday at 2:30pm. schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function () { // List the top 5 posts. // [START top_posts_query] const topPostsRef = firebase.database().ref('/posts').orderByChild('starCount').limitToLast(5); // [END top_posts_query] const allUserRef = firebase.database().ref('/users'); Promise.all([topPostsRef.once('value'), allUserRef.once('value')]).then(function(resp) { const topPosts = resp[0].val(); const allUsers = resp[1].val(); const emailText = createWeeklyTopPostsEmailHtml(topPosts); sendWeeklyTopPostEmail(allUsers, emailText); }).catch(function(error) { console.log('Failed to start weekly top posts emailer:', error); }); }); console.log('Weekly top posts emailer started...'); }
/** User delete endpoint. */ app.get('/delete', function (req, res) { const sessionCookie = req.cookies.session || ''; res.clearCookie('session'); if (sessionCookie) { // Verify user and then delete the user. admin.auth().verifySessionCookie(sessionCookie, true).then(function(decodedClaims) { return admin.auth().deleteUser(decodedClaims.sub); }) .then(function() { // Redirect to login page on success. res.redirect('/'); }) .catch(function() { // Redirect to login page on error. res.redirect('/'); }); } else { // Redirect to login page when no session cookie available. res.redirect('/'); } });
/** User signout endpoint. */ app.get('/logout', function (req, res) { // Clear cookie. const sessionCookie = req.cookies.session || ''; res.clearCookie('session'); // Revoke session too. Note this will revoke all user sessions. if (sessionCookie) { admin.auth().verifySessionCookie(sessionCookie, true).then(function(decodedClaims) { return admin.auth().revokeRefreshTokens(decodedClaims.sub); }) .then(function() { // Redirect to login page on success. res.redirect('/'); }) .catch(function() { // Redirect to login page on error. res.redirect('/'); }); } else { // Redirect to login page when no session cookie available. res.redirect('/'); } });