1
0
mirror of https://github.com/Foltik/Shimapan synced 2024-09-21 19:28:40 -04:00
shimapan/public/js/services/AuthSvc.js

80 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-10-11 10:15:19 -04:00
angular.module('AuthSvc', []).service('AuthService', ['$http', '$window', function($http, $window) {
function decodeToken(token) {
if (token) {
var payload = token.split('.')[1];
payload = $window.atob(payload);
payload = JSON.parse(payload);
return payload;
} else {
return {};
}
}
function saveToken(token) {
$window.localStorage['shimapan-token'] = token;
}
function getToken() {
return $window.localStorage['shimapan-token'];
}
2017-10-11 14:02:27 -04:00
this.getAuthHeader = function() {
return 'Bearer ' + getToken();
};
2017-10-11 10:15:19 -04:00
this.login = function(user) {
return $http({
method: 'POST',
url: '/api/auth/login',
2017-10-11 13:11:57 -04:00
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
2017-10-11 10:15:19 -04:00
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: user
}).then(function(res) {
saveToken(res.data.token);
$window.location.href = '/home';
2017-10-11 10:15:19 -04:00
})
};
this.logout = function() {
$window.localStorage.removeItem('shimapan-token');
$window.location.href = '/';
2017-10-11 10:15:19 -04:00
};
this.isLoggedIn = function() {
var payload = decodeToken(getToken());
return payload.exp > Date.now() / 1000;
};
this.register = function(user) {
return $http({
method: 'POST',
url: '/api/auth/register',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: user
}).then(function(res) {
saveToken(res.data.token);
$window.location.href = '/home';
2017-10-11 10:15:19 -04:00
});
};
this.currentUser = function() {
var payload = decodeToken(getToken());
return payload.username;
};
2017-10-14 15:16:58 -04:00
this.currentScope = function() {
var payload = decodeToken(getToken());
return payload.scope;
}
2017-10-11 10:15:19 -04:00
}]);