Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AngualrJS Module to help in Web Application authentication (Written in Javascript)
// Generated by CoffeeScript 1.7.1
(function() {
var app = angular.module('AppAuth', [])
app.config([
'$httpProvider', function($httpProvider) {
//Intercept all Out-Going HTTP Requests
$httpProvider.interceptors.push("AuthInterceptor");
//Routes Configuration
return $routeProvider.when('/', {
templateUrl: 'partials/home.html',
access: 'guest'
}).when('/dashboard', {
templateUrl: 'partials/dash.html',
controller: 'DashCtrl',
access: 'authorized'
}).otherwise({ redirectTo: '/' });
}
]);
app.run([
'$rootScope', 'AuthService', function ($rootScope, AuthService) {
// Listen for the $routeChangeStart event
$rootScope.$on('$routeChangeStart', function (event, next, current) {
if(AuthService.isGuest() && next.access == "authorized") {
$rootScope.$broadcast("not-authenticated")
}
});
//Current User is not authenticated
$rootScope.$on("not-authenticated", function() {
// Perform an action here, either redirect to login route or show a
// Login Modal
});
}
]);
// Dedicated Service for Storing Auth Token in LocalStorage
app.factory('AuthToken', [
'$window', function($window) {
var authStorage;
authStorage = {
get: function() {
return $window.localStorage.getItem("sc_api_key");
},
set: function(value) {
return $window.localStorage.setItem("sc_api_key", value);
},
clear: function() {
return $window.localStorage.removeItem("sc_api_key");
}
};
return authStorage;
}
])
//Dedicated Service for maintaining session state
app.factory('Session', [
'$window', function($window) {
var sStorage;
sStorage = {
get: function(key) {
return $window.sessionStorage.getItem("__" + key);
},
set: function(key, value) {
return $window.sessionStorage.setItem("__" + key, value);
},
clear: function(key) {
return $window.sessionStorage.removeItem("__" + key);
}
};
return sStorage;
}
])
app.constant('AuthEvents', {
loginSuccess: "loginSuccess",
loginFailed: "loginFailed",
notAuthenticated: "notAuthenticated",
notAuthorized: "notAuthorized",
})
app.factory('AuthService', [
'$http', 'Session', 'AuthToken', function($http, Session, AuthToken) {
return {
//Login Function
login: function(username, password) {
return $http.post('api/v1/users/login/', {
username: username,
password: password
}).then(function(response) {
if (response.data._meta.status === 'SUCCESS') {
AuthToken.set(response.data.records.privateKey);
}
Session.set("currentUser", JSON.stringify(response.data.records.user));
return response.data.records.user;
});
},
// Check if Current User is not signed in
isGuest: function() {
return AuthToken.get() === null;
},
//Retrieve Current User details
currentUser: function() {
return JSON.parse(Session.get("currentUser"));
},
//Logout the Current User
logout: function() {
Session.clear("currentUser");
return AuthToken.clear();
}
};
}
]);
app.factory("AuthInterceptor", [
'$q', '$injector', function($q, $injector) {
return {
// This will be called on every outgoing http request
request: function(config) {
var AuthToken, token;
if (config.url.match(new RegExp('api/v1/'))) {
uiBlock.block('html');
}
AuthToken = $injector.get("AuthToken");
token = AuthToken.get();
config.headers = (config != null ? config.headers : void 0) || {};
if ((token != null) && config.url.match(new RegExp('api/v1/'))) {
config.headers.X_API_KEY = token;
}
return config || $q.when(config);
},
// This will be called on every incoming response that has en error status code
responseError: function(response) {
var AuthEvents, matchesAuthenticatePath;
AuthEvents = $injector.get('AuthEvents');
matchesAuthenticatePath = response.config && response.config.url.match(new RegExp('api/v1/users/login/'));
if (!matchesAuthenticatePath) {
$injector.get('$rootScope').$broadcast({
401: AuthEvents.notAuthenticated,
403: AuthEvents.notAuthorized
}[response.status], response);
}
return $q.reject(response);
}
};
}
]);
}).call(this);
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.