Skip to content

Instantly share code, notes, and snippets.

@citylims
Created January 20, 2016 21:17
Show Gist options
  • Save citylims/21ee20a42c200ba1d4a6 to your computer and use it in GitHub Desktop.
Save citylims/21ee20a42c200ba1d4a6 to your computer and use it in GitHub Desktop.
'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