{"id":6375,"date":"2014-04-17T01:13:21","date_gmt":"2014-04-17T01:13:21","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/04\/17\/factory-get-current-user-id-for-firebase-simple-login-email-password-collection-of-common-programming-errors-2\/"},"modified":"2014-04-17T01:13:21","modified_gmt":"2014-04-17T01:13:21","slug":"factory-get-current-user-id-for-firebase-simple-login-email-password-collection-of-common-programming-errors-2","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/04\/17\/factory-get-current-user-id-for-firebase-simple-login-email-password-collection-of-common-programming-errors-2\/","title":{"rendered":"FACTORY: get current user.id for Firebase Simple Login (Email \/ Password)-Collection of common programming errors"},"content":{"rendered":"<p>So here is my solution to this exact problem. I am using Firebase, FirebaseAuthClient, and angularFire for my Angular app. I ran into the same situation for my login system where you cannot inject the $scope into the factory and therefore I came up with making a controller that used a factory for it&#8217;s methods to retrieve, add, update, and delete things. And in the controller, I have my firebaseAuth stuff going on, the setting of the User values, and references whick I assign to the scope of that. Once the user is logged in, they are redirected to another location, at which point the app.js file takes over with a child controller when at that address location.<\/p>\n<p>My login also uses localStorage, so logins will persist, you can refresh and not have to keep logging in, and you can change it to be cookies or sessionStorage easy enough.<\/p>\n<p>This is going to need to be adapted for your needs specifically if you choose to use this method, it&#8217;s quite complex no matter what, but this is very solid for me and I&#8217;m no longer needing to worry about firebaseAuth or angularFire stuff now that my factories are all setup for passing data back and forth. I&#8217;m just doing angularJS stuff mostly with directives. So here&#8217;s my code.<\/p>\n<p>NOTE: <em>This will need modifying, and some things will be pseudo or open-ended for you to figure out for your needs.<\/em><\/p>\n<p><strong>AuthCtrl.js<\/strong><\/p>\n<pre><code>'use strict';\n\nangular.module('YOUR_APP', []).\ncontroller('AuthCtrl', [\n'$scope',\n'$location',\n'angularFire',\n'fireFactory',\n\nfunction AuthCtrl($scope, $location, angularFire, fireFactory) {\n    \/\/ FirebaseAuth callback\n    $scope.authCallback = function(error, user) {\n        if (error) {\n            console.log('error: ', error.code);\n            \/*if (error.code === 'EXPIRED_TOKEN') {\n                $location.path('\/');\n            }*\/\n        } else if (user) {\n            console.log('Logged In', $scope);\n            \/\/ Store the auth token\n            localStorage.setItem('token', user.firebaseAuthToken);\n            $scope.isLoggedIn = true;\n\n            $scope.userId = user.id;\n\n            \/\/ Set the userRef and add user child refs once\n            $scope.userRef = fireFactory.firebaseRef('users').child(user.id);\n            $scope.userRef.once('value', function(data) {\n                \/\/ Set the userRef children if this is first login\n                var val = data.val();\n                var info = {\n                    userId: user.id,\n                    name: user.name\n                };\n                \/\/ Use snapshot value if not first login\n                if (val) {\n                    info = val;\n                }\n                $scope.userRef.set(info); \/\/ set user child data once\n            });\n\n            $location.path('\/user\/' + $scope.userRef.name());\n        } else {\n            localStorage.clear();\n            $scope.isLoggedIn = false;\n            $location.path('\/');\n        }\n    };\n\n    var authClient = new FirebaseAuthClient(fireFactory.firebaseRef('users'), $scope.authCallback);\n\n    $scope.login = function(provider) {\n        $scope.token = localStorage.getItem('token');\n        var options = {\n            'rememberMe': true\n        };\n        provider = 'twitter';\n\n        if ($scope.token) {\n            console.log('login with token', $scope.token);\n            fireFactory.firebaseRef('users').auth($scope.token, $scope.authCallback);\n        } else {\n            console.log('login with authClient');\n            authClient.login(provider, options);\n        }\n    };\n\n    $scope.logout = function() {\n        localStorage.clear();\n        authClient.logout();\n        $location.path('\/');\n    };\n}\n<\/code><\/pre>\n<p>]);<\/p>\n<p>And now for the nice and simple yet quite reusable factory. You will need to set your Firebase path for your app for the baseUrl variable for it to work.<\/p>\n<p><strong>fireFactory.js<\/strong><\/p>\n<pre><code>'use strict';\nangular.module('YOUR_APP').\nfactory('fireFactory', [\nfunction fireFactory() {\n    return {\n        firebaseRef: function(path) {\n            var baseUrl = 'https:\/\/YOUR_FIREBASE_PATH.firebaseio.com';\n            path = (path !== '') ?  baseUrl + '\/' + path : baseUrl;\n            return new Firebase(path);\n        }\n    };\n}\n<\/code><\/pre>\n<p>]);<\/p>\n<p><strong>Info<\/strong><\/p>\n<p>You give the factory just a piece of the path reference such as &#8216;users&#8217; which will be used as part of the full path ref to where you want to store your user data.<\/p>\n<pre><code>fireFactory.firebaseRef('users')\n<\/code><\/pre>\n<p>Once you have a reference set for a user, they won&#8217;t need to be set again it will just use the existing data and .auth() to it. Additionally if there&#8217;s an existing &#8216;token&#8217; in localStorage it will use that to auth() the user too.<\/p>\n<p>Otherwise, it will login() the user and pop open the Oauth windows for them to do so using whatever option you provide them.<\/p>\n<p>I have spent a lot of time, many many hours days and yes even months searching for something better than this when it comes to Firebase\/FirebaseAuthClient and angularFire. With the way the Firebase API and FireAuth API is, it&#8217;s very annoying to make them play nicely with each other when using them with angularFire anyways. It&#8217;s very frustrating but I&#8217;ve gotten past it finally.<\/p>\n<p>If you want to check out the code for my app and see how I&#8217;m doing these things more completely, you can find it in this branch of my Webernote github repo.<\/p>\n<p>Feel free to fork it, install and run it locally, or contribute to it even if you like. I could use some help myself \ud83d\ude42<\/p>\n<p>Hope this helps you!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>So here is my solution to this exact problem. I am using Firebase, FirebaseAuthClient, and angularFire for my Angular app. I ran into the same situation for my login system where you cannot inject the $scope into the factory and therefore I came up with making a controller that used a factory for it&#8217;s methods [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-6375","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6375","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=6375"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6375\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=6375"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=6375"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=6375"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}