Last active
August 29, 2015 14:01
-
-
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)
This file contains hidden or 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
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