Skip to content

Instantly share code, notes, and snippets.

@guersam
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guersam/24bd61849ad93244b6eb to your computer and use it in GitHub Desktop.
Save guersam/24bd61849ad93244b6eb to your computer and use it in GitHub Desktop.
Generating unique random token using async Redis driver (https://github.com/debasishg/scala-redis-nb)
def generateUniqueRandomToken(): Future[String] = {
val token = generateRandomToken(TokenLength)
redis.exists(tokenKey(token)) flatMap {
case true => generateUniqueRandomToken()
case false => Future.successful(token)
}
}
// ...
private val secureRandom = {
val s = new SecureRandom
s.nextInt()
s
}
private val unreservedChars: Array[Char] =
Array('-', '.', '_', '~') ++ ('0' to '9') ++ ('A' to 'Z') ++ ('a' to 'z')
private def generateRandomToken(length: Int) = {
val chars = Array.fill(length) {
val randIdx = secureRandom.nextInt(unreservedChars.length)
unreservedChars(randIdx)
}
new String(chars)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment