How to use the firebase-functions.auth function in firebase-functions

To help you get started, we’ve selected a few firebase-functions 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 TarikHuber / react-most-wanted / packages / cra-template-rmw / template / functions / auth / onCreate.f.js View on Github external
import admin from 'firebase-admin'
import moment from 'moment'
import nodemailer from 'nodemailer'

const gmailEmail = encodeURIComponent(
  functions.config().gmail ? functions.config().gmail.email : ''
)
const gmailPassword = encodeURIComponent(
  functions.config().gmail ? functions.config().gmail.password : ''
)

const mailTransport = nodemailer.createTransport(
  `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`
)

export default functions.auth.user().onCreate((uRecord, context) => {
  const userRecord = uRecord || {}
  const email = userRecord.email // The email of the user.
  const displayName = userRecord.displayName // The display name of the user.
  const creationTime = moment(userRecord.creationTime)
  const year = creationTime.format('YYYY')
  const month = creationTime.format('MM')
  const day = creationTime.format('DD')

  return admin
    .auth()
    .getUser(userRecord.uid)
    .then(user => {
      // User  without provider data
      console.log('Event user data', userRecord)

      // User with provider data
github drejohnson / sapper-graphql-firebase / functions / index.js View on Github external
const functions = require('firebase-functions')
const admin = require('firebase-admin')

admin.initializeApp(functions.config().firebase)

// On sign up.
exports.processSignUp = functions.auth.user().onCreate(user => {
  const customClaims = {
    'https://hasura.io/jwt/claims': {
      'x-hasura-default-role': 'user',
      'x-hasura-allowed-roles': ['user'],
      'x-hasura-user-id': user.uid,
    },
  }

  // Set custom user claims on this newly created user.
  return admin
    .auth()
    .setCustomUserClaims(user.uid, customClaims)
    .then(() => {
      return admin
        .firestore()
        .collection('metadata')
github TarikHuber / react-most-wanted / functions / auth / onDelete.f.js View on Github external
const functions = require('firebase-functions')
const admin = require('firebase-admin')
try { admin.initializeApp() } catch (e) { console.log(e) }
const nodemailer = require('nodemailer')
const gmailEmail = encodeURIComponent(functions.config().gmail ? functions.config().gmail.email : '')
const gmailPassword = encodeURIComponent(functions.config().gmail ? functions.config().gmail.password : '')
const mailTransport = nodemailer.createTransport(`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`)

exports = module.exports = functions.auth.user().onDelete((userMetadata, context) => {
  const uid = userMetadata.uid
  const email = userMetadata.email
  const displayName = userMetadata.displayName

  console.log(userMetadata.providerData)
  console.log(userMetadata)
  console.log(context)

  const provider = userMetadata.providerData.length ? userMetadata.providerData[0] : { providerId: email ? 'password' : 'phone' }
  const providerId = provider.providerId ? provider.providerId.replace('.com', '') : provider.providerId

  let promises = []

  const mailOptions = {
    from: `"Tarik Huber" <${gmailEmail}>`,
    to: email,
github m4r1vs / mnged / functions / index.js View on Github external
console.log('request done: ', response);
		if (!error && response.statusCode === 200) {
			const cover = JSON.parse(body).cover;
			console.log('Got cover: ', cover);
			if (!cover) return null;
			if (!cover.coverPhoto) return null;
			if (!cover.coverPhoto.url) return null;
			headerURL = cover.coverPhoto.url;
		}
		else console.error('Error fetching HeaderURL: ', error);
	});

	return headerURL;
};

exports.setUpNewUser = functions.auth.user().onCreate(event => {
	
	const user = event.data;

	const batch = firestore.batch();
	const userRef = firestore.collection('user-data').doc(user.uid);

	batch.set(userRef, {
		name: user.displayName || 'Mnger',
		email: user.email || null,
		photoURL: user.photoURL || 'https://mnged.me/assets/imgs/default_profile_picture.png',
		headerURL: getHeader(user) || 'https://mnged.me/assets/imgs/default_header.jpg'
	});

	const taskRef = userRef.collection('tasks').doc();
	batch.set(taskRef, {
		title: 'My first Task: Explore MNGED!',
github fossasia / badgeyay / cloud-functions / functions / index.js View on Github external
decipher.update(edata, "binary", "utf8") + decipher.final("utf8");
  }

  callback(plaintext);
};

String.prototype.format = function() {
  var formatted = this;
  for (var prop in arguments[0]) {
    var regexp = new RegExp("\\{" + prop + "\\}", "gi");
    formatted = formatted.replace(regexp, arguments[0][prop]);
  }
  return formatted;
};

exports.sendVerificationMail = functions.auth.user().onCreate(user => {
  const uid = user.uid;
  if (user.emailVerified) {
    console.log("User has email already verified: ", user.email);
    sendGreetingMail(user.email, user.displayName);
    return 0;
  } else {
    let userEmail = user.email;
    const mailOptions = {
      from: `${APP_NAME}`,
      to: userEmail
    };

    encrypt(userEmail, password, encoded => {
      var resp = {
        link: BASE_URL + "verify/email?id=" + encodeURIComponent(encoded)
      };
github goemen / react-material-ui-typescript / functions / index.js View on Github external
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.createProfile = functions.auth.user().onCreate(event => {
    const data = {
        displayName: event.displayName,
        email: event.email,
        photoUrl: event.photoURL,
        uid: event.uid
    };
    
    if (user.email === 'gnthomiwa@gmail.com') {
        return admin.auth().setCustomUserClaims(event.uid, {
            admin: true
        });
    } else {
        return;
    }
});
github stevekinney / think-piece / functions / index.js View on Github external
.document('users/{userId}')
  .onUpdate(async (change, context) => {
    const { displayName } = change.after.data();

    const posts = await admin
      .firestore()
      .collection('posts')
      .where('user.uid', '==', change.after.id)
      .get();

    return posts.forEach(doc => {
      doc.ref.update({ 'user.displayName': displayName });
    });
  });

exports.createUserDocument = functions.auth.user().onCreate(user => {
  const { uid, email, displayName, photoURL } = user;
  return firestore
    .collection('users')
    .doc(uid)
    .set({
      email,
      displayName,
      photoURL,
      createdByCloudFunction: true,
    });
});
github mcnamee / react-native-starter-kit / firebase / functions / index.js View on Github external
const fullName = `${original.firstName} ${original.lastName}`;
  return change.after.ref.child('fullName').set(fullName);
});

/**
  * Adds a 'user' role to all new users on create
  */
exports.addUserRole = functions.database.ref('/users/{userId}')
  .onCreate(snapshot => snapshot.ref.parent.child('role').set('user'));

/**
  * Listens for user deletion and
  * - deletes the user's reference in the database
  */
exports.deleteUserData = functions.auth.user()
  .onDelete(user => admin.database().ref(`/users/${user.uid}`).remove());
github bmcmahen / julienne / functions / index.js View on Github external
*/

exports.onRecipeDeleted = functions.firestore
  .document("recipes/{recipeId}")
  .onDelete(snap => {
    const index = client.initIndex(ALGOLIA_INDEX_NAME);
    return index.deleteObject(snap.id);
  });

exports.api = functions.https.onRequest(app);

/**
 * Save users to algolia for user searches
 */

exports.onUserCreated = functions.auth.user().onCreate(user => {
  const index = client.initIndex(ALGOLIA_USER_INDEX_NAME);
  const userToSave = Object.assign(
    {},
    {
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      uid: user.uid
    },
    {
      objectID: user.uid
    }
  );

  return Promise.all([
    index.saveObject(userToSave),