accessTokens.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. package utils
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. )
  6. const tokenLength = 32
  7. // GenerateAccessToken will generate and return an access token.
  8. func GenerateAccessToken() (string, error) {
  9. return GenerateRandomString(tokenLength)
  10. }
  11. // generateRandomBytes returns securely generated random bytes.
  12. // It will return an error if the system's secure random
  13. // number generator fails to function correctly, in which
  14. // case the caller should not continue.
  15. func generateRandomBytes(n int) ([]byte, error) {
  16. b := make([]byte, n)
  17. _, err := rand.Read(b)
  18. // Note that err == nil only if we read len(b) bytes.
  19. if err != nil {
  20. return nil, err
  21. }
  22. return b, nil
  23. }
  24. // GenerateRandomString returns a URL-safe, base64 encoded
  25. // securely generated random string.
  26. // It will return an error if the system's secure random
  27. // number generator fails to function correctly, in which
  28. // case the caller should not continue.
  29. func GenerateRandomString(n int) (string, error) {
  30. b, err := generateRandomBytes(n)
  31. return base64.URLEncoding.EncodeToString(b), err
  32. }