Created
January 20, 2016 21:17
-
-
Save citylims/21ee20a42c200ba1d4a6 to your computer and use it in GitHub Desktop.
This file contains 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
'use strict'; | |
//auth routes with ui.router, and middleware auth headers for http client; | |
var app = angular | |
.module('clientApp', [ | |
'ui.router', | |
'angular-storage', | |
]); | |
app.config(function($stateProvider, $urlRouterProvider, $httpProvider) { | |
$stateProvider | |
.state('app', { | |
url: '/', | |
abstract: true, | |
templateUrl: 'views/menu.html', | |
controller: 'MainCtrl', | |
controllerAs: 'main', | |
}) | |
.state('app.landing', { | |
url: 'landing', | |
templateUrl: 'views/landing.html', | |
controller: 'LandingCtrl', | |
controllerAs: 'vm', | |
data: { | |
isPublic: true | |
} | |
}) | |
.state('home', { | |
parent: 'app', | |
url: 'home', | |
templateUrl: 'views/home.html', | |
controller: 'HomeCtrl', | |
controllerAs: 'vm', | |
data: { | |
isPublic: false | |
} | |
}) | |
$urlRouterProvider.otherwise('landing'); | |
$httpProvider.interceptors.push('httpRequestInterceptor'); | |
} | |
app.service('httpRequestInterceptor', function(store, $rootScope) { | |
var service = this; | |
var authUser = store.get('user'); | |
//auth user for api requests | |
service.request = function(config) { | |
config.headers.accept = 'foobar; version=1'; | |
config.headers['Content-Type'] = 'application/json'; | |
if (authUser) { | |
config.headers.authorization = 'Token token=' + authUser.token; | |
} | |
return config; | |
}; | |
service.responseError = function(response) { | |
if (response.status === 401) { | |
//emit event for unathorized request | |
$rootScope.$broadcast('unauthorized'); | |
} | |
return response; | |
}; | |
}); | |
app.run(function($rootScope, UserService) { | |
//auth for routes | |
$rootScope.$on('$stateChangeStart', function(event, toState) { | |
var authUser = UserService.getCurrentUser(); | |
var access = toState.data.isPublic; | |
if (authUser || access) { | |
return; | |
} else { | |
event.preventDefault(); | |
$state.go(app.landing); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment