Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FACTORY: get current user.id for Firebase Simple Login (Email / Password)

I am looking for a solid way to have the 'current user id' in all my controllers available. Using: Firebase Simple Login : Email / Password Authentication

My ida: I need a 'Factory' wich I can inject into my controllers, to have the 'current user id' always available.

I came up with this code:

    app.factory('User', ['angularFire',

    //Get Current UserID

    function(angularFire){

        console.log ('FACTORY: User');
            var currentUser = {};
            var ReturnStr = '';
        var ref = new Firebase("https://myFIREBASE.firebaseio.com/");
        var authClient = new FirebaseAuthClient(ref, function (err, user) {

            if (err) {
                    ReturnStr = 'FACTORY: User Error: ' + err; 
                console.log (ReturnStr);
                        //var User = ReturnStr;
            } else if (user) {
                console.log ('FACTORY: User: Login successfully:');
                console.log (user);
                currentUser = user;
            } else {
                //console.log ('-----------User: Logged Out ---------------');
                    ReturnStr = 'FACTORY: Logged out: Redirect to Login'; 
                console.log (ReturnStr);
                window.location.href = "/login.php";
            }
        });

    return currentUser;
        }
]);

My simplest Controller looks like:

function ToDoCtrl($scope, User) {
    $scope.MyUser = User;
    $scope.MyUser.test = 'Test';
}

In HTML (angular partials) i have:

<h2>{{MyUser.id}}</h2>
<h2>{{MyUser.email}}</h2>
<h2>{{MyUser.provider}}</h2>
<h2>{{MyUser.test}}</h2>

=> id, email, provider are 'undefined'. In console I see the 'FACTORY: User: Login successfully:' with correct user - Object.

=> Asynchronous loading of data problem?

I have also experimented (without luck):

        $timeout(function () {
        currentUser = user;
        }

Such a FACTORY would be very useful! Thanks for a pointing me in the right direction!

Edit 1.1: Now, with $rootscope hack

=> Same effect - mycontroller is too fast - factory to slow.

app.factory('User', ['$rootScope', '$timeout', 'angularFire',

    //Aktueller Benutzer auslesen

    function($rootScope, $timeout, angularFire){

        console.log ('FACTORY: User');
            var currentUser = {};
            var ReturnStr = '';
        var ref = new Firebase("https://openpsychotherapy.firebaseio.com/");
        var authClient = new FirebaseAuthClient(ref, function (err, user) {

            if (err) {
                    ReturnStr = 'FACTORY: User Error: ' + err; 
                console.log (ReturnStr);
                        //var User = ReturnStr;
            } else if (user) {
                console.log ('FACTORY: User: Login successfully:');
                        //currentUser = user;

            $timeout(function () {
                        ReturnStr = 'FACTORY: Inside timout'; 
                  console.log (ReturnStr);

                            currentUser = user;
                  console.log (currentUser);

                $rootScope.myUser = user;
                $rootScope.myUserID = user.id;
                $rootScope.loggedIn = true;
                            $rootScope.$apply();

                  return currentUser;
            });


            } else {
                //console.log ('-----------User: Logged Out ---------------');
                    ReturnStr = 'FACTORY: Logged out: Redirect to Login'; 
                console.log (ReturnStr);
                        //var User = ReturnStr;
                window.location.href = "/login.php";
            }
        });

    return currentUser;
        }
]);

TAHNKS for any helpful suggestions! Wonderin how others solve this!

like image 848
o_tiger Avatar asked Jun 23 '13 09:06

o_tiger


2 Answers

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'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.

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.

This is going to need to be adapted for your needs specifically if you choose to use this method, it's quite complex no matter what, but this is very solid for me and I'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'm just doing angularJS stuff mostly with directives. So here's my code.

NOTE: This will need modifying, and some things will be pseudo or open-ended for you to figure out for your needs.

AuthCtrl.js

'use strict';

angular.module('YOUR_APP', []).
controller('AuthCtrl', [
'$scope',
'$location',
'angularFire',
'fireFactory',

function AuthCtrl($scope, $location, angularFire, fireFactory) {
    // FirebaseAuth callback
    $scope.authCallback = function(error, user) {
        if (error) {
            console.log('error: ', error.code);
            /*if (error.code === 'EXPIRED_TOKEN') {
                $location.path('/');
            }*/
        } else if (user) {
            console.log('Logged In', $scope);
            // Store the auth token
            localStorage.setItem('token', user.firebaseAuthToken);
            $scope.isLoggedIn = true;

            $scope.userId = user.id;

            // Set the userRef and add user child refs once
            $scope.userRef = fireFactory.firebaseRef('users').child(user.id);
            $scope.userRef.once('value', function(data) {
                // Set the userRef children if this is first login
                var val = data.val();
                var info = {
                    userId: user.id,
                    name: user.name
                };
                // Use snapshot value if not first login
                if (val) {
                    info = val;
                }
                $scope.userRef.set(info); // set user child data once
            });

            $location.path('/user/' + $scope.userRef.name());
        } else {
            localStorage.clear();
            $scope.isLoggedIn = false;
            $location.path('/');
        }
    };

    var authClient = new FirebaseAuthClient(fireFactory.firebaseRef('users'), $scope.authCallback);

    $scope.login = function(provider) {
        $scope.token = localStorage.getItem('token');
        var options = {
            'rememberMe': true
        };
        provider = 'twitter';

        if ($scope.token) {
            console.log('login with token', $scope.token);
            fireFactory.firebaseRef('users').auth($scope.token, $scope.authCallback);
        } else {
            console.log('login with authClient');
            authClient.login(provider, options);
        }
    };

    $scope.logout = function() {
        localStorage.clear();
        authClient.logout();
        $location.path('/');
    };
}

]);

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.

fireFactory.js

'use strict';
angular.module('YOUR_APP').
factory('fireFactory', [
function fireFactory() {
    return {
        firebaseRef: function(path) {
            var baseUrl = 'https://YOUR_FIREBASE_PATH.firebaseio.com';
            path = (path !== '') ?  baseUrl + '/' + path : baseUrl;
            return new Firebase(path);
        }
    };
}

]);

Info

You give the factory just a piece of the path reference such as 'users' which will be used as part of the full path ref to where you want to store your user data.

fireFactory.firebaseRef('users')

Once you have a reference set for a user, they won't need to be set again it will just use the existing data and .auth() to it. Additionally if there's an existing 'token' in localStorage it will use that to auth() the user too.

Otherwise, it will login() the user and pop open the Oauth windows for them to do so using whatever option you provide them.

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's very annoying to make them play nicely with each other when using them with angularFire anyways. It's very frustrating but I've gotten past it finally.

If you want to check out the code for my app and see how I'm doing these things more completely, you can find it in this branch of my Webernote github repo.

Feel free to fork it, install and run it locally, or contribute to it even if you like. I could use some help myself :)

Hope this helps you!!

like image 126
jaredwilli Avatar answered Oct 06 '22 07:10

jaredwilli


Here's the way I do it.

First of all I have my firebase auth service (I'm not using Angularfire) that calls off to Singly to handle logins. When the user status changes it $broadcasts an event.

p4pApp.factory('firebaseAuth', function($rootScope, singlyAuth) {
var auth = {},
    FBref = new Firebase(p4pApp.FIREBASEPATH);

auth.login = function(service) {
    singlyAuth.login(service);
};

auth.logout = function() {
    FBref.unauth();
    auth.user = null;
    auth.broadcastAuthEvent();
};

auth.broadcastAuthEvent = function() {
    $rootScope.$broadcast('authEvent');
};

auth.authWithToken = function(token) {
    if (token !== undefined) {
        FBref.auth(token, function(error, authData) {
            if(!error) {
                auth.user = authData.auth.account;
                auth.broadcastAuthEvent();
            } else {
                auth.user = null;
                auth.broadcastAuthEvent();
            }
        }, function(error) {
            auth.user = null;
            auth.broadcastAuthEvent();
        });
    }
};

return auth;
});

Then I have a 'top level' controller that looks after authorisation state.

var AuthCtrl = function($scope, firebaseAuth, singlyAuth, firebase, user) {
$scope.user = null;

$scope.logout = function() {
    firebaseAuth.logout();
};

$scope.isLoggedIn = function() {
    return !!$scope.user;   
};

// src: Alex Vanston (https://coderwall.com/p/ngisma)
$scope.safeApply = function(fn) {
    var phase = this.$root.$$phase;
    if (phase == '$apply' || phase == '$digest') {
        if(fn && (typeof(fn) === 'function')) {
            fn();
        }
    } else {
        this.$apply(fn);
    }
};

$scope.$on('authEvent', function() {
    $scope.safeApply(function() {
        $scope.user = firebaseAuth.user;
    });

    user.setID(firebaseAuth.user);

    if (firebaseAuth.user) {
        firebase.fetch(['users', firebaseAuth.user], function(results) {
            if (results) {
                user.setData(results);
            } else {
                results = {};
                results.createdAt = DateTimeStamp();
            }

            results.lastLogin = DateTimeStamp();

            firebase.set('users', firebaseAuth.user, results);
        });     
    } else {
        user.clearData();
    }
});
};

Finally, I use a dedicated user service to maintain user state. (It's still in development)

p4pApp.factory('user', function() {
var userService = {}, user={};

user.data = {};

userService.setID = function(id) {
    user.id = id;
};

userService.getID = function() {
    return user.id;
};

userService.setData = function(data) {
    user.data = data || {};
};

userService.getData = function() {
    return user.data;
};

userService.clearData = function() {
    user.data = {};
};

userService.setDataField = function(field, data) {
    user.data[field] = data;
};

userService.clearDataField = function(field) {
    delete user.data[field];
};

userService.pushData = function(key, data) {
    if (typeof(key) === 'string') {
        user.data[key] = data;
    } else {
        _.reduce(key, function(obj, child, index, list) {
            obj[child] = obj[child] || {};

            if (index == list.length-1) {
                obj[child] = data;
            }

            return obj[child];
        }, user.data);          
    }
};

userService.deleteData = function(key) {
    if (typeof(key) === 'string') {
        delete user.data[key];
    } else {
        _.reduce(key, function(obj, child, index, list) {
            obj[child] = obj[child] || {};

            if (index == list.length-1) {
                delete obj[child];
                return;
            }

            return obj[child];
        }, user.data);          
    }
};

return userService;
});
like image 37
axzr Avatar answered Oct 06 '22 07:10

axzr