Updated: code in JavaScript
I took the authentication (session) service from angular-app, and made significant modifications to it:
angular.module('auth', [])
.factory('session', ['$location', '$http', '$q', ($location, $http, $q) ->
service =
requestCurrentUser: ->
if service.isAuthenticated()
$q.when service.currentUser
else
$http.get('/user').then (response) ->
console.log(response.data)
service.currentUser = response.data
service.currentUser
currentUser: null
isAuthenticated: ->
not service.currentUser?
service
])
This is how the app looks like:
BookReader = angular.module('BookReader', ['ngRoute', 'home', 'main', 'books', 'auth'])
BookReader
.config(['$routeProvider', '$httpProvider', '$locationProvider', ($routeProvider, $httpProvider, $locationProvider) ->
$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', (session) ->
session.requestCurrentUser()
])
When the application starts, the currentUser is requested. Then, we have the Controllers:
angular.module('main', ['ngCookies'])
.controller('MainCtrl', ['$scope', '$http', '$cookies', '$location', 'session', '$log',
($scope, $http, $cookies, $location, session, $log) ->
$log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
$location.path '/home' if session.isAuthenticated()
])
angular.module('home', ['ngCookies'])
.controller('HomeCtrl', ['$scope', '$http', '$cookies', 'session', '$location', '$log'
($scope, $http, $cookies, session, $location, $log) ->
$log.info "currentUser: " + session.currentUser + " ; isAuth: " + session.isAuthenticated()
$location.path '/' unless session.isAuthenticated()
])
The issue is that isAuthenticated()
always returns false
, even when currentUser is not null. When logged in, $log.info
shows
currentUser: [object Object] ; isAuth: false
, not only on initial load, but during navigation as well. When logged out, it shows currentUser: null ; isAuth: false
. It seems that currentUser
is always null within the service. How can I properly define it to be able to change its value?