public
Created

  • Download Gist
angular_session.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
// app
 
var BookReader = angular.module('BookReader', ['ngRoute', 'home', 'main', 'books', 'auth']);
 
BookReader.config([
'$routeProvider', '$httpProvider', '$locationProvider', function($routeProvider, $httpProvider, $locationProvider) {
return $routeProvider.when('/', {
templateUrl: 'assets/tour.html',
controller: 'MainCtrl'
}).when('/home', {
templateUrl: 'assets/main.html',
controller: 'HomeCtrl'
}).when('/books', {
templateUrl: 'assets/books.html',
controller: 'BooksCtrl'
});
}
]).run([
'session', function(session) {
return session.requestCurrentUser();
}
]);
 
 
// session service
 
angular.module('auth', []).factory('session', [
'$location', '$http', '$q', function($location, $http, $q) {
var service;
service = {
requestCurrentUser: function() {
if (service.isAuthenticated()) {
return $q.when(service.currentUser);
} else {
return $http.get('/user').then(function(response) {
console.log(response.data);
service.currentUser = response.data;
return service.currentUser;
});
}
},
currentUser: null,
isAuthenticated: function() {
return !(service.currentUser != null);
}
};
return service;
}
]);
 
// Controllers
 
angular.module('main', ['ngCookies']).controller('MainCtrl', [
'$scope', '$http', '$cookies', '$location', 'session', '$log', function($scope, $http, $cookies, $location, session, $log) {
$log.info("currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated());
if (session.isAuthenticated()) {
return $location.path('/home');
}
}
]);
 
angular.module('home', ['ngCookies']).controller('HomeCtrl', [
'$scope', '$http', '$cookies', 'session', '$location', '$log', function($scope, $http, $cookies, session, $location, $log) {
$log.info("currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated());
if (!session.isAuthenticated()) {
return $location.path('/');
}
}
]);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.