How to use firebase-admin - 10 common examples

To help you get started, we’ve selected a few firebase-admin examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lineupninja / ninjafire / test / embedded.ts View on Github external
it('should retrieve belongsTo and hasMany relationships in hasMany embedded record', async () => {

        /**
         * A record embedded with a hasMany relationship can contain belongsTo and hasMany relationships to other records, confirm they are retrieved successfully
         *
         * This retrieves the data created in the previous test
         */

        const store: Store = new Store(admin.database(), { basePath });
        const post: Post = await store.findRecord(Post, testData.post[1].id);

        const firstPhoto = post.photos.filter((photo: Photo) => photo.id === testData.photo[1].id)[0];
        expect(firstPhoto, 'Photo with id of photo1 is in post photos').to.not.be.an('undefined');

        const takenBy = await firstPhoto.takenBy;
        expect(takenBy.name, 'taken by is user3').to.equal(testData.user[3].name);

        const taggedUsers = firstPhoto.taggedUsers;

        // Firebase does not preserve array ordering so the two tagged users

        await Promise.all(taggedUsers.map(async (taggedUserPromise: ModelOrPromise) => {
            const user = await taggedUserPromise;
            if (user.id === testData.user[1].id) {
                expect(user.name, 'tagged user 1 is user 1').to.equal(testData.user[1].name);
github celo-org / celo-monorepo / packages / faucet / src / test-driver.ts View on Github external
// await printAccounts(pool)

    // console.log('after')

    // const tx = await sendFunds({
    //   providerUrl: 'http://34.83.69.157:8545',
    //   fromPk: '0x0e08757b5e1efd8fc93e25188f2a2fea51c9bff6438729c3c7208de2169f9e7a',
    //   to: '0x193eab124b946b79461b484812dca10afb3b2294',
    //   valueEth: '0.05',
    // })
    // console.log(tx)
  } catch (err) {
    console.error('Failed')
    console.error(err)
  } finally {
    await admin.app().delete()
  }
}
github NUS-ALSET / achievements / functions / src / ltiLogin.js View on Github external
function get_token(data, res, exists) {
  //Create a new user.
  let uid = data["user_id"] + "@" + data["oauth_consumer_key"];
  admin
    .auth()
    .createCustomToken(uid)
    .then(function(customToken) {
      console.log("Custom token here: ", customToken);
      let message = "user_id -> " + data["user_id"] + "\n";
      message += "oauth_consumer_key -> " + data["oauth_consumer_key"] + "\n";
      message += "create user -> " + uid + "\n";
      message += "redirect to\n\n ";
      message += data["APP_REDIRECT_URL"] + customToken;
      var link = data["APP_REDIRECT_URL"] + customToken;

      var newString = uid.split(".").join("---");
      // data['oauth_consumer_key'] = newString;

      if (exists) {
        admin
github androidthings / photobooth / firebase / functions / assistant-app / request-handlers.js View on Github external
function sendFirebaseCommand (command) {
  // figure out how to delay the set about of time
  // i.e. wait(delay);

  // Define capture command playload for FCM message
  var payload = {
    data: {
      cmd: command
    }
  };
  // Send a message to devices subscribed to the provided topic.
  admin.messaging().sendToTopic(TOPIC, payload)
    .then(function (response) {
      // See the MessagingTopicResponse reference documentation for the
      // contents of response.
      console.log('Successfully sent message:', response);
      console.log('"' + KEY_FOR_COMMAND + ': ' + command + '"' + ' to topic ' + TOPIC);
    })
    .catch(function (error) {
      console.log('Error sending message:', error);
      console.log('"' + KEY_FOR_COMMAND + ': ' + command + '"' + ' to topic ' + TOPIC);
    });
}
github andrewevans0102 / how-to-build-a-firebase-api / functions / index.js View on Github external
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));

var serviceAccount = require("./permissions.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://fir-api-9a206.firebaseio.com"
});
const db = admin.firestore();

// create
app.post('/api/create', (req, res) => {
    (async () => {
        try {
            await db.collection('items').doc('/' + req.body.id + '/').create({item: req.body.item});
            return res.status(200).send();
        } catch (error) {
            console.log(error);
            return res.status(500).send(error);
        }
      })();
  });

// read item
app.get('/api/read/:item_id', (req, res) => {
github moflo / jpvcdb / src / app / scripts / add-airtable-records.js View on Github external
const admin = require('firebase-admin')
const chalk = require('chalk')
var Airtable = require('airtable');


// init firebase
const serviceAccount = require('../credentials/serviceAccountKey.json')
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://jpvcdb.firebaseio.com"
})
const db = require('firebase-admin').firestore()
db.settings({timestampsInSnapshots: true})  // Using Timestamps

const airTableAccount = require('../credentials/airTableKey.json')
var base = new Airtable({apiKey: airTableAccount.apiKey}).base(airTableAccount.appKey);

// add seed posts
console.log(chalk.blue(`Adding seed post data...`))

base('Table 2').select({
    // Selecting the first 3 records in Grid view:
    // maxRecords: 3,
    pageSize: 10,
    view: "Grid view",
    cellFormat: 'json'
}).eachPage(function page(records, fetchNextPage) {
    // This function (`page`) will get called for each page of records.
github devuxd / SeeCodeRun / functions / index.js View on Github external
parentPastebinId: 0,
        children: 0
    },
    users: 0
};

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: dataBaseUrl,
    // storageBucket: "firebase-seecoderun.appspot.com",
    databaseAuthVariableOverride: {
        uid: uid
    }
});

const databaseRef = admin.database();
// Provide custom logger which prefixes log statements with "[FIREBASE]"
// Disable logging across page refreshes
//   databaseRef.enableLogging(function (message) {
//       console.log("[FIREBASE]", message);
//     },
//     false);
let databaseRootRef = databaseRef.ref(dataBaseRoot);

// Data functions
const makeNewPastebin = onComplete => {
    return databaseRootRef
        .push(defaultPastebinScheme, onComplete);
};

const makeNewPastebinId = () => {
    return databaseRootRef.push(0).key;
github machinelabs / machinelabs / firebase / functions / src / post-lab-write.ts View on Github external
console.log('Post lab write: updating indices');

  delta[`/idx/user_labs/${data.user_id}/${data.id}`] = true;
  delta[`/idx/user_visible_labs/${data.user_id}/${data.id}`] = data.hidden ? null : true;

  if (data.hidden || data.is_private) {
    delta[`/idx/recent_labs/${data.id}`] = null;
  }

  // We need to find all executions that are attached to this lab
  // and hide them as well.
  //
  // Notice we don't update `lab_visible_executions` because we only
  // need to hide them for the users not for the labs.
  return admin
    .database()
    .ref(`/idx/lab_executions/${data.id}`)
    .once('value')
    .then(snapshot => snapshot.val())
    .then(val => (val ? Object.keys(val) : []))
    .then(executionIds => {
      executionIds.forEach(id => {
        delta[`/idx/user_visible_executions/${data.user_id}/${id}`] = data.hidden ? null : true;
      });
    })
    .then(_ =>
      admin
        .database()
        .ref()
        .update(delta)
    );
github OmarAliSaid / android-paypal-example / server / index.js View on Github external
var bodyParser = require('body-parser');
var paypal = require('paypal-rest-sdk');
var express = require('express');
var app = express();

// Initialize the app with a service account, granting admin privileges
var serviceAccount = require("path/to/serviceAccountKey.json");

paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': 'REPLACE WITH PAYPAL APP CLIENT_ID',
  'client_secret': 'REPLACE WITH PAYPAL APP SECRET'
});

firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccount),
  databaseURL: "https://.firebaseio.com"
});

// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port  = process.env.PORT || 5000; // set our port

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);


// get an instance of the express Router
github Festify / app / functions / lib / spotify-auth.ts View on Github external
photoURL: (user.images && user.images.length > 0 && isValidUrl(user.images[0].url))
            ? user.images[0].url
            : undefined,
        email: user.email,
    };

    let loginUid;
    try {
        if (linkedAccountUid) {
            await admin.auth().updateUser(linkedAccountUid, userMeta);
            loginUid = linkedAccountUid;
        } else {
            // If user does not exist we create it.

            const [oldUser, newUser] = await Promise.all([
                admin.auth().getUser(ctx.auth.uid),
                admin.auth().createUser({
                    ...userMeta,
                    displayName: user.display_name || user.id,
                }),
            ]);

            await admin.auth().setCustomUserClaims(newUser.uid, { spotify: spotifyId });
            if (oldUser.providerData.length === 0) {
                await transferData(ctx.auth.uid, newUser.uid);
            }

            loginUid = newUser.uid;
        }
    } catch (error) {
        if (error.code === 'auth/invalid-display-name') {
            console.error(error, userMeta.displayName);