저는 신생아입니다. 사용자 인증 여부를 확인할 수있는 AuthenticationService를 만드는 방법을 알고 싶습니다. 내가 볼 수있게하기 위해 사용자를 인증하기를 원하는 경로가 있고 인증되지 않은 경우 로그인 페이지로 리디렉션되는 경로가 있습니다. 토큰 기반 인증에 satellizer을 사용하고 있습니다. 제안각도 인증 서비스
내가 app.js을 변경 한
angular.module('coop.controllers', [])
.controller('FrontPageController', function($scope, ArticleService, $state) {
ArticleService.all().then(function(data){
$scope.articles = data;
$scope.like = function(article){
article.like = article.like == 0 ? 1 : 0;
ArticleService.like(article.id, article.like)
};
})
})
.controller('ArticleController', function($scope, ArticleService, $stateParams, $ionicSlideBoxDelegate, $auth) {
ArticleService.get($stateParams.id).then(function(response) {
$scope.article = response;
$scope.commentsCount = response.comments.length;
$scope.articleText = response.text;
$scope.like = function(){
$scope.article.like = $scope.article.like == 0 ? 1 : 0;
ArticleService.like($scope.article.id, $scope.article.like)
};
$ionicSlideBoxDelegate.update();
})
})
.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
$scope.loginData = {}
$scope.loginError = false;
$scope.loginErrorText;
$scope.login = function() {
var credentials = {
email: $scope.loginData.email,
password: $scope.loginData.password
}
$auth.login(credentials).then(function(response) {
var token = JSON.stringify();
localStorage.setItem('token', response.data.token);
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('main.front');
}, function(){
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
});
}
});
업데이트 코드 :
이 내 app.js
angular.module('coop', ['ionic', 'coop.controllers', 'coop.services', 'satellizer'])
.constant('ApiEndpoint', {
url: 'http://coop.app/api'
})
.run(function($ionicPlatform, $rootScope, $auth, $state, $location) {
// Check for login status when changing page URL
$rootScope.$on('$routeChangeStart', function (event, next) {
var currentRoute = next.$$route;
if (!currentRoute || currentRoute.requiresAuth && !AuthenticationService.authenticated) {
$location.path('/auth');
}
else if (!currentRoute || !currentRoute.requiresAuth && AuthenticationService.authenticated) {
$location.path('/front');
}
});
$rootScope.logout = function() {
$auth.logout().then(function() {
// Remove the authenticated user from local storage
localStorage.removeItem('user');
// Remove the current user info from rootscope
$rootScope.currentUser = null;
$state.go('main.auth');
});
}
$rootScope.token = localStorage.getItem('token');
$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);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
// StatusBar.styleDefault();
StatusBar.show();
StatusBar.overlaysWebView(false);
StatusBar.styleLightContent();
StatusBar.backgroundColorByHexString("#2a2e34");
}
});
})
.config(function($stateProvider, $urlRouterProvider, $authProvider, ApiEndpoint) {
$authProvider.loginUrl = ApiEndpoint.url + '/authenticate';
$stateProvider
.state('main', {
url: '/main',
abstract: true,
templateUrl: 'templates/main.html',
requiresAuth: true
})
.state('main.auth', {
url: '/auth',
views: {
'content': {
templateUrl: 'templates/login.html',
controller: 'AuthController',
requiresAuth: false
}
}
})
.state('main.front', {
url: '/front',
views: {
'content': {
templateUrl: 'templates/main-front.html',
controller: 'FrontPageController',
requiresAuth: true
}
}
})
.state('main.article', {
url: '/article/{id}',
views: {
'content': {
templateUrl: 'templates/main-article.html',
controller: 'ArticleController',
requiresAuth: true
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/main/front');
});
그리고 내 컨트롤러입니다 // Check for login status when changing page URL
$rootScope.$on('$routeChangeStart', function (event, next) {
var currentRoute = next.$$route;
if (!currentRoute || currentRoute.requiresAuth && !$auth.isAuthenticated()) {
$location.path('/main/login');
}
else if (!currentRoute || !currentRoute.requiresAuth && $auth.isAuthenticated()) {
$location.path('/main/front');
}
});
그리고 사용자를 삭제하고 로컬 스토리지에서 토큰 로그 아웃 컨트롤러를 추가했습니다,하지만 난 여전히 페이지 로그인 리디렉션하고 있지 않다 :
는내 컨트롤러 :
.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
$scope.loginData = {}
$scope.loginError = false;
$scope.loginErrorText;
$scope.login = function() {
var credentials = {
email: $scope.loginData.email,
password: $scope.loginData.password
}
$auth.login(credentials).then(function(response) {
var token = JSON.stringify();
localStorage.setItem('token', response.data.token);
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('main.front');
}, function(){
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
});
}
$scope.logout = function() {
$auth.logout().then(function() {
// Remove the authenticated user from local storage
localStorage.removeItem('user');
localStorage.removeItem('token');
// Remove the current user info from rootscope
$rootScope.currentUser = null;
$state.go('main.login');
});
}
});
난 당신이 완벽 할 것이라고 제안하고 내가 좋아 한 일을 생각한다 당신이 말했다,하지만 내가 메인/프론트 페이지로 갈 때 나는 여전히 로그인 페이지로 리다이렉트되지 않고있다. – Marco
이전에 로그인하고 로그 아웃하지 않은 경우 수동으로 localstorage에서 토큰을 삭제해야 할 수도 있습니다. – marton
또한 AuthController에서 토큰을 수동으로 설정해야하는 경우 localStorage.setItem() 대신 satellizer의 $ auth.setToken()을 사용합니다. 그러나 올바르게 호출하면 $ login이 자동으로 설정합니다. – marton