token_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package token
  2. import (
  3. "fmt"
  4. "testing"
  5. "time"
  6. "github.com/google/uuid"
  7. )
  8. func TestToken(t *testing.T) {
  9. secret := uuid.New().String()
  10. // create maker
  11. issuer := "daisy"
  12. user := "user1"
  13. maker, err := NewJWTMaker(secret)
  14. if err != nil {
  15. t.Errorf("creating token maker error %s", err.Error())
  16. }
  17. token, err := maker.CreateToken(issuer, user, time.Second*10)
  18. if err != nil {
  19. t.Errorf("creating token error %s", err.Error())
  20. }
  21. // create verifier
  22. verifier, err := NewJWTMaker(secret)
  23. if err != nil {
  24. t.Errorf("creating token maker verifier error %s", err.Error())
  25. }
  26. customClaim, err := verifier.VerifyToken(token)
  27. if err != nil {
  28. t.Errorf("verify token error %s", err.Error())
  29. }
  30. if customClaim.Issuer != issuer {
  31. t.Errorf("issuer mismatch ")
  32. }
  33. if customClaim.UserName != user {
  34. t.Errorf("user mismatch ")
  35. }
  36. }
  37. func TestTokenExpiration(t *testing.T) {
  38. secret := uuid.New().String()
  39. // create maker
  40. issuer := "daisy"
  41. user := "user1"
  42. maker, err := NewJWTMaker(secret)
  43. if err != nil {
  44. t.Errorf("creating token maker error %s", err.Error())
  45. }
  46. token, err := maker.CreateToken(issuer, user, time.Second*2)
  47. if err != nil {
  48. t.Errorf("creating token error %s", err.Error())
  49. }
  50. time.Sleep(time.Second * 3)
  51. // create verifier
  52. verifier, err := NewJWTMaker(secret)
  53. if err != nil {
  54. t.Errorf("creating token maker verifier error %s", err.Error())
  55. }
  56. _, err = verifier.VerifyToken(token)
  57. if err == nil {
  58. t.Errorf("verify token should return error")
  59. }
  60. }
  61. func TestSecretKeyGenerator(t *testing.T) {
  62. key, err := GenerateSecretKey()
  63. fmt.Println("key:", key)
  64. // t.Logf("key:%s\n", key)
  65. if err != nil {
  66. t.Errorf("generate secret key error %s", err.Error())
  67. }
  68. if len(key) != 120 {
  69. t.Errorf("secret key length, expected %d, got %d", 120, len(key))
  70. }
  71. }