Skip to content

Instantly share code, notes, and snippets.

@tarex
Forked from sararob/data-structure.js
Created June 29, 2017 18:24
Show Gist options
  • Select an option

  • Save tarex/415ce96982779cc5e2d1750fab6aa6d5 to your computer and use it in GitHub Desktop.

Select an option

Save tarex/415ce96982779cc5e2d1750fab6aa6d5 to your computer and use it in GitHub Desktop.
Role-based security in Firebase
/* This shows how you can authenticate users and store user data in Firebase
using Firebase Simple Login with Twitter. The corresponding security rules for
this app are available in this gist: https://gist.github.com/sararob/8694d5b4111e4ed31cec */
// Define Firebase references
var ref = new Firebase("<your-firebase>.firebaseio.com/");
var usersRef = ref.child("users");
var currentUser = null; //we'll use this to see if a user is currently logged in
// Call an 'auth' function when a user clicks a login button (this example uses twitter)
$('#login').on("click", function () {
auth.login('twitter');
});
// Authenticate users and store each user in Firebase by their Twitter UID
var auth = new FirebaseSimpleLogin(ref, function (error, user) {
if (error) {
console.log(error);
} else if (user) {
usersRef.child(user.uid).set({pic: user.thirdPartyUserData.profile_image_url, username: user.username});
currentUser = user;
} else {
//user is logged out
}
});
// When a user adds a message, add the message data to Firebase
$('#message-submit').on('click', function () {
if (currentUser != null) {
var message = $('#msgInput').val();
//Send the message to Firebase
messagesRef.push({user: currentUser.uid, username: currentUser.username, message: message});
} else {
alert('You must login with Twitter to post!');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment