Skip to content

Instantly share code, notes, and snippets.

@joselo
Created January 5, 2014 06:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joselo/8265250 to your computer and use it in GitHub Desktop.
Save joselo/8265250 to your computer and use it in GitHub Desktop.
How to user a resolver to check if a user is signed in
'use strict';
angular.module('instafacApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider, $httpProvider){
$routeProvider
.when('/me', {
templateUrl: 'views/user/dashboard/dashboard.html',
controller: 'DashboardCtrl',
resolve: {
resolveData: function(Resolver){
return Resolver();
}
}
})
.otherwise({
redirectTo: '/'
});
var interceptor = ['$rootScope', '$location', '$q',
function($scope, $location, $q) {
var success = function(resp) {
return resp;
},
err = function(resp) {
if (resp.status === 401) {
var d = $q.defer();
$scope.$broadcast('event:unauthorized');
return d.promise;
}
return $q.reject(resp);
};
return function(promise) {
return promise.then(success, err);
};
}
];
$httpProvider.responseInterceptors.push(interceptor);
})
.run(function($rootScope, $http, $location) {
$rootScope.$on('event:unauthorized', function(evt) {
$location.path('/login');
});
});
angular.module('myApp')
.factory('Resolver', function ($http, $q) {
return function () {
var deferred = $q.defer();
$http({
url: '/api/v1/auth/current_user',
method: 'GET'
}).then(function (response) {
deferred.resolve(response.success);
});
return deferred.promise;
};
});
module Api
module V1
class Auth::SessionsController < Devise::SessionsController
def get_current_user
if user_signed_in?
render status: 200,
json: {
success: true,
info: "Current user",
data: {
token: current_user.authentication_token,
email: current_user.email
}
}
else
render status: 401,
json: {
success: false,
info: "",
data: {}
}
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment