AngularJS Firebase logout user not working - javascript

My logout function, linked to a logout button is:
$scope.logoutUser = function() {
var ref = new Firebase("https://buzzmovieionic.firebaseio.com");
ref.unauth();
console.log(ref.getAuth);
$state.transitionTo('login');
}
When I click logout, it prints this to the console:
function (){x("Firebase.getAuth",0,0,arguments.length);return this.k.P.we()}
I am checking for authData in my other controller with:
CONTROLLER:
.controller('SearchCtrl',
function ($scope, $http, Movie, $state, UsersRef, AuthData, $timeout) {
$scope.$on('$ionicView.enter', function () {
if (!AuthData) {
console.log("Auth data null!");
swal("Unauthorized", "You are not logged in", "error");
$state.transitionTo('login');
} else {
console.log("Auth data found: " + AuthData);
//do stuff
}
});
})
FACTORY:
.factory("AuthData", [
function () {
var ref = new Firebase("https://buzzmovieionic.firebaseio.com");
var data = null;
ref.onAuth(function (authData) {
if (authData) {
data = authData;
}
});
return data;
}
])
If I logout, then go back to the page linked to SearchCtrl by changing the URL, it still says it found the authData.
However, if I try and go to the search page the FIRST time I open the app, before anybody has logged in, it gives me the right error message and exits out to the login page.
How can I ensure the user can't go back into the app after logging out?

Welcome to async programming 101.
Firebase's onAuth methods listens for changes on auth state. When the auth state changes, the callback method you provide is invoked. But while it's waiting for auth state changes, your other code continues to run.
It most easy to see this if you add some log statements to your code:
.factory("AuthData", [
function () {
var ref = new Firebase("https://buzzmovieionic.firebaseio.com");
var data = null;
console.log('before onAuth');
ref.onAuth(function (authData) {
console.log('in callback');
if (authData) {
data = authData;
}
});
console.log('after onAuth');
return data;
}
])
The output is going to be:
before onAuth
after onAuth
in callback
Which is likely not what you expected when you wrote this code.
The simplest way to fix this in your code is to use the synchronous ref.getAuth() method:
.factory("AuthData", [
function () {
var ref = new Firebase("https://buzzmovieionic.firebaseio.com");
return ref.getAuth();
}
])
But you're going to run into this asynchronicity problem quite often. I highly recommend using and studying AngularFire instead of reinventing the wheel.

You are never cleaning data inside AuthData so it will always have data after the first guy logs in. I'm not familiar with Firebase but you need something like this in your AuthData factory:
.factory("AuthData", [
function () {
var ref = new Firebase("https://buzzmovieionic.firebaseio.com");
var data = null;
ref.onAuth(function (authData) {
if (authData) {
data = authData;
}
else
data = null;
});
return data;
}
])

Related

Intern Async call in before()

I need to request some json files that contain data I use for testing. I would like to make the request in the setup method, but there is no async method attached to it. When I run the code below, the log inside the test login function gets sent to the console before my logs from the setup method get sent. Is there a way I can tell setup to wait till my calls get completed before running the tests?
define([
'intern!object',
'pages/LoginPage',
'data-objects/DataFetcher'
], function(registerSuite, LoginPage, DataFetcher) {
registerSuite(function() {
var loginId = admin;
var password = test;
var regionData = US;
var loginPage = null;
return {
name: 'Login test',
setup: function() {
// Initialize page objects
loginPage = new LoginPage(this.remote, this.timeout);
// get test data
DataFetcher.getData(Pages.LoginPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.TablePage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.PersonPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.BasicInfoPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
DataFetcher.getData(Pages.CompanyInfoPage).then(function(response) {
logger.info(DataFetcher.generateData(response));
});
},
login: function() {
logger.log('info', 'Login is ' + loginId + ' Password ' +
password);
return loginPage.load(regionData.BASE_URL)
.login(loginId, password)
.getAccumulatedState();
}
};
});
});
If you return a Promise from the setup function, Intern will wait for it to resolve before starting tests. You can return a Promise.all(...) of all your requests.

Angular unknower provider error in custom service

This is my code for initializing the app and creating a controller.
var app = angular.module('newstalk',[]);
app.controller("articleCtrl",['$scope','$http','dataService',function($scope,$http,dataService){
$scope.articles = dataService.getArticles();
$scope.commentForm = function(id,userid){
console.log(userid);
var uid = userid;
var c = this.contents;
var data = {
content: c,
user: uid
};
console.log(data);
$http.post('/api/article/'+id,data);
};
}]);
Now, I have also created a service to fetch the data from the server. Here is the code for that:
(function(){
angular.module('newstalk')
.factory('dataService',dataService);
function dataService(){
return {
getArticles : getArticles
};
function getAricles(){
console.log("yolo");
return $http({
method:get,
url:'/api/articles/0'
})
.then(sendResponse);
}
function sendResponse(response){
console.log(data);
return response.data;
}
}
})
This is in a seperate file. Now when I run this I get a Error: $injector:unpr Unknown Provider error.
I've read multiple other such questions, none of which came to help. Any ideas?
I think you have not used IIFE correctly.
you should put () at the end of file.
(function(){
angular.module('newstalk')
.factory('dataService',dataService);
function dataService(){
return {
getArticles : getArticles
};
function getAricles(){
console.log("yolo");
return $http({
method:get,
url:'/api/articles/0'
})
.then(sendResponse);
}
function sendResponse(response){
console.log(data);
return response.data;
}
}
})()
putting () execute/run the function. rightnow you are not executing IIFE.

tell protractor to block on asynchronous call

I'm adding a fresh, angular client-tier to a legacy app. Upon login the legacy up redirects to a 'home' url. The url contains a session id which I need to grab and use (in the url) for any subsequent gets/posts. After login I call:
browser.getCurrentUrl()
and then use a regex to extract the session id. I store the session id away and use it for later gets/posts.
The problem is though that browser.getCurrentUrl() returns a promise and all my tests run before I can get the session id back. How can I make protractor wait for the browser.getCurrentUrl() to resolve.
Specifically below where I have the code:
var sessionId = loginPage.login('testuser#example.com', 'testuser');
homePage = new HomePage(sessionId);
I really need all code to block on loginPage.login() so I'll have a defined session id. My home page tests and any other page tests will need the session id to run properly.
How can I achieve this in protractor?
Thanks!
The relevant parts of my code looks like this...
home.spec.js:
describe('home page tests', function() {
var loginPage = new LoginPage();
var homePage;
// get sessionId from login and create a new HomePage object from it
beforeEach(function() {
var sessionId = loginPage.login('testuser#example.com', 'testuser');
homePage = new HomePage(sessionId);
homePage.get();
});
describe('main elements of home page test', function() {
it('page has correct username as part of user menu', function() {
expect(homePage.getUsername()).toEqual('testuser#example.com');
});
});
});
login.po.js:
function LoginPage {
// ...snip...
this.login = function(username, password) {
return this.get()
.then(function() {
this.username.sendKeys(username);
this.password.sendKeys(password);
this.loginButton.click();
})
.then(function() {
return browser.getCurrentUrl().then(function(url) {
var groups = sessionIdRegex.exec(url);
// return the extracted session id or null if there is none
if (groups !== null) {
return sessionIdRegex.exec(url)[2];
} else {
return null;
}
});
});
};
}
home.po.js:
function HomePage(sessionId) {
this.username = element(by.binding('username'));
this.getUsername = function() {
return this.username.getText();
}
this.get = function() {
return browser.get(browser.baseUrl + sessionId + '#/home');
};
};
module.exports = HomePage;
The simplest could be to use expect:
Jasmine expectations are also adapted to understand promises. That's why the line
`expect(name.getText()).toEqual('Jane Doe');
works - this code actually adds an expectation task to the control flow, which will run after the other tasks.
login.po.js:
function LoginPage {
this.login = function(username, password) {
return this.get()
.then(function() {
this.username.sendKeys(username);
this.password.sendKeys(password);
this.loginButton.click();
})
.then(function() {
return browser.getCurrentUrl().then(function(url) {
var groups = sessionIdRegex.exec(url);
// return the extracted session id or null if there is none
if (groups !== null) {
return sessionIdRegex.exec(url)[2];
} else {
return null;
}
});
});
};
expect(this.login).not.toBeUndefined();
}

angular service not work as singleton

Angular doc states:
Angular services are singletons
I want to use the angular service as singleton, so I can access the logged-in user data every where in my application. but the serivce does not seem to return the same data, here is my codes.
Service:
angular.module("myapp", [])
.service("identity", function (){
this.token = null;
this.user = null;
});
Facotry:
.factory("authentication", function (identity, config, $http, $cookieStore) {
var authentication = {};
authentication.login = function (email, password, remember) {
var p=$http.post(config.baseUrl+"api/","email="+email+"&password="+password);
return p.then(function (response) {
identity= response.data;
if (remember) {
$cookieStore.put("identity", identity);
}
});
};
authentication.isAuthenticated = function () {
if (!identity.token) {
//try the cookie
identity = $cookieStore.get("identity") || {};
}
console.log(identity) // {token: 23832943, user: {name: something}}
return !!identity.token;
};
return authentication;
});
controller:
.controller('LoginCtrl', function ($state, $scope, authentication, identity) {
var user = $scope.user = {};
$scope.login = function () {
authentication.login(user.email, user.password, user.remember)
.then(function () {
if (authentication.isAuthenticated()) {
console.log(identity); // {token:null, user: null}
$state.transitionTo("dashboard");
}
});
};
});
The identity is injected to both authentication and controller. But the first console logs the correct user data, while the second console just logs the same data as initially defined. If the service is singleton as stated, I would expect two identity returns the same data. What am I doing wrong here?. any pointers are appreciated.
In your authentication service change
identity= response.data;
to
identity.token=response.data.token;
identity.user=response.data.user;
and things should work.
Basically what you are doing is replacing the identity object reference.

Angular UI Router and server side redirecting

I'm building a small Meteor app and I've stumbled upon a minor setback.
I was using Iron:Router and Angular UI Router which led to some difficulties. I had to remove the Iron:Router to resolve them and by doing that I lost the benefit of redirecting to an URL on the server side. How I used to redirect and process using the Iron:Router:
Router.route('/payment/:invoice_no/:amount/:userId', {
where: 'server',
action: function() {
var amount = parseInt(this.params.amount);
var url = generate_URL_for_payment_authorization(this.params.invoice_no,this.params.amount,this.params.userId);
if (url == null) {
this.response.end("error");
}
this.response.writeHead(301, { 'Location': url});
this.response.end();
}
});
How I rewrote the previous code using the Angular UI Router:
.state('premiumPayment', {
url: '/payment/:invoice_no/:amount/:userId',
controller: function($scope, $stateParams, $http) {
var invoice_no = $stateParams.invoice_no;
var amount = $stateParams.amount;
var userId = $stateParams.userId;
Meteor.call('testingFunction', invoice_no, amount, userId, (error) => {
if (error) {
alert(error);
}
else {
console.log('Going to PayPal screen!');
}
});
}
})
And the testingFunction. I would like to know how do I redirect once I got the URL?
testingFunction: function (invoice_no, amount, userId) {
console.log(invoice_no);
console.log(amount);
console.log(userId);
var url = "";
if (Meteor.isServer) {
url = generate_URL_for_payment_authorization(invoice_no,amount,userId);
console.log("Going to this URL now: " + url);
//HOW DO I REDIRECT TO THE URL HERE???
}
}
So basically what I'm asking, how do I navigate to that URL which I get in the testingFunction function? I can't use Iron:Router because I'll get some unwanted behaviour back into my app.

Categories