FACTORY:获得火力地堡简单登录当前user.id(电子邮件/密码) [英] FACTORY: get current user.id for Firebase Simple Login (Email / Password)

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

问题描述

我要寻找到在我的所有可用控制器当前用户ID'了坚实的道路。
使用:火力地堡简单登录:电子邮件/密码认证

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.

我想出了这个code:

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

在HTML(角谐音)我有:

In HTML (angular partials) i have:

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

=> ID,电子邮件提供商都未定义。在控制台我看到了'厂:用户:登录成功:用正确的用户 - 对象

=> 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!

修改1.1:现在,$ rootscope破解

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

TAHNKS任何有益的建议!迷惘别人是怎么解决这个问题!

推荐答案

因此​​,这里是我的解决这个确切的问题。我使用的火力地堡,FirebaseAuthClient和angularFire我的角度应用程序。我遇到了同样的情况对我的登录系统,你不能注入$范围进厂,因此,我想出了制作所用工厂为它的方法来检索,添加,更新和删除的东西控制器。而在控制,我有我的东西firebaseAuth回事,用户价值和参考whick我分配到的那个范围的设置。一旦用户登录,他们将被重定向到另一个位置,此时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.

我的登录也使用本地存储,所以登录将持续下去,您可以刷新,而不必继续登录,您可以更改它是饼干或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东西大多用指令。因此,这里是我的code。

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

]);

和现在的美好和简单但很可重复使用的工厂。您将需要设置你的火力地堡路径您的应用程序的变量的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的现有'令牌',它会用它来权威性()用户了。

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.

,否则会登录()用户和流行开的Oauth窗户他们这样做使用任何选项,则提供给他们。

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

我花了很多时间,很多很多时间几天甚至是几个月寻找比这更好的东西,当涉及到火力地堡/ FirebaseAuthClient和angularFire。随着火力地堡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.

如果您要检查出code为我的应用程序,看看我是如何更全面地做这些事情,你可以的这个分支我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 :)

希望这有助于你!

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

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