simple_token.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "strings"
  21. )
  22. const (
  23. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  24. defaultSimpleTokenLength = 16
  25. )
  26. func (as *authStore) GenSimpleToken() (string, error) {
  27. ret := make([]byte, defaultSimpleTokenLength)
  28. for i := 0; i < defaultSimpleTokenLength; i++ {
  29. bInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
  30. if err != nil {
  31. return "", err
  32. }
  33. ret[i] = letters[bInt.Int64()]
  34. }
  35. return string(ret), nil
  36. }
  37. func (as *authStore) assignSimpleTokenToUser(username, token string) {
  38. as.simpleTokensMu.Lock()
  39. _, ok := as.simpleTokens[token]
  40. if ok {
  41. plog.Panicf("token %s is alredy used", token)
  42. }
  43. as.simpleTokens[token] = username
  44. as.simpleTokensMu.Unlock()
  45. }
  46. func (as *authStore) invalidateUser(username string) {
  47. as.simpleTokensMu.Lock()
  48. defer as.simpleTokensMu.Unlock()
  49. for token, name := range as.simpleTokens {
  50. if strings.Compare(name, username) == 0 {
  51. delete(as.simpleTokens, token)
  52. }
  53. }
  54. }