工厂:获取 Firebase 简单登录的当前 user.id(电子邮件/密码) [英] FACTORY: get current user.id for Firebase Simple Login (Email / Password)

查看:23
本文介绍了工厂:获取 Firebase 简单登录的当前 user.id(电子邮件/密码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种可靠的方法来在我所有可用的控制器中使用当前用户 ID".使用:Firebase 简单登录:电子邮件/密码身份验证

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

我的 ida:我需要一个可以注入控制器的工厂",让当前用户 ID"始终可用.

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

我想出了这个代码:

    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';
}

在 HTML(角度部分)中,我有:

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 是未定义".在控制台中,我看到工厂:用户:登录成功:"与正确的用户 - 对象.

=> 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:现在,使用 $rootscope hack

Edit 1.1: Now, with $rootscope hack

=> 相同的效果 - mycontroller 太快 - 工厂慢.

=> 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;
        }
]);

TANHKS 提供任何有用的建议!想知道其他人是如何解决这个问题的!

推荐答案

这里是我对这个确切问题的解决方案.我正在为我的 Angular 应用程序使用 Firebase、FirebaseAuthClient 和 angularFire.我的登录系统遇到了同样的情况,您无法将 $scope 注入工厂,因此我想出了一个控制器,该控制器使用工厂的方法来检索、添加、更新和删除内容.在控制器中,我有我的 firebaseAuth 东西,用户值的设置,以及我分配给它的范围的引用.用户登录后,他们将被重定向到另一个位置,此时 app.js 文件会在该地址位置接管一个子控制器.

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.

我的登录也使用 localStorage,因此登录将持续存在,您可以刷新而不必继续登录,并且您可以轻松地将其更改为 cookie 或 sessionStorage.

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.

如果您选择使用这种方法,这将需要专门针对您的需求进行调整,无论如何它都非常复杂,但这对我来说非常可靠,我不再需要担心 firebaseAuth 或 angularFire现在我的工厂都设置为来回传递数据.我只是在做 angularJS 的东西,主要是用指令.所以这是我的代码.

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.

注意:这需要修改,有些东西会是伪的或开放式的,你可以根据自己的需要找出来.

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('/');
    };
}

]);

现在是漂亮、简单但可重复使用的工厂.您需要为您的应用设置 Firebase 路径,以便 baseUrl 变量使其工作.

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);
        }
    };
}

]);

信息

您只为工厂提供了一段路径引用,例如用户",它将用作您要存储用户数据的完整路径引用的一部分.

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

一旦您为用户设置了参考,他们就不需要再次设置,它只会使用现有数据和 .auth() .此外,如果 localStorage 中有一个现有的令牌",它也会使用它来 auth() 用户.

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.

否则,它将 login() 用户并弹出 Oauth 窗口,让他们使用您提供的任何选项来执行此操作.

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

当涉及到 Firebase/FirebaseAuthClient 和 angularFire 时,我花了很多时间、很多天甚至几个月的时间来寻找比这更好的东西.根据 Firebase API 和 FireAuth API 的方式,无论如何在将它们与 angularFire 一起使用时让它们相互配合是非常烦人的.这非常令人沮丧,但我终于克服了它.

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.

如果您想查看我的应用程序的代码并更完整地了解我是如何做这些事情的,您可以在 我的 Webernote github 存储库的这个分支.

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 :)

希望对你有帮助!!

这篇关于工厂:获取 Firebase 简单登录的当前 user.id(电子邮件/密码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆