jwt.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package functions
  2. import (
  3. "time"
  4. "github.com/gravitl/netmaker/config"
  5. "github.com/gravitl/netmaker/models"
  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, isadmin bool) (response string, err error) {
  27. expirationTime := time.Now().Add(60 * time.Minute)
  28. claims := &models.UserClaims{
  29. UserName: username,
  30. IsAdmin: isadmin,
  31. StandardClaims: jwt.StandardClaims{
  32. ExpiresAt: expirationTime.Unix(),
  33. },
  34. }
  35. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  36. tokenString, err := token.SignedString(jwtSecretKey)
  37. if err == nil {
  38. return tokenString, nil
  39. }
  40. return "", err
  41. }
  42. // VerifyToken func will used to Verify the JWT Token while using APIS
  43. func VerifyUserToken(tokenString string) (username string, isadmin bool, err error) {
  44. claims := &models.UserClaims{}
  45. if tokenString == config.Config.Server.MasterKey {
  46. return "masteradministrator", true, nil
  47. }
  48. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  49. return jwtSecretKey, nil
  50. })
  51. if token != nil {
  52. return claims.UserName, claims.IsAdmin, nil
  53. }
  54. return "", false, err
  55. }
  56. // VerifyToken func will used to Verify the JWT Token while using APIS
  57. func VerifyToken(tokenString string) (macaddress string, network string, err error) {
  58. claims := &models.Claims{}
  59. //this may be a stupid way of serving up a master key
  60. //TODO: look into a different method. Encryption?
  61. if tokenString == config.Config.Server.MasterKey {
  62. return "mastermac", "", nil
  63. }
  64. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  65. return jwtSecretKey, nil
  66. })
  67. if token != nil {
  68. return claims.MacAddress, claims.Network, nil
  69. }
  70. return "", "", err
  71. }