Skip to content

Instantly share code, notes, and snippets.

@sebastianhaas
Last active September 29, 2015 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastianhaas/2ffe12f0fddadb3de9f6 to your computer and use it in GitHub Desktop.
Save sebastianhaas/2ffe12f0fddadb3de9f6 to your computer and use it in GitHub Desktop.
LoopBack + AngularJS authentication solution
(function() {
'use strict';
angular
.module('app.auth')
.constant('authEvents', {
LOGIN_SUCCESS: 'auth_login_success',
LOGIN_FAILED: 'auth_login_failed',
LOGOUT_SUCCESS: 'auth_logout_success',
LOGOUT_FAILED: 'auth_logout_failed',
SESSION_TIMEOUT: 'auth_session_timeout',
NOT_AUTHENTICATED: 'auth_not_authenticated',
NOT_AUTHORIZED: 'auth_not_authorized'
});
})();
(function() {
'use strict';
angular
.module('app.auth')
.factory('authService', authService);
authService.$inject = ['User', 'authEvents', '$rootScope'];
/* @ngInject */
function authService(User, authEvents, $rootScope) {
var service = {
login: login,
logout: logout,
register: register,
isAuthenticated: isAuthenticated,
getCurrentUser: getCurrentUser
};
return service;
////////////////
function login(email, password) {
return User
.login({email: email, password: password})
.$promise
.then(function(response) {
$rootScope.$broadcast(authEvents.LOGIN_SUCCESS);
}, function() {
$rootScope.$broadcast(authEvents.LOGIN_FAILED);
});
}
function logout() {
return User
.logout()
.$promise
.then(function(response) {
$rootScope.$broadcast(authEvents.LOGOUT_SUCCESS);
}, function() {
$rootScope.$broadcast(authEvents.LOGOUT_FAILED);
});
}
function register(email, password) {
return User
.create({
email: email,
password: password
})
.$promise;
}
function isAuthenticated() {
return User.isAuthenticated();
}
function getCurrentUser() {
return User.getCurrent();
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment