Created
January 5, 2014 06:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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'); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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