Skip to content

@zishe /angular_session.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
// 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('/');
}
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.