我如何制作我的Ionic App以防止在退出app后每次登录或返回后台而无需注销? 它是我的源代码:
login.js
angular.module('starter.controllers')
.controller('LoginCtrl', ['$scope', '$rootScope', '$location', '$localStorage', '$q', '$http', '$window', '$state', 'AuthFac tory', 'SessionFactory',
function($scope, $rootScope, $location, $localStorage, $q, $http, $window, $cordovaSQLite, $state, AuthFactory, SessionFactory) {
$scope.login = {
email: null,
password: null
};
$scope.login = function() {
$rootScope.showLoading("Authenticating..");
var email = $scope.login.email,
password = $scope.login.password;
if (email !== undefined && password !== undefined) {
AuthFactory.login(email, password).success(function(data, status, headers, config) {
if (data.success === false) {
$rootScope.hideLoading();
$rootScope.toast('Invalid Credentials');
} else {
SessionFactory.isLogged = true;
SessionFactory.user = data.data.username;
SessionFactory.userRole = data.data.name;
$localStorage.id = data.data.id;
$localStorage.token = data.data.token;
$window.sessionStorage.token = data.data.token;
console.log($window.sessionStorage.token);
$localStorage.user = data.data.username; // to fetch the user details on refresh
console.log($localStorage.user);
$localStorage.userRole = data.data.name; // to fetch the user details on refresh
console.log($localStorage.userRole);
} //end else data.success
}).error(function(data, status, headers, config) {
if (status === 500) {
$rootScope.hideLoading();
$rootScope.toast('Invalid Email');
}
});
}
};
}
]);
authfactory.js
angular.module('starter.factories')
.factory('SessionFactory', function($window, $localStorage) {
var auth = {
isLogged: false,
check: function() {
if ($localStorage.token && $localStorage.user ) {
this.isLogged = true;
} else {
this.isLogged = false;
delete this.user;
}
}
}
return auth;
})
.factory('AuthFactory', function($window, $location, $http, SessionFactory, $localStorage) {
return {
login: function(email, password) {
return $http.post('url', {
email : email,
password: password
});
},
logout: function() {
if (SessionFactory.isLogged) {
SessionFactory.isLogged = false;
delete SessionFactory.user;
delete SessionFactory.userRole;
delete $localStorage.token;
delete $localStorage.user ;
delete $window.sessionStorage.userRole;
$location.path("/login");
}
}
}
})
.factory('TokenInterceptor', function($q, $window, $localStorage) {
return {
request: function(config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers['X-Access-Token'] = $localStorage.token;
config.headers['X-Key'] = $localStorage.user;
config.headers['Content-Type'] = "application/json";
}
return config || $q.when(config);
},
response: function(response) {
return response || $q.when(response);
}
};
})
app.js
angular.module('starter.controllers', []);
angular.module('starter.services', []);
angular.module('starter.factories', []);
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'starter.factories', 'ngCordova', 'ngRoute'])
.run(function($ionicPlatform, $rootScope, $ionicLoading, $state, $location, $q, $http, $timeout, $localStorage, $window, SessionFactory) {
$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 && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
$ionicPlatform.registerBackButtonAction(function(event) {
if ($state.current.name == "tab.dashboard") {
navigator.app.exitApp();
console.log('1');
} else {
navigator.app.backHistory();
console.log('2');
}
}, 100);
if (window.cordova) {
});
// when the page refreshes, check if the user is already logged in
SessionFactory.check(); $rootScope.showLoading = function(msg) {
$ionicLoading.show({
template: msg || 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
$timeout(function() {
$rootScope.hideLoading();
}, 2999);
}
$rootScope.hideLoading = function() {
$ionicLoading.hide();
};
$rootScope.toast = function(msg) {
$rootScope.showLoading(msg);
$timeout(function() {
$rootScope.hideLoading();
}, 2999);
};
$ionicPlatform.on('resume', function() {
$rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
if ((nextRoute.access && nextRoute.access.requiredLogin) && !SessionFactory.isLogged) {
$location.path("/login");
} else {
// check if user object exists else fetch it. This is incase of a page refresh
if (!SessionFactory.user) SessionFactory.user = $localStorage.user;
if (!SessionFactory.userRole) SessionFactory.userRole = $localStorage.userRole;
}
console.log('true');
});
$rootScope.$on('$routeChangeSuccess', function(event, nextRoute, currentRoute) {
$rootScope.showMenu = SessionFactory.isLogged;
$rootScope.role = SessionFactory.userRole;
// if the user is already logged in, take him to the home page
if (SessionFactory.isLogged == true && $location.path() == '/login') {
$location.path('/tab/price');
}
});
console.log(SessionFactory.isLogged);
$rootScope.$broadcast('onResume');
});
$ionicPlatform.on('pause', function() {
$rootScope.$broadcast('onPause');
console.log('pause');
});
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl',
access: {
requiredLogin: false
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
的login.html
<ion-view view-title="Ionic App">
<ion-content>
<ion-list>
<form name="loginForm">
<div class="list">
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="login.email" required>
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="login.password" required>
</label>
<button class="button button-block button-assertive" ng-click="login()" ng-disabled="loginForm.$invalid">
<b>Login</b>
</button>
</div>
</form>
</ion-list>
</ion-content>
</ion-view>
我希望有人能帮我解决这个问题
答案 0 :(得分:2)
简单且推荐的解决方案:将用户凭据存储在localStorage中并执行自动登录。在我看到您的代码时,您已经在localStorage中存储了一些用户详细信息。您可以在控制器加载时检查localStorage中是否存在这些详细信息并直接调用您的登录方法。
这样的事情:
function($scope, $rootScope, $location, $localStorage, $q, $http, $window, $cordovaSQLite, $state, AuthFactory, SessionFactory) {
$scope.login = {
email: null,
password: null
};
$scope.isLoggedIn = false;
$scope.login = function() {
// on login set a flag to mark the user as logged in
};
if (!$scope.isLoggedIn) {
if ($localStorage.userName !== undefined and $localStorage.password !== undefined) {
$scope.login();
}
}
]);
或者,如果您正在进行一些登录令牌驱动的身份验证,您还可以存储该令牌并使用它在下次与服务器通信。
不要忘记使用加密(y)
答案 1 :(得分:0)
1)。在$ urlRouterProvider.otherwise('')中,设置应用程序的仪表板或主页面的URL,以便在登录后发送用户。让我们假设$ urlRouterProvider.otherwise('/ dashboard')。
2)。在仪表板的控制器中,注入检查用户身份验证的服务,如果未经过身份验证,则将用户发送到登录。
答案 2 :(得分:0)
可以通过在Ionic中使用本地存储
首次登录时在本地存储中设置一些凭据
window.localStorage.setItem("username", "rahul");
window.localStorage.setItem("password", "123");
下次在.run()方法中打开应用时,请检查本地存储中的凭据。
var localval = window.localStorage.getItem('username');
var localval1 = window.localStorage.getItem('password');
console.log(localval);
if(localval != null && localval1 != null)
{
$state.go('app.home');
}
从应用程序注销时清除应用程序的本地存储
window.localStorage.removeItem("username", "rahul");
window.localStorage.removeItem("password", "123");