Created
December 5, 2014 01:34
-
-
Save danethurber/57dac260b21ec753bcf3 to your computer and use it in GitHub Desktop.
Client Side Auth Example
This file contains hidden or 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
(function(){ | |
'use strict'; | |
angular.module('welbe-auth', ['ui.router']); | |
angular.module('welbe-auth').config([ | |
'$httpProvider', | |
'$stateProvider', | |
'$urlRouterProvider', | |
'authProvider', | |
'RequireAuthResolve', | |
function($httpProvider, $stateProvider, $urlRouterProvider, authProvider, RequireAuthResolve){ | |
authProvider.configure({ loginUrl: '/sessions' }); | |
$httpProvider.interceptors.push('authInterceptor'); | |
// OMG - this is such a horrible idea - replace with JST!! | |
var commentToString = function(str) { | |
return str.toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; | |
}; | |
$urlRouterProvider.otherwise('/'); | |
$stateProvider | |
.state('authRequired', { | |
abstract: true, | |
template: '<ui-view/>', | |
resolve: { | |
auth: RequireAuthResolve | |
} | |
}) | |
.state('index', { | |
url: '/', | |
template: commentToString(function () {/* | |
<div> | |
<p> | |
<a ui-sref="login">login</a> | |
</p> | |
</div> | |
*/}) | |
}) | |
.state('login', { | |
url: '/login', | |
template: commentToString(function () {/* | |
<div> | |
<form ng-submit="authorize(session)"> | |
<input type="text" name="email" placeholder="email" ng-model="session.email" /> | |
<input type="password" name="password" placeholder="password" ng-model="session.password"/> | |
<input type="submit" /> | |
</form> | |
</div> | |
*/}), | |
controller: ['$scope', 'auth', function($scope, auth) { | |
angular.extend($scope, { authorize: auth.authorize }); | |
$scope.session = { email: '', password: '' }; | |
}] | |
}) | |
// .state('authenticated', { | |
// abstract: true, | |
// template: '<ui-view></ui-view>' | |
// }) | |
.state('profile', { | |
url: '/profile', | |
parent: 'authRequired', | |
template: commentToString(function () {/* | |
<div> | |
<p>Logged in as <span ng-bind="user.name"></span></p> | |
<p><a ui-sref="logout">logout</a></p> | |
</div> | |
*/}), | |
controller: ['$scope', 'user', function($scope, user) { | |
$scope.user = user; | |
}], | |
resolve: { | |
user: ['$q', '$http', function($q, $http){ | |
var deferred = $q.defer(); | |
$http.get('/api/users/current') | |
.then(function(res){ | |
deferred.resolve(res.data.user); | |
}) | |
.catch(deferred.reject); | |
return deferred.promise; | |
}] | |
} | |
}) | |
.state('logout', { | |
url: '/logout', | |
controller: ['auth', '$state', function(auth, $state) { | |
auth.logout(); | |
}] | |
}); | |
} | |
]); | |
angular.module('welbe-auth').run([ | |
'$rootScope', | |
'$state', | |
function($rootScope, $state){ | |
$rootScope.$on('auth:authorized', function(token){ | |
$state.go('profile'); | |
}); | |
$rootScope.$on('auth:loggedOut', function(token){ | |
$state.go('index'); | |
}); | |
$rootScope.$on('$stateChangeStart', function(evt, toState, toParams, fromState, fromParams){ | |
}); | |
$rootScope.$on('$stateChangeSuccess', function(evt, to, toParams, from, fromParams){ | |
}); | |
$rootScope.$on('$stateChangeError', function(evt, toState, toParams, fromState, fromParams, error){ | |
alert('not authenticated'); | |
$state.go('logout'); | |
}); | |
} | |
]); | |
angular.module('welbe-auth').provider('auth', function() { | |
var tokenName = 'access_token', | |
config = { | |
loginUrl: null | |
}; | |
var getToken = function() { | |
return localStorage.getItem(tokenName); | |
}; | |
var setToken = function(newToken) { | |
localStorage.setItem(tokenName, newToken); | |
}; | |
var clearToken = function(newToken) { | |
localStorage.removeItem(tokenName); | |
}; | |
this.configure = function(options) { | |
angular.extend(config, options); | |
}; | |
this.$get = [ | |
'$window', | |
'$state', | |
'$http', | |
'$rootScope', | |
'$q', | |
function($window, $state, $http, $rootScope, $q) { | |
return { | |
authorize: function(data) { | |
var req = $http.post(config.loginUrl, { session: data }); | |
req.then(function(res){ | |
setToken(res.data.auth_token); | |
$rootScope.$broadcast('auth:authorized'); | |
return res.data.auth_token; | |
}); | |
return req; | |
}, | |
getToken: getToken, | |
logout: function() { | |
var deferred = $q.defer(); | |
clearToken(); | |
$rootScope.$broadcast('auth:loggedOut'); | |
deferred.resolve(); | |
return deferred.promise; | |
} | |
}; | |
} | |
]; | |
return this; | |
}); | |
angular.module('welbe-auth').factory('authInterceptor', [ | |
'$q', | |
function($q){ | |
var getAuthToken = function() { | |
return localStorage.getItem('access_token'); | |
}; | |
return { | |
responseError: function(rejection) { | |
if (rejection.status === 401) | |
console.log('request unauthenticated'); | |
if (rejection.status === 403) | |
console.log('request unauthorized'); | |
return $q.reject(rejection); | |
}, | |
request: function($config) { | |
if (getAuthToken()) | |
$config.headers['X-Auth-Token'] = getAuthToken(); | |
return $config; | |
} | |
}; | |
} | |
]); | |
angular.module('welbe-auth').constant('RequireAuthResolve', [ | |
'$q', | |
'auth', | |
function($q, auth){ | |
var deferred = $q.defer(); | |
if (auth.getToken()) | |
deferred.resolve(); | |
else | |
deferred.reject(); | |
return deferred.promise; | |
} | |
]); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment