Auth redirects to wrong path - javascript

I have this strange behaviour on my AngularFire Auth function.
The user logs in with email+password and on success it should redirect to /dash, but is redirecting to /home.
/dash is locked for unauth and work as expected, but when I log in and are being redirected to /home, if I type /dash in the browser it's accessible. So, it IS working but my redirecting behaviour is obviously wonky. Also it seems like it's trying to access /dash because it flickers by quickly before sending me to /home on successful login.
I'm using latest Angular + AngularFire + Firebase.
I've tried to set up a plunkr-view of it but it seems to be something with plunkr and firebase that doesn't work.
Anyhow, here's my auth code and my route code, all ideas are welcome!
app.controller('loginController', ['currentAuth', '$scope', '$firebaseAuth', 'Auth', '$location', '$rootScope',
function(currentAuth, $scope, $firebaseAuth, Auth, $location, $rootScope){
var ref = new Firebase('https://url.firebaseio.com');
$scope.auth = $firebaseAuth(ref);
// Login user, if true redirect to dash.html, if false, don't redirect, show error message
$scope.loginUser = function(){
$scope.auth = Auth;
$scope.auth.$authWithPassword({
email:$scope.email,
password:$scope.password
}, {
remember: 'sessionOnly'
}).then(function(authData) {
console.log('Logged in as: ', authData.uid);
$scope.auth.$onAuth(function(authData) {
$rootScope.auth = true;
$scope.auth = Auth;
$location.path('/dash.html');
})
// If error with login, catch it and prompt it
}).catch(function(error) {
$('#signBlock').text(error);
});
};
}
]);
And routes:
app.run(['$rootScope', '$location', 'Auth',
function($rootScope, $location, Auth){
$rootScope.$on('$routeChangeError',
function(event, next, previous, error){
if(error === 'AUTH_REQUIRED'){
console.log('AUTH REQ!')
$location.path('/home');
}
});
}]);
// Config for routing
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
// Route for landing page
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
// Route for login page
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$waitForAuth();
}]
}
})
// Route for user dashboard
.when('/dash', {
templateUrl: '/dash.html',
controller: 'dashController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$requireAuth();
}]
}
})
.otherwise({ redirectTo: '/home' });
}]);

Related

Can pass login page with wrong password/username AngularJS

If type the username or password once wrong and change manually the URL to my home GUI, I get access to it without any authentication.
I can't explain why :/
this is my app.js, where all the routing happens and a fiddle with my controller and my html data :
(function() {
'use strict';
// declare modules
angular.module('Authentication', []);
angular.module('Home', ['naif.base64', 'ngFileSaver']);
//dependecies of the module
angular.module('JMeterGui', ['Authentication','Home','ngRoute', 'ngCookies'])
//configure the module
.config(config)
//configure the start of the module
.run(run);
//dependencies of the config module
config.$inject = ['$routeProvider', '$locationProvider', '$qProvider'];
//configure routing depends on the actual URL
function config($routeProvider, $locationProvider, $qProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html'
})
.otherwise({ redirectTo: '/login' });
}
//dependecies of the run module
run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
function run($rootScope, $location, $cookies, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookies.getObject('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in
var restrictedPage = $.inArray($location.path(), ['/login']) === -1;
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
})()
my fiddle with controller and html
Anyone knows why ?
Try to add:
if (restrictedPage && !loggedIn) {
//Prevent default
event.preventDefault();
$location.path('/login');
}

Angularfire ngRoute/resolve issue, jumps to otherwise

I'm using the latest Angular + Firebase and trying to set up a login authorization system. I have home.html which contains login+signup links, going to login.html and adding credentials works just fine (logging correct UID when submittet) but it's supposed to route to dash.html but goes back to home.html.
I've figured out that it seem to be issues with my resolve functions because the problem disappears when I remove .otherwise. But I still want (need?) it there I think.
If I'm logged in (but redirected to home.html) I can still access dash.html through the URL and I cannot access it again if I use the logout function at dash.html and that's how it should be.
But I can't figure out why I'm redirected to home.html in the first place.
Here's some of the code, any help appreciated:
My .run, .config and routes.
app.run(['$rootScope', '$location',
function($rootScope, $location){
$rootScope.$on('$routeChangeError',
function(event, next, previous, error){
if(error === 'AUTH_REQUIRED'){
$location.path('/home');
}
});
}]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider,
$locationProvider){
$routeProvider
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$waitForAuth();
}]
}
})
.when('/dash', {
templateUrl: '/dash.html',
controller: 'dashController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$requireAuth();
}]
}
})
.otherwise({ redirectTo: '/home' });
}]);
My login controller:
app.controller('loginController', ['currentAuth', '$scope', '$firebaseAuth',
'Auth', '$location', '$rootScope',
function(currentAuth, $scope, $firebaseAuth, Auth, $location, $rootScope){
var ref = new Firebase('https://url.firebaseio.com');
$scope.auth = $firebaseAuth(ref);
$scope.loginUser = function(){
$scope.auth = Auth;
$scope.auth.$authWithPassword({
email:$scope.email,
password:$scope.password
}, {
remember: 'sessionOnly'
}).then(function(authData) {
console.log('Logged in as: ', authData.uid);
$scope.auth.$onAuth(function(authData) {
$rootScope.auth = true;
$scope.auth = Auth;
$location.path('/dash.html');
})
}).catch(function(error) {
console.log('There was an error: ', error);
});
};
}]);
And my factory and module:
var app = angular.module('app', ['firebase', 'ngRoute']);
app.factory('Auth', ['$firebaseAuth',
function($firebaseAuth){
var ref = new Firebase('https://url.firebaseio.com');
return $firebaseAuth(ref);
}]);
it has with your resolve issue.
If you look at the documentation firebase doc
you will see that they use the
$waitForSignIn
or
$requireSignIn
functions. I know that because I have done the same thing. Try that instead and it should work

How to load login page as first page

I am using ionic framework. I am trying to load login page as first page but cant see its just getting an empty page.
My code looks like
app.js:
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
and controller:
.controller('AppCtrl', function ($scope, $state, $ionicModal) {
$ionicModal.fromTemplateUrl('templates/login.html', function(modal) {
$scope.loginModal = modal;
},
{
scope: $scope,
animation: 'slide-in-up',
focusFirstInput: true
}
);
//Be sure to cleanup the modal by removing it from the DOM
$scope.$on('$destroy', function() {
$scope.loginModal.remove();
});
.controller('LoginCtrl', function ($scope, $state, AuthenticationService) {
$scope.message = "";
$scope.user = {
username: null,
password: null
};
$scope.login = function () {
AuthenticationService.login($scope.user);
};
$scope.$on('event:auth-loginRequired', function (e, rejection) {
console.log('handling login required');
$scope.loginModal.show();
});
$scope.$on('event:auth-loginConfirmed', function () {
$scope.username = null;
$scope.password = null;
$scope.loginModal.hide();
});
But still cant see it.
my app looks like
https://github.com/keithdmoore/ionic-http-auth but without the home page.
Thnx!
try to change your app.config section.
app.config(function ($stateProvider) {
$stateProvider.otherwise({ redirectTo: '/login' });
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
}).state('login', {
url: "/login",
templateUrl: "login.html page url",
controller: 'login controller'
}));
don't need to write any code appcontroller'. Whenever you run the application the url path is should be empty. So this line $stateProvider.otherwise({ redirectTo: '/login' }); helps to open the login screen.

Manage Access using $routeChangeStart

Am Trying to manage access to some urls. when Am not logged in and i try to navigate to the home page it must redirect me to login page.
This what happens when I navigate to the home page '/' : in my browser the url is #!/login but inside ng-view i get the home view instead of login view.
Navigation to login and signup works fine
var app = angular.module('todo', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');
$routeProvider
.when("/", {
controller: "homeController",
templateUrl: "app/partials/home.html",
requireAuth: true
})
.when("/login", {
controller: "loginController",
templateUrl: "app/partials/login.html",
requireAuth: false
})
.when("/signup", {
controller: "signupController",
templateUrl: "app/partials/signup.html",
requireAuth: false
})
.otherwise({ redirectTo: "/" });
}])
// Manage Access
.run(['$rootScope', '$location', 'authService', function($rootScope, $location, authService){
$rootScope.$on('$routeChangeStart', function(evt, next, current){
if((!authService.userInfo.isAuth)&&(next.requireAuth)){
$location.path('login');
}
})
}]);
The behaviour of being able to change $location during a $routeChangeStart event was altered in Angular 1.3.0. This was fixed in a more recent update, so you can either update to the latest version, or use this workaround:
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if ((!authService.userInfo.isAuth) && (next.requireAuth)) {
event.preventDefault();
$rootScope.$evalAsync(function() {
$location.path('/login');
});
}
});

Yeoman: AngularJS & facebook SDK, page not loading

So im new with Angular and i downloaded the Yeoman scaffolding for Angular.JS to fiddle with it a bit.
I'm trying to implement Facebook Login with this library: https://github.com/pc035860/angular-easyfb
Nothing is loading and the console doesnt reflect anything. I'm almost sure the problem has something to do with the injecting of the facebook dependency on the controller.
I have this on my main.js file:
angular.module('circeApp', ['ezfb'])
.controller('MainCtrl', function($scope, ezfb, $window, $location) {
updateLoginStatus(updateApiMe);
$scope.login = function(){
ezfb.login(function(response){
if(response.authResponse){
updateLoginStatus(updateApiMe);
}
}, {scope: 'email,user_likes'});
};
$scope.logout = function(){
ezfb.logout(function(){
updateLoginStatus(updateApiMe);
});
};
function updateLoginStatus(more){
ezfb.getLoginStatus(function(response){
$scope.loginStatus = response;
(more || anular.noop)();
});
}
function updateApiMe(){
ezfb.api('/me', function(response){
$scope.apiMe = response;
});
}
});
And this on my app.js file:
'use strict';
angular.module('circeApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ezfb'
])
.config(function ($routeProvider, $locationProvider, $httpProvider, ezfbProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'partials/login',
controller: 'LoginCtrl'
})
.when('/signup', {
templateUrl: 'partials/signup',
controller: 'SignupCtrl'
})
.when('/settings', {
templateUrl: 'partials/settings',
controller: 'SettingsCtrl',
authenticate: true
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
// Intercept 401s and redirect you to login
$httpProvider.interceptors.push(['$q', '$location', function($q, $location) {
return {
'responseError': function(response) {
if(response.status === 401) {
$location.path('/login');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
}]);
})
.run(function ($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$routeChangeStart', function (event, next) {
if (next.authenticate && !Auth.isLoggedIn()) {
$location.path('/login');
}
});
//Configure ezfb provider aqui
ezfbProvider.setInitParams({
appId: 'XXXXXXXXXXXX',
status: true,
cookie: true,
xfbml: true
});
});
Before this, the page rendered but console told me: "Argument 'MainCtrl' is not a function, got undefined". I fixed a missing parenthesis and made sure ezfb was included in angular.module. Now, the only thing i get is a blank page.

Categories

Resources