Skip to content

Instantly share code, notes, and snippets.

@rewonc
Last active January 23, 2017 19:59
Show Gist options
  • Save rewonc/388451443a51175a927d to your computer and use it in GitHub Desktop.
Save rewonc/388451443a51175a927d to your computer and use it in GitHub Desktop.
Authenticate a user with angularfire, save to firebase, and make available to controllers with promise
/*
This file is a brief example of how to use angularfire to authenticate a user, save that user's public profile to firebase, then
ensure that both the authenticated and public user are available in your controllers.
The route configuration uses angular-ui-router: https://github.com/angular-ui/ui-router
*/
//***********in services.js ****************
angular.module('myapp.services', [])
//simpleLogin service for angularfire, as described in angularfire docs
//https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasesimplelogin
.factory("simpleLogin", ["$firebaseSimpleLogin", "$firebase", function($firebaseSimpleLogin, $firebase){
var ref = new Firebase("your_url_here");
var authProvider = $firebaseSimpleLogin(ref);
return authProvider;
}])
.factory("userPromise", ["simpleLogin", "$firebase", "$q", function(simpleLogin, $firebase, $q) {
//function returnPromise will generate a promise that will get the authenticated user, make a profile if it doesn't exist,
//and then return both objects on resolution.
var returnPromise = function(){
var user, publicUser;
var deferred = $q.defer();
//this function will take a user object and check for existing profile "publicUser" and create it if not
var getPublicUser = function(auth_user){
var ref = new Firebase("your_firebase_url");
var remoteUser = $firebase(ref.child('users').child(auth_user.uid)).$asObject();
remoteUser.$loaded().then(function(){
if (remoteUser.profile){
deferred.notify('Existing public profile');
publicUser = remoteUser;
deferred.resolve({user: user, publicUser: publicUser});
} else {
deferred.notify('New user - initializing profile');
remoteUser.displayName = auth_user.displayName;
remoteUser.provider = auth_user.provider;
remoteUser.provider_id = auth_user.id;
remoteUser.provider_username = auth_user.username;
remoteUser.profile_img_url = auth_user.thirdPartyUserData.profile_image_url;
remoteUser.profile = {};
remoteUser.$save(function(){console.log('successfully saved')}); //save to firebase
publicUser = remoteUser;
deferred.resolve({user: user, publicUser: publicUser});
}
});
}
//get the authenticated user
simpleLogin.$getCurrentUser().then(function(userData){
if(userData){
deferred.notify('User ' + userData.id + " successfully logged in through simpleLogin");
user = userData;
//if authenticated, get the public object
getPublicUser(userData);
} else {
deferred.reject('Not authenticated')
}
});
//return promise
return deferred.promise;
}
//return function to generate the promise. We return a function instead of
//the promise directly so they can regenerate the promise if they fail authentication.
return {getPromise: returnPromise};
}]);
//************************* in app.js ***************************
//Example of how to use angular-ui-routes to ensure user is logged in
// & that the promise is resolved before your controllers are initialized
angular.module('myapp', ['myapp.services', 'myapp.controllers', 'firebase'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('example', {
url: "/example",
templateUrl: "templates/example.html",
resolve: {
"currentUser":
["userPromise", "$state", function(userPromise, $state) {
return userPromise.getPromise().then(function(success){
return success;
}, function(reason){
console.log("userPromise Failed: " + reason);
$state.transitionTo('login');
}, function(notification){
console.log("notification: " + notification);
});
}]
}
});
}
//************************* in controllers.js ***************************
//you can inject currentUser and immediately retrieve the objects
//as the promise will be resolved before ExampleCtrl is initialized
angular.module('myapp.controllers', [])
.controller('ExampleCtrl', ["$scope", "currentUser", function($scope, currentUser) {
$scope.user = currentUser.user //returns the authenticated user object
$scope.profile = currentUser.publicUser; //returns the public user object we created earlier
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment