javascript - restrict the redirection to login page once the user has already logged in even if he press the back button of browser in angular? -
i want make login page check conditon , user redirected home page afterwards , want implement condition when user has visited home page , clicks on button or browser should'nt able again visit login page . tried set variable islogged in false , after checking username , password make variable true , store in local storage , use flag , not able where's m wrong .
here app.js
var validationapp = angular.module('validationapp',['ngroute','ngstorage']); var loggedin = false; validationapp.run(function($rootscope, $localstorage){ //var loggedin = false; //if(!loggedin) { storage = window.localstorage; //storage.setitem("loggedin", true); //console.log(storage.getitem("loggedin")); // $rootscope.$storage = $localstorage.$default({ // loggedin: false // }) // } }); validationapp.controller('maincontroller', function($scope,loginservice,$localstorage) { $scope.dologin = function () { //storage.setitem("loggedin" ,true); //loginsucess = storage.getitem("loggedin"); if(loggedin == false) { //console.log(loginsucess); if ($scope.userform.$valid) { loginservice.login($scope.user.email, $scope.user.password); } storage.setitem("loggedin", true); } } }); i tried put check condition routes , not able home page after valid credentials .
validationapp.config( function($routeprovider) { $routeprovider .when('/', { templateurl: 'main.html', controller: 'maincontroller' }) .when('/home', { templateurl: 'home.html', resolve:{ "check":function($location){ if(storage.getitem(loggedin) == true) { alert(loggedin); $location.path("/home"); } else { $location.path("/main"); } } }, controller: 'maincontroller' }) .otherwise({ redirectto: '/' }); }); validationapp.service('loginservice',function($location) { this.login = function(username, password){ console.log(username,password); if(username == "ank@gmail.com" && password=="1234") { //alert('thank submitting form'); $location.path("/home"); //console.log(storage.getitem("loggedin")); } else { //alert("invalid username , password"); $location.path("/main"); } } });
please see working example: http://plnkr.co/edit/46o0znc5hfde4cyxsm5h?p=preview
stored data in cookies in login function follows,
$cookies.userinfo = { 'id': 1, 'name': 'pqr' }; and on logout remove data -
delete $cookies.userinfo; then check 'angular.isdefined($cookies.userinfo)' (userinfo cookie name given @ time of storing data in it) if find redirect page want see after login. i.e
app.run(function ($cookies) { $rootscope.$on("$routechangestart", function () { if (angular.isdefined($cookies.userinfo)) { $location.path("/pathname"); } }); });
Comments
Post a Comment