simple_token.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. func (as *authStore) GenSimpleToken() (string, error) {
  26. ret := make([]byte, defaultSimpleTokenLength)
  27. for i := 0; i < defaultSimpleTokenLength; i++ {
  28. bInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
  29. if err != nil {
  30. return "", err
  31. }
  32. ret[i] = letters[bInt.Int64()]
  33. }
  34. return string(ret), nil
  35. }
  36. func (as *authStore) assignSimpleTokenToUser(username, token string) {
  37. as.simpleTokensMu.Lock()
  38. _, ok := as.simpleTokens[token]
  39. if ok {
  40. plog.Panicf("token %s is alredy used", token)
  41. }
  42. as.simpleTokens[token] = username
  43. as.simpleTokensMu.Unlock()
  44. }