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');
});
}
});
Related
I had created js (angular js code) file like below, but this js file not allowing to work other Javascript components.
'use strict';
// declare modules
angular.module('Authentication', []);
angular.module('Home', []);
angular.module('BasicHttpAuthExample', [
'Authentication',
'Home',
'ngRoute',
'ngCookies'
])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html',
hideMenus: true
})
.when('/home', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.when('/component1', {
controller: 'ComponentsController',
templateUrl: 'modules/home/views/components/component1.html'
})
.when('/databaseconfig',{
controller: 'DatabaseConfigController',
templateUrl: 'modules/home/view/components/databaseConfig.html'
})
.otherwise({ redirectTo: '/login' });
}])
When ('/component1', { controller: 'ComponentsController', templateUrl: 'modules/home/views/components/component1.html' })
let us say in component1.html file, I am using ng-show/ng-hide is not working. If I use jquery components like hide/show the div based on the radio button is not working. When I am not importing above mentioned js file in component1.html then jquery (hide/show div based on radio button) angularjs (ng-show/ng-hide) components are working.
.run(['$rootScope','$location','$cookieStore','$http',
function ($rootScope, $location, $cookieStore, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to login page if not logged in
if ($location.path() !== '/login' && !$rootScope.globals.currentUser) {
$location.path('/login');
}
});
}]);
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' });
}]);
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
I ask them to help solve this problem, follows the code :
Controller
angular.module('tareasApp')
.controller('HumorCtrl', function ($scope, $route, $location) {
$scope.pageName = $route.current.params.pageName;
$scope.items =[
{
href:'/humor/smile-today',
img:'smile.jpg',
descricao:'Those Relaxing Sounds of Waves'
}
];
});
angular.module('tareasApp')
.controller('NewsCtrl', function ($scope, $route, $location) {
$scope.pageName = $route.current.params.pageName;
$scope.items =[
{
href:'/news/news-today',
img:'news.jpg',
descricao:'Those Relaxing Sounds of Waves'
}
];
});
App.js
myApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
title: 'Home Page',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/humor/:pageName', {
templateUrl: 'views/wizard.html',
controller: 'HumorCtrl'
})
.when('/news/:pageName', {
templateUrl: 'views/wizard.html',
controller: 'NewsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
When I type any route that does not exist right after the bar, eg:
domain.com/hhhoedr
returns to the start page .
The problem is in the sub-directory, which contains the $routeParams, typing a page that does not exist , eg:
domain.com/humor/hhhoedr
is not redirecting to index.html or to 404.html.
I would like to adapt this code, I found in another answer, to my app.
myApp.constant('EXISTING_PAGES', [
'page1',
'page2',
...
]);
resolve: {
exists: function ($location, $route) {
if (EXISTING_PAGES.indexOf($route.current.params.page) === -1) {
$location.path('/error/404');
}
return true;
}
}
.when('/error/404', {
templateUrl: '404.html'
})
.otherwise({
redirectTo: '/error/404'
});
how can I do it?
When you are typing any route e.g-domain.com/hhhoedr,It is returning to starting page because check you last part of your code,you are setting it like below.
.otherwise({
redirectTo: '/'
});
If you will set anything except from your all .when part it will simple redirect to the starting page.Try to set it for redirecting to any other page as per your requirement.
Ok,Now you can write it like below.
.otherwise({
redirectTo: '/here give your destination path(e.g-404.html...etc)'
});
I am using AngularJs with Ruby on Rails.
I set the html5 option to true in angular: $locationProvider.html5Mode(true)
But now when I try to navigate through pages in my application, it will only change the URL in my browsers URL bar. But the page it self will nto change unless I reload the page. Only then will it go to the page specified.
This is how my Angular routing looks like:
#test.config(['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider) ->
# Route for '/'
$routeProvider.when('/', { templateUrl: '../../views/visitors/index.html.erb', controller: 'VisitorsCtrl' } )
$routeProvider.when('/users', { templateUrl: '../../views/users/index.html.erb', controller: 'UsersCtrl' } )
# Default
$routeProvider.otherwise( { redirectTo: "/" } )
$locationProvider.html5Mode(true)
])
On the root page I have a element: <h2><a ng-click="viewUsers()">Users</a></h2>
And viewUsers() is called here:
#test.controller 'VisitorsCtrl', ['$scope', '$location', '$http', ($scope, $location, $http) ->
$scope.viewUsers = ->
$location.path('/users')
console.log("Redirected")
]
What could be needed more to get this kind of routing to work?
New angular route:
Test.config ($routeProvider, $locationProvider) ->
$routeProvider
.when '/',
templateUrl: '../../views/visitors/index.html.erb',
controller: 'VisitorsCtrl'
.when '/users',
templateUrl: '../../views/users/index.html.erb',
controller: 'UsersCtrl'
try to use following instead:
$window.location.href = '/users'