Skip to content

Instantly share code, notes, and snippets.

@kudchikarsk kudchikarsk/oauth.js
Last active Apr 23, 2019

Embed
What would you like to do?
AngularJs service to manage login
//refer https://gist.github.com/kudchikarsk/f8ae377255f04cdc00a0fbc35287dbb5 for currentUser Service
(function (module) {
var oauth = function () {
var url = "/login";
this.setUrl = function (newUrl) {
url = newUrl;
};
this.$get = function ($http, formEncode, currentUser) {
var processToken = function (username) {
return function (response) {
currentUser.profile.username = username;
currentUser.profile.token = response.data.access_token;
currentUser.save();
return username;
}
};
var login = function (username, password) {
var configuration = {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var data = formEncode({
username: username,
password: password,
grant_type: "password"
});
return $http.post(url, data, configuration).then(processToken(username));
};
var logout = function() {
currentUser.profile.username = "";
currentUser.profile.token = "";
currentUser.remove();
};
return {
login: login,
logout: logout
};
}
};
module.config(function ($provide) {
$provide.provider("oauth", oauth);
});
}(angular.module("common")));
//FormEncode service
(function(module) {
var formEncode = function() {
return function(data) {
var pairs = [];
for (var name in data) {
pairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
return pairs.join('&').replace(/%20/g, '+');
};
};
module.factory("formEncode", formEncode);
}(angular.module("common")));
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.