I hav a controller responsible for navigation, it checks the cookie and if the user is logged in shows and hides navigation menu.
nav.js - controller
'use strict';
//app global variable
//this is the controller that handles post requests
//declare services as dependecies $http, $location, custom service apiServiceWeb
app.controller('navigationController', function($scope, $route, $rootScope, $http, $location, $cookies, setCredentials) {
//get what is in the cookie
var cookieValue = setCredentials.getCookie('globals');
if (cookieValue == '[object Object]') {
//redirect to home
$location.path("/");
//remove cookie
//setCredentials.removeCookie('globals');
}
//hide menu in certain paths
if ($location.path() == '/' || $location.path() == 'signup' || cookieValue == '[object Object]') {
//hide menu
$scope.isConnected = true;
} else {
$rootScope.$watch('globals', function() {
//if a currentUser does NOT exist, the hide menu.
console.log('changed');
// console.log($rootScope.globals);
if (cookieValue = null) {
$scope.isConnected = true;
} else {
//show menu, user is logged in
$scope.isConnected = false;
}
});
}
});
However the problem is, if the user clicks back and they end up in the login page. The nav.js controller does not reload, meaning the menu that shows when the user is logged in, shows on the login page.
So far I have detected when the user clicks back, like this:
app.js
/* global app:true */
/* exported app */
'use strict';
/**
* #ngdoc overview
* #name WebAppApp
* #description
* # WebAppApp
*
* Main module of the application.
*/
var app = angular
.module('WebAppApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/login.html',
controller: 'loginCtrl',
// controllerAs: 'login'
})
.when('/home', {
controller: 'homeCtrl',
templateUrl: 'views/home.html',
resolve: {
"checkLoggedIn": function($location, $cookies, $rootScope) {
if (!$cookies.get('globals')) {
$location.path('/');
}
}
},
//controllerAs: 'home'
})
.when('/signup', {
templateUrl: 'views/signup.html',
controller: 'signupCtrl',
//controllerAs: 'home'
})
.otherwise({
redirectTo: '/'
});
});
//when app runs call this function.
app.run(function($rootScope, $route, $location){
//Bind the `$locationChangeSuccess` event on the rootScope, so that we dont need to
//bind in induvidual controllers.
$rootScope.$on('$locationChangeSuccess', function() {
$rootScope.actualLocation = $location.path();
});
$rootScope.$watch(function () {return $location.path()}, function (newLocation, oldLocation) {
if($rootScope.actualLocation === newLocation) {
alert('Why did you use history back?');
alert($rootScope.actualLocation);
if($rootScope.actualLocation=='/'){
//clear cookie
}
}
});
});
I basically would like to reload the nav.js controller once I detect the user is back to the login page or other pages where the nav bar should not appear.
How can I achieve this?
Thanks
Related
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');
}
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 am trying to create a pagination using Angularjs in Ionic Framework. Please help me to write code of pagination. I am getting data form this json url.
controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function() {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
console.log('Doing login', $scope.loginData);
// Simulate a login delay. Remove this and replace with your login
// code if using a login system
$timeout(function() {
$scope.closeLogin();
}, 1000);
};
})
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
$scope.data = response.data;
});
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
});
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.search', {
url: '/search',
views: {
'menuContent': {
templateUrl: 'templates/search.html'
}
}
})
.state('app.browse', {
url: '/browse',
views: {
'menuContent': {
templateUrl: 'templates/browse.html'
}
}
})
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'templates/playlists.html',
controller: 'PlaylistsCtrl'
}
}
})
.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'templates/playlist.html',
controller: 'PlaylistCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
});
playlists.html
<ion-view view-title="Playlists">
<ion-content>
<ion-list>
<ion-item ng-repeat="playlist in data | firstPage:currentPage*pageSize | limitTo:pageSize" href="#/app/playlists/{{playlist.id}}">
{{playlist.title}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
<< 1/2/3/4/5 >>
You need to set pageSize to the total number of movies returned as the response does not contain any meta data about the response:
.controller('PlaylistsCtrl', function($scope, $http, $log) {
$http.get('https://raw.githubusercontent.com/bantic/imdb-data-scraping/master/data/movies.json')
.then(function(response)
{
// populate data with the array of movies
$scope.data = response.data;
// set the page size to the total number of movies
$scope.pageSize = $scope.data.length;
});
});
I am using route resolver in angularjs,for user will be redirect to login if user is not logged in as follows,
$routeProvider
.when('/', {
templateUrl: 'app/components/main/dashboard.html',
controller: 'dashboardController',
resolve: {
login: function ($rootScope, $location) {
if (!$rootScope.currentUser) {
$location.path('/login');
}
}
}
})
Here I want use this login function in many other routes,So i can copy paste same resolve function to every where as follows,
.when('/items', {
templateUrl: 'app/components/item/list.html',
controller: 'itemController',
resolve: {
login: function ($rootScope, $location) {
if (!$rootScope.currentUser) {
$location.path('/login');
}
}
}
})
It is working fine,my question is,is there any way to avoid this duplication of codes or is there any other better method ?
I set up a github repository yesterday which is a starting point for a web app and contains this feature here
If you look in public/app/app-routes.js you will see I have added resolve functions as variables, then you can simply do this rather than writing a whole function each time:
Function
var checkLoggedIn = function($q, $timeout, $http, $window, $location, $rootScope) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') {
$rootScope.loggedInUser = user;
$window.sessionStorage['loggedInUser'] = JSON.stringify(user);
deferred.resolve();
}
// Not Authenticated
else {
$window.sessionStorage['loggedInUser'] = null;
$rootScope.loggedInUser = null;
deferred.reject();
$location.url('/login');
}
});
return deferred.promise;
};
checkLoggedIn.$inject = ["$q", "$timeout", "$http", "$window", "$location", "$rootScope"];
Route
.when('/profile', {
title: 'Profile',
templateUrl: '/app/templates/profile.html',
controller: 'ProfileController',
resolve: {
loggedIn: checkLoggedIn
}
})
Should be easily adaptable for your app. Hope that helps!
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');
});
}
});