Skip to content

Instantly share code, notes, and snippets.

@gabrielmiller
Last active December 28, 2015 17:49
Show Gist options
  • Save gabrielmiller/7538755 to your computer and use it in GitHub Desktop.
Save gabrielmiller/7538755 to your computer and use it in GitHub Desktop.
angular service
// ----------------
// app.js
// ----------------
var myApp = angular.module('myApp', ['ngRoute','myControllers','myServices']);
myApp.config(['$routeProvider',
function($routeProvider, authentication) {
$routeProvider.when('/', {
authentication: false,
templateUrl: 'partials/about.html',
controller: 'user'
}).
when('/signup', {
authentication: false,
templateUrl: 'partials/signup.html',
controller: 'user'
}).
when('/test', {
authentication: true, /* I'd like to divert the user upon hitting this unauthed */
templateUrl: 'partials/signup.html',
controller: 'user'
}).
otherwise({
redirectTo: '/'
}).
run($scope.$on("$routeChangeStart", function(event, next, current){
// ^^ $scope is undefined here so the page explodes
var authRequired = $route.current && $route.current.$route && $route.current.$route.authentication;
if (authRequired && authentication.loggedin === false){
console.log("Auth required for the requested URL.");
// reroute the user to /login?redir=url in next
}
}));
}
]);
// ----------------
// services.js
// ----------------
var myServices = angular.module('myServices', []);
/* Authentication Service */
myServices.service('authentication', function($scope){
$scope.loggedin = false;
$scope.login = function(){
$scope.loggedin = true;
}
$scope.logout = function(){
$scope.loggedin = false;
}
$scope.isAuthenticated = function(){
return $scope.loggedin;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment