// GetNewToken returns a JSON object which contains a new NONCE with its expiration time and the number of allowed usages. func GetNewToken(c *gin.Context) { failed := true // Allow up to ten attempts to generate an access key. for iter := 0; iter < 10; iter++ { if token, err := randutil.AlphaStringRange(10, 10); err == nil { if _, inCache := perishableCache.Get(token); inCache { // If this token is already in our cache, we don't even check if it's in Redis, // and just ask for a new one. continue } if ok, _ := getTokenHits(PerishableRedisKey(token), RedisCnx); !ok { // We calculate the expire time prior to actually setting it so the client // can switch to another Nonce before it actually expires. expires := time.Now().Add(NonceTTL) perishableCache.Set(token, &PerishableInfo{0, expires}, NonceTTL) setToken(PerishableRedisKey(token), NonceTTL, RedisCnx) c.JSON(200, gin.H{"token": token, "expires": expires.Format(time.RFC3339), "limit": NonceLimit}) failed = false break } } } if failed { // Could not generate a valid token. c.JSON(503, Status503.JSON()) } }
func makeRandomUserToken() (username string, tokenString string) { token := jwt.New(jwt.GetSigningMethod("HS256")) username, err := randutil.AlphaStringRange(5, 10) errPanic(err, "Cannot random string, wtf?") token.Claims["username"] = username token.Claims["secret"] = time.Now().Add(time.Hour * 72).Unix() tokenString, err = token.SignedString([]byte(mySigningKey)) errPanic(err, "Cannot sign string, wtf?") return }
// Generate returns a new value for a token according to the definition. func (t URLToken) Generate() (r string) { if t.Choices != "" { r, _ = randutil.ChoiceString(strings.Split(t.Choices, "|")) } switch t.Pattern { case "alpha": r, _ = randutil.StringRange(t.Min, t.Max, randutil.Alphabet) case "alphanum": r, _ = randutil.AlphaStringRange(t.Min, t.Max) case "num": rInt, _ := randutil.IntRange(t.Min, t.Max) r = strconv.FormatInt(int64(rInt), 10) } return }
func NewAnalyticsEvent() *AnalyticsJSON { randToken, _ := randutil.AlphaStringRange(10, 10) return &AnalyticsJSON{IP: "127.0.0.1", KissMetric: randToken[0:7], Session: "session_" + randToken[5:10], UserAgent: "Mozilla/5.0 (X11; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0", URL: "http://sparrho.com/awesome/link"} }