For some security reason, you application only allow authenticated user to have access to certain views while some other views can be accessed publicly.There are already a few solutions available. However, here I just want to show a simple way to handle the case.
- First, of course, you need to configure a route provider with a few views and controllers and etc.
- Then you need to define an authentication service factory to be in charge of the authentication.
- Third, you need to monitor the authentication status every time the route changes.
The following is the sample JavaScript code (together with the html file) to demonstrate how it is done. If you have more patience and you want to make the sample working on your end, you can check some notes below.
- The sample code just uses template to overwrite the value of templateUrl for each state definition. This is just to simplify the demo code. In a real world example, you would use templateUrl instead.
- The sample code does not actually make (RESTful) calls to the server to do the login check. This is also simplified for demo purpose. You can actually check the code that is commented for calling the server side API. Of course, you need to implement the server site API first to make it work.
- The skeleton of the above code is generated using yo angular generator. This is a very useful code generator which helps to build prototype in a quick way.
Java script code (app.js)
'use strict'; /** * @ngdoc overview * @name mytechtipdemoApp * @description * # mytechtipdemoApp * * Main module of the application. */ angular.module('mytechtipdemoApp', [ 'ngRoute' ]) .config(function ($routeProvider) { $routeProvider .when('/', { template: 'This is protected main view. <button ng-click="logout()">Logout</button>', templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/login', { template: '<form ng-submit="login()" name="loginForm"> username: <input type="text" ng-model="user.username"> <br/> password: <input type="password" ng-model="user.password"><button>login</button></form>', templateUrl: 'views/login.html', controller: 'LoginCtrl' }) .otherwise({ redirectTo: '/' }); }) .factory('Auth', function ($rootScope, $window, $http) { return { login: function (user, successHandler, errorHandler) { if (user.username == 'test' && user.password == 'test') { this.setLoggedInUser(user); successHandler(user); } else { alert("please use username/password as test/test to login"); errorHandler(user); } // call the server side login restful api // $http.post('api/login', user).success(function(user) { // this.setLoggedInUser(user); // successHandler(user); // }).error(errorHandler); }, getLoggedInUser: function () { if ($rootScope.user === undefined || $rootScope.user == null) { var userStr = $window.sessionStorage.getItem('user'); if (userStr) { $rootScope.user = angular.fromJson(userStr); } } return $rootScope.user; }, isLoggedIn: function () { return this.getLoggedInUser() != null; }, setLoggedInUser: function (user) { $rootScope.user = user; if (user == null) { $window.sessionStorage.removeItem('user'); } else { $window.sessionStorage.setItem('user', angular.toJson($rootScope.user)); } } }; }) .controller('LoginCtrl', function ($scope, Auth, $location, $http) { $scope.user = {}; $scope.login = function () { Auth.login($scope.user, function () { $location.path('/'); }, function (e) { // do some error handling. }); }; }) .controller('MainCtrl', function ($scope, Auth, $location) { $scope.logout = function () { Auth.setLoggedInUser(null); $location.path('/somewhere'); }; }) .run(['$window', '$rootScope', '$location', 'Auth', function ($window, $rootScope, $location, Auth) { $rootScope.$on("$routeChangeStart", function (event) { if (!Auth.isLoggedIn() && $location.path() !== '/login') { $location.path('/login'); } }); }]);
html file (index.html)
<!doctype html> <html class="no-js"> <head> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" /> <link rel="stylesheet" href="styles/main.css"> </head> <body ng-app="mytechtipdemoApp"> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <!-- Add your site or application content here --> <div class="container"> <div class="header"> <ul class="nav nav-pills pull-right"> <li><a ng-href="#/">Home</a></li> <li><a ng-href="#/login">Login</a></li> </ul> <h3 class="text-muted">mytechtipdemo</h3> </div> <div ng-view=""></div> <div class="footer"> </div> </div> <!-- java script files to be included --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js"></script> <script src="scripts/app.js"></script> </body> </html>
No comments:
Post a Comment