Skip to content

Instantly share code, notes, and snippets.

@acoyfellow
Forked from DennisAlund/createUserDoc.ts
Created June 3, 2018 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acoyfellow/23caa5d07d35e870caa3575c1d9c95fd to your computer and use it in GitHub Desktop.
Save acoyfellow/23caa5d07d35e870caa3575c1d9c95fd to your computer and use it in GitHub Desktop.
import * as functions from "firebase-functions";
import * as firebase from "firebase-admin";
import {MD5} from "crypto-js";
export const createUserDoc = functions.auth.user().onCreate(event => {
const firebaseUser = event.data;
// Use gravatar as default if photoUrl isn't specified in user data
const gravatarHash = MD5(firebaseUser.email).toString().toLowerCase();
let photoURL = `https://www.gravatar.com/avatar/${gravatarHash}.jpg?s=1024&d=robohash`;
let fileEnding = "jpg";
if (firebaseUser.photoURL) {
fileEnding = firebaseUser.photoURL.substr(firebaseUser.photoURL.lastIndexOf(".") + 1);
photoURL = firebaseUser.photoURL;
}
const fileName = `users/${firebaseUser.uid}/profile.${fileEnding}`;
const profilePhotoStorageOpts = {
destination: fileName,
metadata: {
contentType: `image/${fileEnding}`
}
};
const user = {
name: firebaseUser.displayName || "No Name",
email: firebaseUser.email,
photoUrl: `gs://${firebase.storage().bucket().name}/${fileName}`
};
return Promise.all([
firebase.storage().bucket().upload(photoURL, profilePhotoStorageOpts),
firebase.firestore().collection("users").doc(firebaseUser.uid).set(user)
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment