how to resolve firebase $waitForAuth() .then do something - angularjs

In my app i want to resolve a few things before the front page loads. on my other pages its easy for me as i use this function in my resolve:
userAccount.$inject = ['userService','authService'];
function userAccount(userService, authService) {
return authService.firebaseAuthObject.$requireAuth()
.then(function(response) {
return userService.getAccount(response.uid).$loaded();
});
}
And it requires Authorisation, once promise is returned it gets the user data in firebase i saved elsewere. And if the promise is revoked it wont load that page.
But on the home page i want to check if user is logged in, If the user is logged in, grab the users data and goto the page. BUT if the user is not logged in, still go to the page just the user data will be empty.
I currently am using this to check Auth:
checkAuth.$inject = ['userService', 'authService'];
function checkAuth(userService, authService) {
return authService.firebaseAuthObject.$waitForAuth()
}
Which works good, but i still want to resolve the users data before loading the page only IF the user is logged in.
I assumed that this was my answer:
checkAuth.$inject = ['userService','authService'];
function checkAuth(userService, authService) {
return authService.firebaseAuthObject.$waitForAuth()
.then(function(response) {
return checkAuth.getAccount(response.uid).$loaded();
});
}
Which would wait for the promise then load in the users data, but unfortunately this doesnt work.
Any ideas on how i can retrieve the users data once the $waitforauth() function has run, the key is i want to resolve this data before the page loads.
Thanks guys
my state that also doesnt work:
.state('home', {
url: '/',
templateUrl: '/views/main.html',
controller: 'MainCtrl as vm',
resolve: {
checkAuth: checkAuth,
userAccount: function(checkAuth){
console.log(checkAuth);
if(checkAuth){
// grab user data
} else {
return false;
}
}
}
})

This got it done for me.
State:
.state('main', {
url: '/',
templateUrl: '/views/main.html',
controller: 'MainCtrl as vm',
resolve: {
userAccount: userAccountMain
}
})
Function:
userAccountMain.$inject = ['userService', 'authService'];
function userAccountMain(userService, authService) {
return authService.firebaseAuthObject.$waitForAuth()
.then(function(response){
if(response){
return userService.getAccount(response.uid).$loaded();
} else {
return false;
}
});
}

Related

AngularJS - how to call an endpoint in the route resolve?

I'm working on an AngularJS 1.5.3 project.
There is one page in my app that needs some server information before going to the page. It's kind of like a route guard. No other pages need this information before proceeding.
How can I get this to work in my route resolve? Is this a valid approach to this problem?
e.g.
.state('verifyCredentials', {
url: '/verifyCredentials',
templateUrl: 'verifyCredentials/verify-credentials.html',
controller: 'VerifyCredentialsController',
controllerAs: 'verifyCredentialsController',
resolve: {
//calls http request
authentication
.getInfo()
.then(function(response) {
if(response.goToHome === true) {
//$state.go('home);
} else {
//proceed to verify credentials
}
})
}
})
An AngularJS (1.x) resolve: block is an object on a state definition. Each key is the name of some data to load, and each value is a function which returns a promise for the data.
Resolve functions are injected using Angular’s injector.
An example can be found in the ui-router tutorial.
You are not providing a valid object to your resolve. The authentication should be a value to a key. Here is how your resolve should look.
.state('verifyCredentials', {
url: '/verifyCredentials',
templateUrl: 'verifyCredentials/verify-credentials.html',
controller: 'VerifyCredentialsController',
controllerAs: 'verifyCredentialsController',
resolve: {
authenticate: function(authentication, $state) { // you'll need to inject $state
and your authentication service here if you want to use them.
return authentication
.getInfo()
.then(function(response) {
if(response.goToHome === true) {
$state.go('home');
} else {
//proceed to verify credentials
}
});
}
})
Another possibility is to use the redirectTo method on the state object in order to redirect to a different state depending on the resolve.
Use the redirectTo with the resolve like so:
.state('verifyCredentials', {
resolve: {
authResolve: function(authenticate) {
return authentication.getInfo();
}
},
redirectTo: (trans) => {
// getAsync tells the resolve to load
let resolvePromise = trans.injector().getAsync('authResolve')
return resolvePromise.then(resolveData => {
return resolveData.loggedIn === true ? 'home' : null; // go to home if logged in, else stay on this route in order to continue with credentials flow.
)}
})
Here is how the doc recommend to handle resolves. They use component architecture.
.state('verifyCredentials', {
url: '/verifyCredentials',
component: 'verifyCredentialsComponent',
resolve: {
authenticateData: function(authentication, $state) { // you'll need to inject $state
and your authentication service here if you want to use them.
return authentication
.getInfo()
.then(function(response) {
if(response.goToHome === true) {
$state.go('home');
} else {
//proceed to verify credentials
}
});
}
})
// component
angular.module('app').component('verifyCredentialsComponent', {
bindings: {
authenticateData: '<'
},
template: '<div></div>'
controller: function() {
...
}
})

angularjs- Why http request returns false with resolve?

I have a login system...and I'm trying to implement login/logout feature to a website.
This is the fiddle I'm following- FIDDLE
This is my route file:
(function() {
var onlyLoggedIn = function($location, $q, AuthService2) {
var deferred = $q.defer();
if (AuthService2.isLogin()) {
deferred.resolve();
} else {
deferred.reject();
$location.url('/login');
}
return deferred.promise;
};
angular.module('myApp', [
'ngRoute',
'myApp.login',
'myApp.home',
'myApp.logout',
'myApp.notifications'
])
.factory('AuthService2', ["$http", "$location", function($http, $location) {
//var vm = this;
var baseUrl = 'api/';
return {
isLogin: function() {
var token;
if (localStorage['entrp_token']) {
token = JSON.parse(localStorage['entrp_token']);
} else {
token = "";
}
var data = {
token: token
};
$http.post(baseUrl + 'validateUserToken', data).success(function(response) {
if (response.msg == "authorized") {
//console.log(response.msg);
return localStorage.isLogged === "true";
} else {
return localStorage.isLogged === "false";
}
});
}
}
return {
isLogin: isLogin
};
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'app/components/login/loginView.html',
controllerAs: 'vm'
})
.when('/home', {
controller: 'HomeController',
templateUrl: 'app/components/home/homeView.html',
resolve: {
loggedIn: onlyLoggedIn
},
controllerAs: 'vm'
})
.when('/logout', {
controller: 'LogoutController',
templateUrl: 'app/components/login/loginView.html',
resolve: {
loggedIn: onlyLoggedIn
},
controllerAs: 'vm'
})
.when('/notifications', {
controller: 'NotificationsController',
templateUrl: 'app/components/notifications/notificationsView.html',
resolve: {
loggedIn: onlyLoggedIn
},
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/login'
});
}]);
})();
Users will be visiting login page. After authentication, I set a session and a local storage token.
I use resolve to check whether the user is valid or not. I defined a function for that (as you can see it from the code).
Upon login, I'm able to validate the user and set the session and login controller redirects the valid user to home. But the user reaches the route and he stays in login page itself.
My http request is fine. I checked it and it returns correct result. But I think the function returns false and afterthat only the http request is getting executed. because I can see the http request in consoel and it returns positive result, so the user should get navigated but it's not happening because http request is getting delayed or something.
I tried giving an alert message inside this if else,and it always goes to else condition, no matter what.
if (AuthService2.isLogin()) {
deferred.resolve();
} else {
deferred.reject();
$location.url('/login');
}
Why is it so? I'm pretty much new to ANgular. Is this a limitation of angular?
The problem is that there is no return statement in your isLogin function.
Your return statement is inside the $http.post callback NOT isLogin hence isLogin return undefined thus resolved to falsy.
$http.post(baseUrl + 'validateUserToken', data).success(function(response) {
//Notice that you are inside function(response) closure.
if (response.msg == "authorized") {
return localStorage.isLogged === "true";
} else {
return localStorage.isLogged === "false";
}
});
I can suggest you to return $http.post instead, $http.post return a promise object which you can use in such way, below is an brief example on how you can do it.
isLogin: function() {
//Omitted some code
//This method return a promise object
return $http.post(baseUrl + 'validateUserToken', data);
});
AuthService2.isLogin().then(function(res){
if (response.msg == "authorized") {
deferred.resolve();
} else {
deferred.reject();
$location.url('/login');
}
}, errorCallback); //Optional if you want to handle when post request failed
Code is not tested, just to give you the idea.

How to prevent state change until value is resolved

I have authentication set up in such a way that I want to prevent any route/state from loading until I know that the user is authorized to access the page. If they are, then the requested page should load, if not, then it should go to the login page.
My config function:
$stateProvider
.state('login', {
url: '/login',
templateUrl : 'login.html',
controller : 'loginController',
data: {
authorizedRoles: [USER_ROLES.guest]
}
})
.state('home', {
url: '/',
templateUrl : 'home.html',
controller : 'homeController',
data: {
authorizedRoles: [USER_ROLES.admin]
}
})
.state('admin', {
url: '/admin',
templateUrl : 'admin.html',
controller : 'adminController',
data: {
authorizedRoles: [USER_ROLES.admin]
}
});
$urlRouterProvider.otherwise('/login');
$locationProvider.html5Mode(true);
My run function:
$rootScope.$on('$stateChangeStart', function(event, next) {
event.preventDefault();
function checkAuthorization() {
if(!AuthService.isAuthorized(authRole)) {
$state.go('login');
} else {
$state.go(next.name);
}
}
if(AuthService.getRoleId() === undefined) {
// We'll have to send request to server to see if user is logged in
AuthService.checkLogin().then(function(response) {
checkAuthorization();
});
} else {
checkAuthorization();
}
})
If I keep the event.preventDefault() in my run function, then the app will be stuck in a loop always going to the requested state. If I remove the event.preventDefault() statement then the app will load the view (which will be visible for a second) before realizing the user should not be allowed to view it (and then go to the correct state).
How can I solve this problem?
You should use resolve and make request to the server to see if user is logged in the resolve
https://github.com/angular-ui/ui-router/wiki#resolve
.state('whatever',{
...
promiseObj: function($http){
// $http returns a promise for the url data
return $http({method: 'GET', url: '/someUrl'}).$promise;
},
...
}
OR
if you have make a call in the controller, make the call in resolve in state, in which your api should response with a 401 if user is not login in and redirect to the log in screen if you have an intercept service.
There is detailed explanation how to do this kind of resolve/wait stuff in this Q & A with working plunker.
An extracted version of the Auth service is:
.factory('userService', function ($timeout, $q) {
var user = undefined;
return {
// async way how to load user from Server API
getAuthObject: function () {
var deferred = $q.defer();
// later we can use this quick way -
// - once user is already loaded
if (user) {
return $q.when(user);
}
// server fake call, in action would be $http
$timeout(function () {
// server returned UN authenticated user
user = {isAuthenticated: false };
// here resolved after 500ms
deferred.resolve(user)
}, 500)
return deferred.promise;
},
// sync, quick way how to check IS authenticated...
isAuthenticated: function () {
return user !== undefined
&& user.isAuthenticated;
}
};
})
where the most important parts are
var user = undefined; - "global" variable which is
containing user and can answer if he has rights
does not contain user (yet) and the answer is "not authorized" then
returned service function: isAuthenticated
That should solve the issue. check more details here

Confusing $locationChangeSuccess and $stateChangeStart

I am trying to do some authentication with AngularUI Router. $urlRouter.sync() looks like exactly what I need. However, that's only available when I intercept $locationChangeSuccess. But when I do that, $state.current.name is empty, whereas I want it to be the current state.
Here's my code so far:
$rootScope.$on('$locationChangeSuccess', function(event, next, nextParams) {
event.preventDefault();
if ($state.current.name === 'login') {
return userService.isAuthenticated().then(function(response) {
var authenticated;
authenticated = response.authenticated;
return alert(authenticated);
});
}
});
Any pointers as to what I'm doing wrong?
I would suggest to go more "UI-Router way". We should use $rootScope.$on('$stateChangeStart' event where $state.current would be properly provided. Here is a working example
Let's observe simple (but not naive) solution, which could be extended to any degree later. Also if you will like this approach, here is much more comprehensive implementation: angular ui-router login authentication
Firstly, let's have our user service defined like this:
.factory('userService', function ($timeout, $q) {
var user = undefined;
return {
// async way how to load user from Server API
getAuthObject: function () {
var deferred = $q.defer();
// later we can use this quick way -
// - once user is already loaded
if (user) {
return $q.when(user);
}
// server fake call, in action would be $http
$timeout(function () {
// server returned UN authenticated user
user = {isAuthenticated: false };
// here resolved after 500ms
deferred.resolve(user)
}, 500)
return deferred.promise;
},
// sync, quick way how to check IS authenticated...
isAuthenticated: function () {
return user !== undefined
&& user.isAuthenticated;
}
};
})
So, we use async (here $timeout) to load user object form a server. In our example it will have a property {isAuthenticated: false }, which will be used to check if is authenticated.
There is also sync method isAuthenticated() which, until user is loaded and allowed - always returns false.
And that would be our listener of the '$stateChangeStart' event:
.run(['$rootScope', '$state', 'userService',
function ($rootScope, $state, userService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams
, fromState, fromParams) {
// if already authenticated...
var isAuthenticated = userService.isAuthenticated();
// any public action is allowed
var isPublicAction = angular.isObject(toState.data)
&& toState.data.isPublic === true;
if (isPublicAction || isAuthenticated) {
return;
}
// stop state change
event.preventDefault();
// async load user
userService
.getAuthObject()
.then(function (user) {
var isAuthenticated = user.isAuthenticated === true;
if (isAuthenticated) {
// let's continue, use is allowed
$state.go(toState, toParams)
return;
}
// log on / sign in...
$state.go("login");
})
...
What we are checking first, is if user is already loaded and authenticated (var isAuthenticated = ...). Next we will give green to any public method. This is done with the data {} property of the state object definition (see Attach Custom Data to State Objects)
And that's it. In case of states defined like in a below snippet we can experience:
the 'public', 'home' are allowed to anybody
the 'private', 'private' will redirect to login if isAuthenticated === false
the 'login' in this example provides quick way how to switch isAuthenticated on/off
// States
$stateProvider
// public
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
data: { isPublic: true },
})
.state('public', {
url: "/public",
templateUrl: 'tpl.html',
data: { isPublic: true },
})
// private
.state('private', {
url: "/private",
templateUrl: 'tpl.html',
})
.state('private2', {
url: "/private2",
templateUrl: 'tpl.html',
})
// login
.state('login', {
url: "/login",
templateUrl: 'tpl.html',
data: { isPublic: true },
controller: 'loginCtrl',
})
Check that all here
Some other resources:
angular ui-router login authentication
Angular UI Router: nested states for home to differentiate logged in and logged out
other state data and authentication

Waiting for $http before running angular spa

I have a SPA using JWT (json web tokens) for authorization to the api. The problem is when they hit refresh on the browser after being logged in I need to verify the token is still valid via an ajax request and then continue loading the SPA. I added this to the .run() which kind of works, but since my navigation changes if they are logged in, the page loads before the token is verified, and looks wrong. I'm new to angular, but guess this could be done with a promise?
// handle refreshing browser
if ($window.sessionStorage.token && !AuthenticationService.isLogged()) {
UserService.verify().success(function (data) {
AuthenticationService.setLogged(true);
}).error(function () {
delete $window.sessionStorage.token;
$state.transitionTo('app.login');
});
}
I was able to get this working with the following state setup:
$stateProvider
.state('app', {
abstract: true,
url: '/',
views: {
root: {
templateUrl: 'tpl/index.html'
}
},
resolve: {
User: ['$window', '$q', 'AuthenticationService', 'UserService' , function($window, $q, AuthenticationService, UserService) {
if ($window.sessionStorage.token && !AuthenticationService.isLogged()) {
var d = $q.defer();
UserService.verify().success(function (data) {
AuthenticationService.setLogged(true);
d.resolve();
}).error(function () {
delete $window.sessionStorage.token;
d.resolve();
});
return d.promise;
}
}]
}
});

Resources