Created
November 17, 2013 20:51
-
-
Save toymachiner62/7518116 to your computer and use it in GitHub Desktop.
This is a simple example of Authentication and/or Authorization using html5's sessionStorage with AngularJS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Main module declaration | |
var myapp = angular.module('myapp', []); | |
// Set some actions to be performed when running the app | |
myezteam.run(['$location', '$rootScope', function($location, $rootScope) { | |
// Register listener to watch route changes. | |
// We use this to make sure a user is logged in when they try to retrieve data | |
$rootScope.$on( "$routeChangeStart", function(event, next, current) { | |
// If there is no token, that means the user is not logged in. | |
if(sessionStorage.getItem("token") == null) { | |
// Redirect to login page | |
window.location.href = "login.html"; | |
} | |
}); | |
}]); | |
// A controller for the login page | |
myapp.controller('LoginController', ['$scope', '$http', function($scope, $http) { | |
// If a user has check the "remember me" box previously and the email/password is in localStorage, set the email/password | |
if(localStorage.getItem("email") != null && localStorage.getItem("password") != null) { | |
$scope.user = { | |
email: localStorage.getItem("email"), | |
password: localStorage.getItem("password"), | |
remember: localStorage.getItem("remember") | |
} | |
} | |
// Login method when the form is submitted | |
$scope.login = function() { | |
// Authenticate the user - send a restful post request to the server and if the user is authenticated successfully, a token is returned | |
$http.post('http://example.com/login', $scope.user) | |
.success(function(response) { | |
// Set a sessionStorage item we're calling "token" | |
sessionStorage.setItem("token", response.token); | |
// Redirect to wherever you want to | |
window.location = 'index.html'; | |
}) | |
} | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can check angular 4 login example learn angularjs 4 tutorials.