Created
December 27, 2011 19:38
-
-
Save justinholmes/1524914 to your computer and use it in GitHub Desktop.
Play2.0 Facebook 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
object Application extends Controller { | |
val FBAppId = "AppIdGoesHere" | |
val FBAppSecret = "FBAppSecretGoesHere" | |
def fbLogin = Action {Redirect("https://www.facebook.com/dialog/oauth?scope=user_birthday,email,user_about_me,user_location,offline_access,publish_stream,user_education_history,user_checkins" + | |
"&client_id="+FBAppId+"&redirect_uri="+URLEncoder.encode("http://domainname.com/fbLogin/code","UTF-8"))} | |
def fbLoginCode(code:String) = Action{response => | |
val ws = WS.url("https://graph.facebook.com/oauth/access_token?client_id="+FBAppId+"&redirect_uri" + | |
"="+URLEncoder.encode("http://domainname.com/fbLogin/code","UTF-8")+"&client_secret="+FBAppSecret+"&code="+code).get().value | |
val accessToken = (ws.get.body.split("=")) | |
try{ | |
val facebookClient = new DefaultFacebookClient(accessToken(1)); | |
val user = facebookClient.fetchObject("me", classOf[com.restfb.types.User]); | |
val email = models.User.find("email", user.getEmail()) | |
email match { | |
case Some(email) =>{ | |
Redirect("/").withSession("email" -> email.email) | |
} | |
case None => { | |
val newUser = new models.User | |
try{ | |
newUser.email = user.getEmail() | |
newUser.name = user.getFirstName() + " " + user.getLastName() | |
newUser.location = user.getLocation().getName() | |
newUser.dateOfBirth = user.getBirthdayAsDate() | |
newUser.facebookId = user.getId() | |
newUser.gender = user.getGender() | |
models.User.save(newUser) | |
}catch{ | |
case (e) => println(e.printStackTrace()) | |
} | |
Redirect("/").withSession("email" -> newUser.email) | |
} | |
} | |
}catch { | |
case (e) => Redirect(routes.Application.index).flashing( | |
"error" -> "An error occurred whilst trying to authenticate using Facebook please try again" | |
) | |
} | |
} |
Author
justinholmes
commented
Apr 24, 2012
via email
I'm glad it was of some use, it was designed for a site which has offline
access and thus didn't have an expires.
…Sent from my Galaxy Nexus
On Apr 24, 2012 2:48 AM, "David Bochenski" < ***@***.***> wrote:
Great gist - just what I was looking for.
Had to make one change, on line 14 needed to split the accessToken again
as on & as facebook returned &expires=[number] in addition to the
accessToken.
Thanks!
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/1524914
That makes sense - just thought I'd mention it incase someone else stumbles at that hurdle.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment