simple_token.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "sync"
  21. )
  22. const (
  23. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  24. defaultSimpleTokenLength = 16
  25. )
  26. var (
  27. simpleTokensMu sync.RWMutex
  28. simpleTokens map[string]string // token -> username
  29. )
  30. func init() {
  31. simpleTokens = make(map[string]string)
  32. }
  33. func genSimpleToken() (string, error) {
  34. ret := make([]byte, defaultSimpleTokenLength)
  35. for i := 0; i < defaultSimpleTokenLength; i++ {
  36. bInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
  37. if err != nil {
  38. return "", err
  39. }
  40. ret[i] = letters[bInt.Int64()]
  41. }
  42. return string(ret), nil
  43. }
  44. func genSimpleTokenForUser(username string) (string, error) {
  45. var token string
  46. var err error
  47. for {
  48. // generating random numbers in RSM would't a good idea
  49. token, err = genSimpleToken()
  50. if err != nil {
  51. return "", err
  52. }
  53. if _, ok := simpleTokens[token]; !ok {
  54. break
  55. }
  56. }
  57. simpleTokensMu.Lock()
  58. simpleTokens[token] = username
  59. simpleTokensMu.Unlock()
  60. return token, nil
  61. }