Last active
April 23, 2019 16:37
-
-
Save kudchikarsk/4145277e8d81aedca5b69782f9fe1713 to your computer and use it in GitHub Desktop.
AngularJs service to manage login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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