Skip to content

Instantly share code, notes, and snippets.

@katowulf
katowulf / print_ip_and_headers.js
Last active Aug 1, 2020
Print IP address and headers in Cloud Functions
View print_ip_and_headers.js
const functions = require('firebase-functions');
const util = require('util');
exports.helloWorld = functions.https.onRequest((req, res) => {
// For Firebase Hosting URIs, use req.headers['fastly-client-ip']
// For callable functions, use rawRequest
// Some users have better success with req.headers['x-appengine-user-ip']
const ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const headers = JSON.stringify(req.headers, null, 2);
const message = util.format("<pre>Hello world!\n\nYour IP address: %s\n\nRequest headers: %s</pre>", ipAddress, headers);
@katowulf
katowulf / app.component.ts
Last active Jul 8, 2020
Dynamically set page title based on active route in Angular 4
View app.component.ts
// This can probably be simplified somehow. Not sure why I need to add it in the component to init the service.
import { Component, OnInit } from '@angular/core';
import {TitleService} from "./@core/utils/title.service";
@Component({...})
export class AppComponent implements OnInit {
constructor(private titleService: TitleService) {...}
@katowulf
katowulf / enable_debug_logging.java
Last active Jun 22, 2020
Enable debug logging in Firestore
View enable_debug_logging.java
/******* Android **********/
// See https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/FirebaseFirestore.html#setLoggingEnabled(boolean)
FirebaseFirestore.setLoggingEnabled(true);
/******* Server-side Java **********/
/**
See https://medium.com/@hiranya911/logging-in-java-libraries-for-firebase-and-google-cloud-platform-f8742493b73f
1) Add the slf4j-simple binding to the application classpath
2) Set the -Dorg.slf4j.simpleLogger.defaultLogLevel=debug system property
**/
View functions-index.js
// Assumes that group members are stored in a subcollection under /groups/{groupId}/members/{userId}
const memberPath = '/familyMembers/{familyMemberId}/parents/{parentId}';
// Trigger updates to our generated maps if group membership changes
exports.memberAdded = functions.firestore.document(memberPath).onCreate(memberAdded);
exports.memberDeleted = functions.firestore.document(memberPath).onDelete(memberDeleted);
async function getAllowedDocuments(parentId) {
// what goes here?
return ['foo', 'bar'];
@katowulf
katowulf / simpleDocSharing_listMembers.js
Last active May 27, 2020
Psuedo rules examples for role based document sharing in Firestore.
View simpleDocSharing_listMembers.js
// docs/{docId}/users is an array of user ids allowed to access the doc
match /docs/{docId} {
allow read if request.auth.uid in getData('docs/$(docId)').users;
}
/**
* Shortcut to simplify pathing
*/
function getPath(childPath) {
@katowulf
katowulf / gist:4741111
Last active May 27, 2020
Firebase security rules for a simple chat room model
View gist:4741111
{
"chat": {
// the list of chats may not be listed (no .read permissions here)
// a chat conversation
"$key": {
// if the chat hasn't been created yet, we allow read so there is a way
// to check this and create it; if it already exists, then authenticated
// user (specified by auth.id) must be in $key/users
@katowulf
katowulf / 1_using_queries.js
Last active May 25, 2020
Methods to search for user accounts by email address in Firebase
View 1_using_queries.js
/***************************************************
* Simple and elegant, no code complexity
* Disadvantages: Requires warming all data into server memory (could take a long time for MBs of data or millions of records)
* (This disadvantage should go away as we add optimizations to the core product)
***************************************************/
var fb = firebase.database.ref();
/**
* @param {string} emailAddress
@katowulf
katowulf / 1_query_timestamp.js
Last active May 19, 2020
Get only new items from Firebase
View 1_query_timestamp.js
// assumes you add a timestamp field to each record (see Firebase.ServerValue.TIMESTAMP)
// pros: fast and done server-side (less bandwidth, faster response), simple
// cons: a few bytes on each record for the timestamp
var ref = new Firebase(...);
ref.orderByChild('timestamp').startAt(Date.now()).on('child_added', function(snapshot) {
console.log('new record', snap.key());
});
@katowulf
katowulf / example_validate_rules.js
Created May 18, 2020
Simple RTDB validation example
View example_validate_rules.js
{
"aListOfRecords": {
// when querying our list, must get less than 50 at a time and be authenticated
".read": "auth != null && (query.limitToFirst <= 50 || query.limitToLast <= 50)",
"$aRecordId": {
// When fetching a single record, I must be logged in
".read": "auth != null",
// When writing a record, I must be logged in
@katowulf
katowulf / rules.js
Created Mar 3, 2016
Search for users by email address in Firebase, without exposing everyone's email address to the world in a bulk-readable format.
View rules.js
{
"rules": {
"users": {
"$user_id": {
// email address is required
".validate": "newData.hasChildren(['email'])",
}
},
"emails_to_users": {
You can’t perform that action at this time.