Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
AngualrJS Module to help in Web Application authentication
app = angular.module 'AppAuth', []
app.factory 'AuthService', ['$http', 'Session', 'AuthToken', ($http, Session, AuthToken) ->
login: (username, password) ->
$'api/v1/users/login/', {
username: username
password: password
}).then (response) ->
AuthToken.set( if == 'SUCCESS'
Session.set "currentUser", JSON.stringify
isGuest: ->
AuthToken.get() is null
currentUser: ->
JSON.parse(Session.get "currentUser")
logout: ->
Session.clear "currentUser"
app.factory 'AuthToken', ['$window', ($window) ->
authStorage = {
get: ->
set: (value) ->
$window.localStorage.setItem("sc_api_key", value)
clear: ->
app.factory 'Session', ['$window', ($window) ->
sStorage = {
get: (key) ->
$window.sessionStorage.getItem "__#{key}"
set: (key, value) ->
$window.sessionStorage.setItem "__#{key}", value
clear: (key) ->
$window.sessionStorage.removeItem "__#{key}"
app.config ['$routeProvider', ($routeProvider) ->
$routeProvider.when '/', {
templateUrl: 'partials/home.html'
access: 'guest'
.when '/dashboard', {
templateUrl: 'partials/dash.html'
controller: 'DashCtrl'
access: 'authorized'
.otherwise({ redirectTo: '/' });
] ['$rootScope', 'AuthService', ($rootScope, AuthService)->
$rootScope.$on '$routeChangeStart', (event, next, current) ->
if AuthService.isGuest() and next.access is "authorized"
$rootScope.$broadcast "not-authenticated"
$rootScope.$on "not-authenticated", ->
# Perform an action here, either redirect to login route or show a
# login modal
app.factory "AuthInterceptor", ['$q', '$injector', 'uiBlock', ($q, $injector, uiBlock) ->
#This will be called on every outgoing http request
request: (config)->
AuthToken = $injector.get("AuthToken")
token = AuthToken.get()
config.headers = config?.headers || {}
if token? and config.url.match(new RegExp('api/v1/')) then config.headers.CUSTOM_HTTP_HEADER = token
config || $q.when(config)
# This will be called on every incoming response that has en error status code
responseError: (response) ->
matchesAuthenticatePath = response.config && response.config.url.match(new RegExp('api/v1/users/login/'))
if not matchesAuthenticatePath
401: "not-authenticated",
}[response.status], response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.