Created
September 1, 2014 07:00
-
-
Save codingawayy/cebcc2da19c8c816acd0 to your computer and use it in GitHub Desktop.
Mozilla Persona - Angular directive
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
angular.module("coderful.persona", []) | |
.constant("navigator", window.navigator) | |
.provider("persona", [ | |
"navigator", function(navigator) { | |
var loginUrl; | |
var logoutUrl; | |
var getUser = angular.noop; | |
this.init = function(options) { | |
options = options || {}; | |
loginUrl = options.loginUrl; | |
logoutUrl = options.logoutUrl; | |
getUser = options.getUser; | |
}; | |
this.$get = [ | |
"$http", function($http) { | |
function verifyAssertion(assertion) { | |
$http.post(loginUrl + assertion).success(function(data) { | |
var authenticated = data.toLowerCase() === "true"; | |
if (authenticated) { | |
window.location.reload(); | |
} else { | |
alert("Your credentials could not be authenticated."); | |
} | |
}).error(function() { | |
navigator.id.logout(); | |
alert("Login error! Please try again."); | |
}); | |
} | |
function signoutUser() { | |
$http.get(logoutUrl).success(function() { | |
window.location.reload(); | |
}).error(function() { | |
alert("Logout error! The page will refresh."); | |
window.location.reload(); | |
}); | |
} | |
return { | |
watch: function() { | |
navigator.id.watch({ | |
loggedInUser: getUser(), | |
onlogin: verifyAssertion, | |
onlogout: signoutUser | |
}); | |
}, | |
login: function() { | |
if (getUser()) { | |
navigator.id.logout(); | |
} else { | |
navigator.id.request(); | |
} | |
}, | |
user: function() { | |
return getUser(); | |
} | |
}; | |
} | |
]; | |
} | |
]) | |
.directive("personaLogin", [ | |
"persona", function(persona) { | |
return { | |
restrict: "A", | |
template: "<span ng-if='user'>{{user}} | </span><a ng-click='login()' class='clickable'>{{action}}</a>", | |
link: function($scope) { | |
persona.watch(); | |
$scope.user = persona.user(); | |
$scope.action = $scope.user ? "Logout" : "Login"; | |
$scope.login = function() { | |
persona.login(); | |
} | |
} | |
}; | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment