Skip to content

Instantly share code, notes, and snippets.

@excavador
Created April 4, 2013 13:43
Show Gist options
  • Save excavador/5310430 to your computer and use it in GitHub Desktop.
Save excavador/5310430 to your computer and use it in GitHub Desktop.
case class Callback(settings: Settings) extends RestHelper {
private def exchange(request : Req)(code : String): Option[Token] = {
val client = new DefaultHttpClient
val request = new HttpPost(entryURL)
val params = List(
("code", code),
("client_id", settings.clientId),
("client_secret", settings.clientSecret),
("redirectUri", settings.redirectUri),
("grantType", "authorization_code")).
map(p => new BasicNameValuePair(p._1, p._2))
request.setEntity(new UrlEncodedFormEntity(params.asInstanceOf[java.util.List[NameValuePair]]))
val response = client.execute(request)
def toString(entity : HttpEntity) : String = {
val stream = entity.getContent
val content = io.Source.fromInputStream(stream).getLines.mkString
stream.close
content
}
case class TokenParser(access_token : String,
refresh_token : Option[String],
expires_in : Integer,
token_type : String) {
def toToken : Option[Token] = token_type match {
case "Bearer" => Some(Token(
accessToken = access_token,
refreshToken = refresh_token,
expiresIn = expires_in,
tokenType = TokenType.Bearer))
case _ => None
}
}
Option(response.getEntity).map{toString(_)}.map{parse(_)}.map{_.extract[TokenParser]}.flatMap(_.toToken)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment