Quantcast
Channel: API method to validate Facebook OAuth token - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 5

Answer by Michele d'Amico for API method to validate Facebook OAuth token

$
0
0

Is better to write two private (or protected if you want override in future) methods to get a valid auth token and a valid user.

@ApiMethod(name = "getUserData", path = "get_user_data")public Bean getUserData(@Named("token") String token) {    Bean response = new Bean();    FacebookAuthToken auth;    User user;    try {        auth = getAuth(token);    } catch (IllegalArgumentException e){        response.setData("Token invalid, please log in");        return response;    } catch (Exception e) {        response.setData("Exception occurred");        return response;    }    user = getUser(auth);    response.setData(user.getPersonalisedWelcome);    return response;}private FacebookAuthToken getAuth(String token) raise Exception{    FacebookAuthToken auth = ServerFacebookHelper.getAuthToken(token);    if (auth == null) {        raise IllegalArgumentException("No valid token");    }    return auth;}private User getUser(FacebookAuthToken auth) {    User user = getUserFromDatabase(auth);    if (user == null) {        user = registerUserInDatabase(auth);    }    return user;}

Maybe the next step could be wrap FacebookAuthToken with a factory that give to you a method to check if is valid, an error message and facebook's token.

Anyway, consider to make a class instead a method. I didn't it because I can seems overkilled here, but if your error or user handling increase is better to switch in a class.

[Edit]

I took another review to my answer and I noted that is already simple to separate error handling and real duty:

protected String welcome(String token) {    return getUser(getAuth(token)).getPersonalisedWelcome}

and finally your method become a neat (as say Uncle Bob Exception handling is a huge duty yet):

@ApiMethod(name = "getUserData", path = "get_user_data")public Bean getUserData(@Named("token") String token) {    Bean response = new Bean();    try {        response.setData(welcome(token));    } catch (IllegalArgumentException e){        response.setData("Token invalid, please log in");    } catch (Exception e) {        response.setData("Exception occurred");    }    return response;}

Now you can use a decorator to implement the same error handling for all your beans.

One more thing : I used to catch and raise raw Exception just because you didn't say what kind of exception getAuthToken() can raise but never do that and catch exactly you know can be raised and you know how to handle it at this level.


Viewing all articles
Browse latest Browse all 5

Trending Articles