Getting Websocket Failure when trying to anonymously authenticate user using AngularFire - angularjs

I am trying to anonymously authenticate users using AngularFire. I want to authenticate a user only once (so, if the user has already been authenticated, a new uid won't be generated). When I use the code below, I get a previous_websocket_failure notification. I also get an error in the console that says TypeError: Cannot read property 'uid' of null. When the page is refreshed, everything works fine.
Any thoughts on what I'm doing wrong here?
app.factory('Ref', ['$window', 'fbURL', function($window, fbURL) {
'use strict';
return new Firebase(fbURL);
}]);
app.service('Auth', ['$q', '$firebaseAuth', 'Ref', function ($q, $firebaseAuth, Ref) {
var auth = $firebaseAuth(Ref);
var authData = Ref.getAuth();
console.log(authData);
if (authData) {
console.log('already logged in with ' + authData.uid);
} else {
auth.$authAnonymously({rememberMe: true}).then(function() {
console.log('authenticated');
}).catch(function(error) {
console.log('error');
});
}
}]);
app.factory('Projects', ['$firebaseArray', '$q', 'fbURL', 'Auth', 'Ref', function($firebaseArray, $q, fbURL, Auth, Ref) {
var authData = Ref.getAuth();
var ref = new Firebase(fbURL + '/projects/' + authData.uid);
console.log('authData.uid: ' + authData.uid);
return $firebaseArray(ref);
}]);

In your Projects factory, you have assumed authData will not be null. There are no guarantees here, since your Projects factory is initialized as soon as you inject it into another provider. I also noticed that your Auth service doesn't actually return anything. This probably means that the caller has to know the internal workings and leads to quite a bit of coupling. A more SOLID structure would probably be as follows:
app.factory('Projects', function(Ref, $firebaseArray) {
// return a function which can be invoked once
// auth is resolved
return function(uid) {
return $firebaseArray(Ref.child('projects').child(uid));
}
});
app.factory('Auth', function(Ref, $firebaseAuth) {
return $firebaseAuth(Ref);
});
app.controller('Example', function($scope, Auth, Projects) {
if( Auth.$getAuth() === null ) {
auth.$authAnonymously({rememberMe: true}).then(init)
.catch(function(error) {
console.log('error');
});
}
else {
init(Auth.$getAuth());
}
function init(authData) {
// when auth resolves, add projects to the scope
$scope.projects = Projects(authData.uid);
}
});
Note that dealing with auth in your controllers and services should generally be discouraged and dealing with this at the router level is a more elegant solution. I'd highly recommend investing in this approach. Check out angularFire-seed for some example code.

Related

How to handle $rootscope and take user id of logged in user in AngularJS?

I want to find the ID of the logged in user and display it in a page. I am new to angular and I don't have much clue on how to handle a session..
I have an angular app which is connected to backend API (.net core).
I will show the instances where $rootScope is used in the website (login and authorization is already enabled). I need to get an understanding of this to learn the app.
In App.js :
//Run phase
myApp.run(function($rootScope, $state) {
$rootScope.$state = $state; //Get state info in view
//Should below code be using rootScope or localStorage.. Check which one is better and why.
if (window.sessionStorage["userInfo"]) {
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
}
//Check session and redirect to specific page
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
if(toState && toState.data && toState.data.auth && !window.sessionStorage["userInfo"]){
event.preventDefault();
window.location.href = "#login";
}
if(!toState && !toState.data && !toState.data.auth && window.sessionStorage["userInfo"]){
event.preventDefault();
window.location.href = "#dashboard";
}
});
});
Users.js :
'use strict';
angular.module('users', []);
//Routers
myApp.config(function($stateProvider) {
//Login
$stateProvider.state('login', {
url: "/login",
templateUrl: 'partials/users/login.html',
controller: 'loginController'
});
//Factories
myApp.factory('userServices', ['$http', function($http) {
var factoryDefinitions = {
login: function (loginReq) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
return $http.post('http://localhost:1783/api/token?UserName='+loginReq.username+'&password='+loginReq.password).success(function (data) { return data; });
}
}
return factoryDefinitions;
}
]);
//Controllers
myApp.controller('loginController', ['$scope', 'userServices', '$location', '$rootScope', function($scope, userServices, $location, $rootScope) {
$scope.doLogin = function() {
if ($scope.loginForm.$valid) {
userServices.login($scope.login).then(function(result){
$scope.data = result;
if (!result.error) {
window.sessionStorage["userInfo"] = JSON.stringify(result.data);
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
//$localStorage.currentUser = { username: login.username, token: result.data };
//$http.defaults.headers.common.Authorization = 'Token ' + response.token;
$location.path("/dashboard");
}
});
}
};
}]);
I came to know that the information about the user will be available in $rootScope.userInfo. If so, how can I take a value inside it?
Please explain with an example if possible. Thanks in advance.
One:
myApp.controller('loginController', [
'$scope', 'userServices', '$location',
'$rootScope',
function($scope, userServices, $location, $rootScope) {
Inside the controller, $rootScope was injected which makes you have access to the userInfo in that controller.
so if you inject $rootScope into another controller and console.log($rootScope.userInfo) you would see the users data.
myApp.controller('anotherController', ['$scope', '$rootScope', function
($scope, $rootScope){
console.log($rootScope.userInfo) //you'd see the users data from sessionStorage
});
According to this post on quora
$scope is an object that is accessible from current component
e.g Controller, Service only. $rootScope refers to an object
which is accessible from everywhere of the application.
You can think $rootScope as global variable and $scope as local variables.
$rootScope Defn.
In your case, once the user is logged in a key "userInfo" in sessionStorage is created and the same data is copied to $rootScope.userInfo. To check the fields in the userInfo after login try
console.log($rootScope.userInfo);
and print it in the console or open your session storage in your browser debugger tools [for chrome open developer tools>applications>sessionstorage>domainname] to view the values in the "userInfo" key.
Suppose you have
{
uid: "10",
fullname: "John Doe"
}
you can access uid in the script using $rootScope.userInfo.uid or $rootScope.userInfo['uid'].
Just in case you are unable to read the code, here is an explanation
if (window.sessionStorage["userInfo"]) {
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
}
is checking the user is logged in or not.
the factory
myApp.factory('userServices', ['$http', function($http) {
var factoryDefinitions = {
login: function (loginReq) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
return $http.post('http://localhost:1783/api/token?UserName='+loginReq.username+'&password='+loginReq.password).success(function (data) { return data; });
}
}
is calling the server to get the userInfo object.
$scope.doLogin = function() {
if ($scope.loginForm.$valid) {
userServices.login($scope.login).then(function(result){
$scope.data = result;
if (!result.error) {
window.sessionStorage["userInfo"] = JSON.stringify(result.data);
$rootScope.userInfo = JSON.parse(window.sessionStorage["userInfo"]);
//$localStorage.currentUser = { username: login.username, token: result.data };
//$http.defaults.headers.common.Authorization = 'Token ' + response.token;
$location.path("/dashboard");
}
});
}
};
$scope.doLogin is calling the above factory and storing the userInfo object.

Trouble with AngularFire (Firebase) and Authenticating with Routers

I'm working on an Angular web app that is using Firebase to authenticate the user when they login or register. I want to restrict going to the /dashboard url unless they're logged in. I tried following Firebase's docs, but I'm coming up with errors.
I think where I'm having problems was making my controller code work with the one provided. I kept getting the error "Unknown provider: AuthProvider <- Auth <- currentAuth", so I just took out their controller code for now.
Any help would be great!
Here's the doc link: https://www.firebase.com/docs/web/libraries/angular/guide/user-auth.html#section-routers
And my code:
ROUTER CONFIG
var app = angular.module('maggsLashes', ['ngRoute', 'ui.calendar', 'firebase']);
app.config(function($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'app/templates/dashboardTmpl.html',
controller: 'dashboardCtrl',
resolve: {
// controller will not be loaded until $requireAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["Auth", function(Auth) {
// $requireAuth returns a promise so the resolve waits for it to complete
// If the promise is rejected, it will throw a $stateChangeError (see above)
return Auth.$requireAuth();
}]
}
})
DASHBOARD CONTROLLER
app.controller('dashboardCtrl', function($scope, $firebaseAuth, $location) {
var ref = new Firebase("https://maggslashes.firebaseio.com/");
var auth = $firebaseAuth(ref);
// app.controller("AccountCtrl", ["currentAuth", function(currentAuth) {
// // currentAuth (provided by resolve) will contain the
// // authenticated user or null if not logged in
// }]);
// console.log(auth);
console.log("Matt is pretty much awesome");
ref.onAuth(function(authData) {
if (authData) {
console.log("User is authenticated w uid:", authData);
}
else {
console.log("client sucks");
}
});
$scope.logOut = function() {
$location.path('/');
$scope.apply();
ref.unauth();
console.log(authData.uid);
};
});
I can see what may be at least on issue. In your router, you refer to "Auth" but do not see your code for that service/factory, so it's possible you don't have that set up. Note that "Auth" is a custom factory.
not you need this somewhere in your code:
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://docs-sandbox.firebaseio.com", "example3");
return $firebaseAuth(ref);
}
])
Also, can you provide the errors you're receiving?
Wayne

Angular passing data from factory to controller

I'm trying to store an authorized user id variable, which I can pass to controllers. I know there's an issue with how I'm trying to pass the data from inside the closure of my factory object, but I'm stuck on how to fix it.
Here is my factory:
myApp.factory('Authentication', function($firebase,
$firebaseAuth, FIREBASE_URL, $location) {
var ref = new Firebase(FIREBASE_URL);
var simpleLogin = $firebaseAuth(ref);
var authorized;
var myObject = {
login : function() {
return simpleLogin.$authAnonymously().then(function(authData) {
authorized = authData.uid;
console.log("Logged in as:", authData.uid);
}).catch(function(error) {
console.error("Authentication failed:", error);
});
},
auth : authorized
} //myObject
return myObject;
});
Here is my controller:
myApp.controller('MeetingsController',
function($scope, $firebase, Authentication) {
var ref = new Firebase('http://i2b2icons.firebaseio.com/');
var meetings = $firebase(ref);
$scope.authid = Authentication.auth;
$scope.meetings = meetings.$asObject();
// $scope.id = = Authentication.login.id;
$scope.addMeeting=function() {
meetings.$push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
}).then(function() {
$scope.meetingname = '';
});
} //addmeeting
$scope.deleteMeeting=function(key) {
meetings.$remove(key);
} //deletemeeting
}); //MeetingsController
I'm really just trying to get the $scope.authid variable to pick up the value of auuthorized from the the login function of myObject.
The login method should have been called already by logging in via this controller:
myApp.controller('RegistrationController',
function($scope, $firebaseAuth, $location, Authentication) {
$scope.login = function() {
Authentication.login();
} //login
}); //RegistrationController
You are just setting the local variable authorized in your factory, it has no relation to the Authentication.auth that you are trying to access in your controller (unless ofcourse you set the value to it while creating the factor and which is not the intention anyway). Instead return a predefined object in your factory and return that object from it. Set the property on the object reference.
myApp.factory('Authentication', function($firebase,
$firebaseAuth, FIREBASE_URL, $location) {
var ref = new Firebase(FIREBASE_URL);
var simpleLogin = $firebaseAuth(ref);
//Predefine the factory
var factory = {
login: login,
authorized: null
};
function login() {
return simpleLogin.$authAnonymously().then(function(authData) {
factory.authorized = authData.uid; //Set the property here
}).catch(function(error) {});
}
//return it
return factory;
});
With this provided you have the reference of the factory and updates to its property will reflect (provided you invoke the method that populates the data) in your controller. Another way would be to use a getter function in your factory to return the auth object, or you can as well cache the promise returned by login function and return it and invalidate it when an event occurs that log the user out.
As others have already pointed out you only update the variable authorized, not the property auth. One rather simple solution is to change authto a getter, that always returns the current value:
var myObject = {
login : function() {
...
},
get auth() {
return authorized;
}
You don't have to change any other code.

Can't get new password authentication methods to work in AngularFire 0.9.0?

I'm trying to use the new authentication methods in Angular Fire 0.9.0 but I must be doing something wrong.
I'm running 1.3.2 of Angular, 2.0.4 of Firebase and 0.9.0 of Angular Fire.
I call the login function from an ng-click in my html.
Here is my js :
var app = angular.module("sampleApp", ["firebase"]);
app.controller('mainCtrl', function ($scope, $firebaseAuth) {
var ref = new Firebase('https://XXXX.xxx');
$scope.auth = $firebaseAuth(ref);
$scope.login = function() {
$scope.num = 'loggin in';
$scope.auth.$authWithPassword({
email: 'xxx#xxx.xxx',
password: 'yyyyy'
}, function(err, authData) {
if (err) {
console.log(err);
$scope.num = err;
} else {
console.log(authData);
}
});
};
I don't see anything in the console and I don't get any errors. So I can't figure out how to debug what I am doing wrong.
When I log $scope.auth to the console, it shows the $authWithPassword method. I just can't get it to work.
Any help would be appreciated.
The problem you are running into is that the AngularFire API is slightly different than the regular Firebase API for the authentication methods. While the Firebase SDK takes a callback as the second argument for authWithPassword(), the AngularFire API returns a promise for $authWithPassword(). The reason for the difference is that promises are a very common idiom in Angular and we wanted to provide an API that people are already familiar with. So, your code should look like this:
var app = angular.module("sampleApp", ["firebase"]);
app.controller('mainCtrl', function ($scope, $firebaseAuth) {
var ref = new Firebase('https://XXXX.xxx');
$scope.auth = $firebaseAuth(ref);
$scope.login = function() {
$scope.num = 'logging in';
$scope.auth.$authWithPassword({
email: 'xxx#xxx.xxx',
password: 'yyyyy'
}).then(function(authData) {
console.log(authData);
}).catch(function(error) {
console.log(err);
$scope.num = err;
});
};
});

Initiate a service and inject it to all controllers

I'm using Facebook connect to login my clients.
I want to know if the user is logged in or not.
For that i use a service that checks the user's status.
My Service:
angular.module('angularFacebbokApp')
.service('myService', function myService($q, Facebook) {
return {
getFacebookStatus: function() {
var deferral = $q.defer();
deferral.resolve(Facebook.getLoginStatus(function(response) {
console.log(response);
status: response.status;
}));
return deferral.promise;
}
}
});
I use a promise to get the results and then i use the $q.when() to do additional stuff.
angular.module('angularFacebbokApp')
.controller('MainCtrl', function ($scope, $q, myService) {
console.log(myService);
$q.when(myService.getFacebookStatus())
.then(function(results) {
$scope.test = results.status;
});
});
My problem is that i need to use the $q.when in every controller.
Is there a way to get around it? So i can just inject the status to the controller?
I understand i can use the resolve if i use routes, but i don't find it the best solution.
There is no need to use $q.defer() and $q.when() at all, since the Facebook.getLoginStatus() already return a promise.
Your service could be simpified like this:
.service('myService', function myService(Facebook) {
return {
getFacebookStatus: function() {
return Facebook.getLoginStatus();
}
}
});
And in your controller:
.controller('MainCtrl', function ($scope, myService) {
myService.getFacebookStatus().then(function(results) {
$scope.test = results.status;
});
});
Hope this helps.
As services in angularjs are singleton you can create new var status to cache facebook response. After that before you make new call to Facebook from your controller you can check if user is logged in or not checking myService.status
SERVICE
angular.module('angularFacebbokApp')
.service('myService', function myService($q, Facebook) {
var _status = {};
function _getFacebookStatus() {
var deferral = $q.defer();
deferral.resolve(Facebook.getLoginStatus(function(response) {
console.log(response);
_status = response.status;
}));
return deferral.promise;
}
return {
status: _status,
getFacebookStatus: _getFacebookStatus
}
});
CONTROLLER
angular.module('angularFacebbokApp')
.controller('MainCtrl', function ($scope, $q, myService) {
console.log(myService);
//not sure how do exactly check if user is logged
if (!myService.status.islogged )
{
$q.when(myService.getFacebookStatus())
.then(function(results) {
$scope.test = results.status;
});
}
//user is logged in
else
{
$scope.test = myService.status;
}
});

Resources