jwt.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package functions
  2. import (
  3. "time"
  4. "os"
  5. "github.com/gravitl/netmaker/config"
  6. "github.com/gravitl/netmaker/models"
  7. "github.com/dgrijalva/jwt-go"
  8. )
  9. var jwtSecretKey = []byte("(BytesOverTheWire)")
  10. // CreateJWT func will used to create the JWT while signing in and signing out
  11. func CreateJWT(macaddress string, network string) (response string, err error) {
  12. expirationTime := time.Now().Add(5 * time.Minute)
  13. claims := &models.Claims{
  14. MacAddress: macaddress,
  15. Network: network,
  16. StandardClaims: jwt.StandardClaims{
  17. ExpiresAt: expirationTime.Unix(),
  18. },
  19. }
  20. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  21. tokenString, err := token.SignedString(jwtSecretKey)
  22. if err == nil {
  23. return tokenString, nil
  24. }
  25. return "", err
  26. }
  27. func CreateUserJWT(username string, isadmin bool) (response string, err error) {
  28. expirationTime := time.Now().Add(60 * time.Minute)
  29. claims := &models.UserClaims{
  30. UserName: username,
  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, isadmin bool, err error) {
  45. claims := &models.UserClaims{}
  46. if tokenString == config.Config.Server.MasterKey || (tokenString == os.Getenv("MASTER_KEY") && tokenString != "") {
  47. return "masteradministrator", 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.IsAdmin, nil
  54. }
  55. return "", 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 == config.Config.Server.MasterKey || (tokenString == os.Getenv("MASTER_KEY") && tokenString != "") {
  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. }