Skip to content

Instantly share code, notes, and snippets.

@justinholmes
Created December 27, 2011 19:38
Show Gist options
  • Save justinholmes/1524914 to your computer and use it in GitHub Desktop.
Save justinholmes/1524914 to your computer and use it in GitHub Desktop.
Play2.0 Facebook Login
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"
)
}
}
@Bochenski
Copy link

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