Created
October 7, 2013 21:41
-
-
Save ambantis/6875428 to your computer and use it in GitHub Desktop.
A function that takes a json response of access_token and user_info from Google OAuth2, validates the json, and information to Cache and the Database if json is valid.
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
trait GoogleOAuth extends AuthConstants with CacheConstants { | |
def persistPacket(rUser: Response, rToken: Response)(implicit s: Session): Future[Try[DbUser]] = future { | |
(rUser.json.as[JsObject] ++ rToken.json.as[JsObject]).validate[GoogleOAuthPacket] match { | |
case JsError(errors) => | |
Logger.error(s"failed to validate user, with errors: $errors") | |
Failure(new Throwable("didn't work")) | |
case JsSuccess(packet, _) => | |
Logger.debug(s"successfully parsed user and token: $packet") | |
Logger.debug(s"response for token request was: ${Json.prettyPrint(rToken.json)}") | |
Logger.debug(s"response for user request was: ${Json.prettyPrint(rUser.json)}") | |
val sqlCount: Try[Int] = { | |
if (DbUsers.findByUserId(packet.user.id).isEmpty) { | |
Logger.debug(s"user ${packet.user} not found, proceeding to save in database") | |
DbUsers.insertUser(packet.user) | |
} | |
else { | |
// todo:2013-09-12:ambantis:if the user already exists, check to see if userinfo has changed | |
// don't do this because it will overwrite the refresh_token | |
//Users.updateUser(packet.user) | |
Success(0) | |
} | |
} | |
sqlCount match { | |
case Failure(e) => {Logger.error(s"failed to persist user: ${e.getStackTrace}"); Failure(e) } | |
case Success(count) => | |
Logger.debug(s"successfully persisted user, proceeding to save token to cache") | |
val magicNotebook = MagicNotebook.create(packet.user.id).getOrElse(MagicNotebook.empty) | |
Cache.set(userKey(packet.user.id), packet.user) | |
Cache.set(magicNotebookKey(packet.user.id), magicNotebook) | |
Cache.set(accessTokenKey(packet.user.id), packet.accessToken, packet.expiresIn) | |
Success(packet.user) | |
} | |
} | |
} | |
} | |
case class GoogleOAuthPacket(user: DbUser, accessToken: String, expiresIn: Int) | |
object GoogleOAuthPacket { | |
import DbUsers.userReads | |
implicit val googleOAuthPacketReads: Reads[GoogleOAuthPacket] = ( | |
userReads ~ | |
(__ \ 'access_token).read[String] ~ | |
(__ \ 'expires_in).read[Int] | |
tupled).map(t => GoogleOAuthPacket(t._1, t._2, t._3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment