Redirect after user has logged in - redirect

I'm pretty new to Angular, and right now I'm just trying to get all my routes set up and working as I'd like.
Setup:
When a user navigates to certain pages (/settings for this example) the app should check if there is a user already logged in. If there is continue as usual. Otherwise the user should go to the login page (/login).
What I'd like:
After the user has successfully logged in they should go to the page they were originally trying to get to (/settings)
My question:
Is there an "Angular way" to remember where the user was trying to go to?
Relevant code:
app.js
.when('/settings', {
templateUrl: '/views/auth/settings.html',
controller: 'SettingsCtrl',
resolve: {
currentUser: function($q, $location, Auth) {
var deferred = $q.defer();
var noUser = function() {
//remember where the user was trying to go
$location.path("/login")
};
Auth.checkLogin(function() {
if (Auth.currentUser()) {
deferred.resolve(Auth.currentUser());
} else {
deferred.reject(noUser());
}
});
return deferred.promise;
}
}
})
login.js
$scope.submit = function() {
if(!$scope.logInForm.$invalid) {
Auth.login($scope.login, $scope.password, $scope.remember_me)
//go to the page the user was trying to get to
}
};
Much thanks to John Lindquist for the video which got me this far.

First off, you do not want to redirect the user to a login page.
An ideal flow in a single page web app is as follows:
A user visits a web site. The web site replies with the static assets for the
angular app at the specific route (e.g. /profile/edit).
The controller (for the given route) makes a call to an API using $http, $route, or other mechanism (e.g. to pre-fill the Edit Profile form with details from the logged in user's account via a GET to /api/v1/users/profile)
If/while the client receives a 401 from the API, show a modal to
login, and replay the API call.
The API call succeeds (in this case, the user can view a pre-filled Edit Profile form for their account.)
How can you do #3? The answer is $http Response Interceptors.
For purposes of global error handling, authentication or any kind of
synchronous or asynchronous preprocessing of received responses, it is
desirable to be able to intercept responses for http requests before
they are handed over to the application code that initiated these
requests. The response interceptors leverage the promise apis to
fulfil this need for both synchronous and asynchronous preprocessing.
http://docs.angularjs.org/api/ng.$http
Now that we know what the ideal user experience should be, how do we do it?
There is an example here: http://witoldsz.github.com/angular-http-auth/
The example is based on this article:
http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application
Good luck and happy Angularing!

Related

Meteor: Implement facebook package outside of accounts-facebook

I've got a Meteor application with a multi-phase sign-up process. The accounts are based on the accounts-password package. In the step prior to account creation, the user needs to provide some profile information.
I'd like the user to be able to launch a Facebook OAuth flow which pre-populates the profile fields with information pulled from Facebook.
This all needs to happen pre-account-creation. I want to implement this with the facebook package that backs accounts-facebook.
At the moment I've got the OAuth flow happening by calling Facebook.requestCredential, but I'm not sure how to get an OAuth access token from the credential token that comes back. I suspect I need to pass this to the server and make an API call to get back an access token.
Any pointers as to how this should work would be much appreciated.
Facebook.requestCredential(function (credentialTokenOrError) {
if (credentialTokenOrError && credentialTokenOrError instanceof Error) {
// Error...
console.log(credentialTokenOrError);
} else {
// Credential Token string
console.log(credentialTokenOrError);
// Now perhaps a Meteor.call to a server method that
// 1. Retrieves an access token
// 2. Hits the graph API to get profile information and returns it to the client
}
});
Thanks,
Chris
I was having the same trouble of converting a credentialToken to an accessToken, only with Github. I've written up a gist that has code that should work very similarly. Essentially, there are two steps:
Within your Facebook.requestCredential callback function, call OAuth._retrieveCredentialSecret(tokenOrError), the result of which is the credentialSecret. Then use Meteor.call, passing in tokenOrError and credentialSecret, to call the Meteor.method you'll set up in the next step.
code (on client):
Github.requestCredential({
loginStyle: 'popup',
requestPermissions: ['gist']
}, function(tokenOrError) {
if (tokenOrError && tokenOrError instanceof Error) {
// Throw a Meteor error
console.log('error getting the token');
return;
}
var credentialSecret = OAuth._retrieveCredentialSecret(tokenOrError);
Meteor.call('getGithubAccessToken', tokenOrError, credentialSecret, function(err, accessToken) {});
});
On the server, set up a Meteor.method that takes your credentialToken and credentialSecret and calls Facebook.retrieveCredential. This function returns a credentials object from the _pendingCredentials Mongo Collection before deleting it from the collection. The access token is credentials.serviceData.accessToken. The credentials object could potentially be persisted in the user object in the Meteor.users collection (as it is in the accounts packages) or sent back to the user.
code (on server):
Meteor.methods({
getGithubAccessToken: function(credentialToken, credentialSecret) {
var credentials = Github.retrieveCredential(credentialToken, credentialSecret);
console.log('accessToken:', credentials.serviceData.accessToken);
return credentials.serviceData.accessToken;
}
});
I'm unfamiliar with the specifics of Facebook's Graph API so after these steps, you're on your own. Good luck!

GWT: A way to cancel PlaceChangeEvent?

I'm using Activity/Place in my GWT project, if current user is not logged in, when he navigates to some Place, the user will be redirect to login page, if the user has logged in, then he will be taken to that Place. How to implement this logic efficiently?
I tried to hook PlaceChangeRequestEvent:
eventBus.addHandler(PlaceChangeRequestEvent.TYPE,new PlaceChangeRequestEvent.Handler() {
#Override
public void onPlaceChangeRequest(PlaceChangeRequestEvent event) {
Place newPlace = event.getNewPlace();
if (newPlace instanceof MyProtectedPlace && userNotLoggedIn()) {
event.goTo(new LoginPlace());
}
}
});
Unfortunately it does not work since the ongoing request for MyProtectedPlace is not cancelled.
Yes I could check this when user are about to navigation away from current place, but this will not be efficient as the check logic will scattered throughout the program.
Thanks.
You can do it a little bit differently I think. Let's say that you want a place called SecuredPlace to be accessible only after login. You have a corresponding SecuredActivity.
What you can do is, when you start your SecuredActivity, you check if your user is logged in. If not you do placeController.goTo(new LoginPlace ()).
If the user is logged in then you continue. As the start is called by the framework there is no way to skip this step which in my opinion makes it secured enough.
But you should implement your security on network calls to your backend not on places. Every time you call the backend, you check that user is authenticated and has the right credentials. If not you can intercept the callback, check that it is a 403 error and then redirect automatically to your login page. Because if your backend calls are not secured, securing your places is useless.

FacebookAuthorizeFilter endless redirect

I'm trying to add facebook login to my application. To that extent I'm using a following snippet of code:
[FacebookAuthorize]
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
And I register a filter FacebookAuthorizeFilter.
When I navigate to /Home/About what I get is an endless redirect to
/Home/About?code=AQAPoxl1J-.......
I can login using facebook if I just use OAuth provided in ASP.NET MVC4 project template.
What am I missing?
I delved into the FacebookAuthorize filter code more. The reason the Filter does not work with non-canvas applications is that inside the filter's OnAuthorization method the the method is relying on Facebook's signed_request being present in the POST requset when the user is redirected back to your application. If signed_request is never present the filter will continue to redirect:
...code omitted...
if (signedRequest == null || String.IsNullOrEmpty(userId) || String.IsNullOrEmpty(accessToken))
{
// Cannot obtain user information from signed_request, redirect to Facebook OAuth dialog.
string redirectUrl = GetRedirectUrl(request);
Uri loginUrl = client.GetLoginUrl(redirectUrl, _config.AppId, null);
filterContext.Result = CreateRedirectResult(loginUrl);
}
...code omitted..
An alternative approach may be to create a similar filter that checks for the existent of the code query string parameter. Once code is obtained you may use your application's appId and appSecret to exchange the code for an access token. Once the access token is obtained you may determine which permissions the user has granted and process appropriately.
After hours spent debugging, reflecting, source-code analyzing I came to the conclusion that FacebookAuthorizeAttribute and FacebookAuthorizeFilter can only meaningfully be used in a Facebook Canvas application.

Loose req.session when trying to get more FB privileges via everyauth

I've been doing user authentication with everyauth and Facebook and all works well. Now, I want to integrate an ability to post to Facebook. Since my app asks only for email scope when users first login, I'll need to get a larger FB scope, and am trying to follow the FB guidelines and only ask for this additional scope when I need it.
I added the following code to my everyauth configuration as per the docs:
everyauth
.facebook
.appId(conf.fb.appId)
.appSecret(conf.fb.appSecret)
//TODO add custom redirect for when authentication is not approved
.scope(function (req, res) {
console.log('Setting FB scope');
console.log('Session: ' + util.inspect(req.session));
var session = req.session;
switch (session.userPhase) {
case 'share-media':
return 'email,user_status';
default:
return 'email';
}
})
All is well when an unauthenticated user logs into the application. The problem is that when I want to "up the ante" on FB scope, which I do by setting req.session.userPhase to 'share-media', and then present a link to /auth/facebook to confirm they want to allow posting to FB. When this happens, I get an error that req.session is undefined from the above code (all of req is undefined).
I assume this is since a previously logged-in user is essentially re-authenticating, but isn't that how I would get more scope from Facebook? Am I going about this the wrong way?
Thanks!!!

Facebook API: FB.Connect.requireSession issues

I have a Facebook app that is built as an iFrame. I am using the JavaScript client API loaded via:
http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php
In my initialization code, I use the requireLogin method to ensure that the user has authorized the app. I have found this to be necessary to be able to gather the user's name, avatar, etc. for the scoreboard. Here's a representative code snippet:
FB_RequireFeatures(["Connect","Api"], function() {
FB.Facebook.init("...API_KEY_HERE...", "xd_receiver.htm");
var api = FB.Facebook.apiClient;
api.requireLogin(function() {
api.users_getInfo(
FB.Connect.get_loggedInUser(),
["name", "pic_square", "profile_url"],
function(users, ex) {
/* use the data here */
});
});
});
This causes the iframe to redirect causing the Facebook authorization screen to load within my app's iFrame. This looks junky and is somewhat confusing to the user, e.g. there are two Facebook bars, etc.
Question 1: is there anything I can do to clean this up while still implementing as an iFrame, and still using the JavaScript APIs?
According to the FB API documentation:
FB.ApiClient.requireLogin
This method is deprecated - use
FB.Connect.requireSession instead.
My experience though when I replace api.requireLogin with FB.Connect.requireSession it never gets invoked. I'd prefer the recommended way of doing it but I struggled and was not able to find a way to get it to work. I tried adding various arguments for the other two parameters as well with seemingly no effect. My expectation is that this method will load in a dialog box inside my app iFrame with a similar authorization message.
Question 2: what am I missing with getting FB.Connect.requireSession to properly prompt the user for authorization?
Finally, at the end of the game, the app prompts the user for the ability to publish their score to their stream via FB.Connect.streamPublish. Which leads me to...
Question 3: am I loading the correct features? Do I need both "Api" and "Connect"? Am I missing any others?
Here is a summary of the changes I needed to make to clean up the authorization process. It appears that iFrames must fully redirect to properly authorize. I tried using the FBConnect authorization but it was a strange experience of popup windows and FBConnect buttons.
Ultimately this game me the expected experience that I've seen with other FB apps:
FB_RequireFeatures(["Connect","Api"], function() {
var apiKey = "...",
canvasUrl = "http://apps.facebook.com/...";
function authRedirect() {
// need to break out of iFrame
window.top.location.href = "http://www.facebook.com/login.php?v=1.0&api_key="+encodeURIComponent(apiKey)+"&next="+encodeURIComponent(canvasUrl)+"&canvas=";
}
FB.Facebook.init(apiKey, "xd_receiver.htm");
FB.ensureInit(function() {
FB.Connect.ifUserConnected(
function() {
var uid = FB.Connect.get_loggedInUser();
if (!uid) {
authRedirect();
return;
}
FB.Facebook.apiClient.users_getInfo(
uid,
["name", "pic_square", "profile_url"],
function(users, ex) {
/* user the data here */
});
},
authRedirect);
});
For iFrames, the solution was ultimately to redirect to the login URL which becomes the authorization URL if they are not already logged in.
I think that FB.requireSession only works from a FB connect site outside of
Facebook. If you're using an app hosted on apps.facebook.com use the php api
call instead,
$facebook = new Facebook($appapikey, $appsecret);
$facebook->require_login();
or link to the login page.
Of these methods to login
* Using the PHP client library
* Directing users to login.php
* Including the requirelogin attribute in a link or form
* Using FBML
only the first 2 are available to iframe apps hosted on apps.facebook.com
I think requirelogin and fbml only work with fbml canvas apps.
see
http://wiki.developers.facebook.com/index.php/Authorization_and_Authentication_for_Canvas_Page_Applications_on_Facebook
Question 1: is there anything I can do
to clean this up while still
implementing as an iFrame, and still
using the JavaScript APIs?
Question 2: what am I missing with
getting FB.Connect.requireSession to
properly prompt the user for
authorization?
Please have a look at this. This article discusses correct use of require session and provides links on how to implement that. And yes, you are right, the requireLogin has been deprecated and won't help any more.
Question 3: am I loading the correct
features? Do I need both "Api" and
"Connect"? Am I missing any others?
As far as I know, you can use both API and Connect together, basically you access Facebook's API with the help of JavaScript.
For iframe apps however, there is no great help and minimum support of API with some handful functionality available. See this for more info.
This causes the iframe to redirect
causing the Facebook authorization
screen to load within my app's iFrame.
This looks junky and is somewhat
confusing to the user, e.g. there are
two Facebook bars, etc.
Finally and personally I have not seen any iframe app requiring user to add the app first. This will create the problem of two bars you mentioned as quoted above.
The link I posted at the beginning of my answer has some useful links to get you started and decide the next-steps or possibly making changes to your apps.