token_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 Yunion
  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 tokens
  15. import (
  16. "testing"
  17. "time"
  18. "github.com/golang-plus/uuid"
  19. api "yunion.io/x/onecloud/pkg/apis/identity"
  20. "yunion.io/x/onecloud/pkg/util/fernetool"
  21. )
  22. func newUuid() string {
  23. u, _ := uuid.NewV4()
  24. return u.Format(uuid.StyleWithoutDash)
  25. }
  26. func TestSAuthToken_Encode(t *testing.T) {
  27. fm := fernetool.SFernetKeyManager{}
  28. err := fm.InitKeys("", 2)
  29. if err != nil {
  30. t.Fatalf("SFernetKeyManager InitKeys fail %s", err)
  31. }
  32. for i := 0; i < 10; i += 1 {
  33. token := SAuthToken{}
  34. token.UserId = newUuid()
  35. token.Method = api.AUTH_METHOD_PASSWORD
  36. token.ProjectId = newUuid()
  37. token.ExpiresAt = time.Now()
  38. token.AuditIds = []string{newUuid()}
  39. tk, err := token.Encode()
  40. if err != nil {
  41. t.Fatalf("SAuthToken encode fail %s", err)
  42. }
  43. ft, err := fm.Encrypt(tk)
  44. if err != nil {
  45. t.Fatalf("SFernetKeyManager encrypt fail %s", err)
  46. }
  47. dtm := fm.Decrypt(ft)
  48. token2 := SAuthToken{}
  49. err = token2.Decode(dtm)
  50. if err != nil {
  51. t.Fatalf("SAuthToken decode fail %s", err)
  52. }
  53. if token.UserId != token2.UserId {
  54. t.Fatalf("recovery uuid fail %s != %s", token.UserId, token2.UserId)
  55. }
  56. }
  57. }