simple_token.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package auth
  15. // CAUTION: This randum number based token mechanism is only for testing purpose.
  16. // JWT based mechanism will be added in the near future.
  17. import (
  18. "crypto/rand"
  19. "math/big"
  20. )
  21. const (
  22. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  23. defaultSimpleTokenLength = 16
  24. )
  25. var (
  26. simpleTokens map[string]string // token -> user ID
  27. )
  28. func init() {
  29. simpleTokens = make(map[string]string)
  30. }
  31. func genSimpleToken() (string, error) {
  32. ret := make([]byte, defaultSimpleTokenLength)
  33. for i := 0; i < defaultSimpleTokenLength; i++ {
  34. bInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
  35. if err != nil {
  36. return "", err
  37. }
  38. ret[i] = letters[bInt.Int64()]
  39. }
  40. return string(ret), nil
  41. }
  42. func genSimpleTokenForUser(userID string) (string, error) {
  43. var token string
  44. var err error
  45. for {
  46. // generating random numbers in RSM would't a good idea
  47. token, err = genSimpleToken()
  48. if err != nil {
  49. return "", err
  50. }
  51. if _, ok := simpleTokens[token]; !ok {
  52. break
  53. }
  54. }
  55. simpleTokens[token] = userID
  56. return token, nil
  57. }