jwt.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package functions
  2. import (
  3. "time"
  4. "github.com/gravitl/netmaker/models"
  5. "github.com/gravitl/netmaker/servercfg"
  6. "github.com/dgrijalva/jwt-go"
  7. )
  8. var jwtSecretKey = []byte("(BytesOverTheWire)")
  9. // CreateJWT func will used to create the JWT while signing in and signing out
  10. func CreateJWT(macaddress string, network string) (response string, err error) {
  11. expirationTime := time.Now().Add(5 * time.Minute)
  12. claims := &models.Claims{
  13. MacAddress: macaddress,
  14. Network: network,
  15. StandardClaims: jwt.StandardClaims{
  16. ExpiresAt: expirationTime.Unix(),
  17. },
  18. }
  19. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  20. tokenString, err := token.SignedString(jwtSecretKey)
  21. if err == nil {
  22. return tokenString, nil
  23. }
  24. return "", err
  25. }
  26. func CreateUserJWT(username string, networks []string, isadmin bool) (response string, err error) {
  27. expirationTime := time.Now().Add(60 * time.Minute)
  28. claims := &models.UserClaims{
  29. UserName: username,
  30. Networks: networks,
  31. IsAdmin: isadmin,
  32. StandardClaims: jwt.StandardClaims{
  33. ExpiresAt: expirationTime.Unix(),
  34. },
  35. }
  36. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  37. tokenString, err := token.SignedString(jwtSecretKey)
  38. if err == nil {
  39. return tokenString, nil
  40. }
  41. return "", err
  42. }
  43. // VerifyToken func will used to Verify the JWT Token while using APIS
  44. func VerifyUserToken(tokenString string) (username string, networks []string, isadmin bool, err error) {
  45. claims := &models.UserClaims{}
  46. if tokenString == servercfg.GetMasterKey() {
  47. return "masteradministrator", nil, true, nil
  48. }
  49. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  50. return jwtSecretKey, nil
  51. })
  52. if token != nil {
  53. return claims.UserName, claims.Networks, claims.IsAdmin, nil
  54. }
  55. return "", nil, false, err
  56. }
  57. // VerifyToken func will used to Verify the JWT Token while using APIS
  58. func VerifyToken(tokenString string) (macaddress string, network string, err error) {
  59. claims := &models.Claims{}
  60. //this may be a stupid way of serving up a master key
  61. //TODO: look into a different method. Encryption?
  62. if tokenString == servercfg.GetMasterKey() {
  63. return "mastermac", "", nil
  64. }
  65. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  66. return jwtSecretKey, nil
  67. })
  68. if token != nil {
  69. return claims.MacAddress, claims.Network, nil
  70. }
  71. return "", "", err
  72. }