Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tutorial App part 5 - User factory
.factory('User', ['$http', '$q', '$rootScope', 'storage', 'config', function($http, $q, $rootScope, storage, config) {
//Endpoints Variables.
var loginEndpoint = 'api/user/login',
logoutEndpoint = 'api/user/logout',
registerEndpoint = 'api/user/register',
sessionTokenEndpoint = 'services/session/token';
return {
/*
* Get services session token.
*/
getSessionToken: function() {
var defer = $q.defer();
$http({
method : 'GET',
url : config.serviceBaseUrl + sessionTokenEndpoint,
dataType : 'text',
})
.success(function(data, status, headers, config) {
defer.resolve(data);
})
.error(function(data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
},
/*
* Login User with username and password.
*/
login: function(username, password, token) {
var defer = $q.defer();
$http({
method : 'POST',
url : config.serviceBaseUrl + loginEndpoint,
dataType : 'json',
data: {
username: username,
password: password
},
headers: {
'X-CSRF-Token': token,
},
})
.success(function(data, status, headers, config) {
defer.resolve(data);
})
.error(function(data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
},
/*
* Logout User.
*/
logout: function(token) {
var defer = $q.defer();
$http({
method : 'POST',
url : config.serviceBaseUrl + logoutEndpoint,
dataType : 'json',
headers: {
'X-CSRF-Token': token,
},
})
.success(function(data, status, headers, config) {
defer.resolve(data);
})
.error(function(data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
},
/*
* Register new User.
*/
register: function(data) {
var defer = $q.defer();
$http({
method : 'POST',
url : config.serviceBaseUrl + registerEndpoint,
dataType : 'json',
data: {
name: data.username,
mail: data.email,
pass: data.password,
status: 1,
},
})
.success(function(data, status, headers, config) {
defer.resolve(data);
})
.error(function(data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
},
/*
* Save user credentials.
*/
setUserData: function(user, token) {
$rootScope.userData = user;
$rootScope.token = token;
storage.set(config.localStoragePrefix + 'token', token);
storage.set(config.localStoragePrefix + 'user', user);
},
/*
* Remove user credentials.
*/
removeUserData: function() {
$rootScope.userData = {};
$rootScope.token = false;
storage.remove(config.localStoragePrefix + 'token');
storage.remove(config.localStoragePrefix + 'user');
}
}
}])
@clivesj

This comment has been minimized.

Copy link

clivesj commented Aug 2, 2015

I get an authentication error on factory User.logout:
POST http://example.com/api/user/logout 406 (Not Acceptable : User is not logged in.)
Apparently the POST is done anonymously.
Session authentication is set to ON at the backend.

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.