jwt.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  46. return jwtSecretKey, nil
  47. })
  48. if token != nil {
  49. return claims.UserName, claims.IsAdmin, nil
  50. }
  51. return "", false, err
  52. }
  53. // VerifyToken func will used to Verify the JWT Token while using APIS
  54. func VerifyToken(tokenString string) (macaddress string, network string, err error) {
  55. claims := &models.Claims{}
  56. //this may be a stupid way of serving up a master key
  57. //TODO: look into a different method. Encryption?
  58. if tokenString == config.Config.Server.MasterKey {
  59. return "mastermac", "", nil
  60. }
  61. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  62. return jwtSecretKey, nil
  63. })
  64. if token != nil {
  65. return claims.MacAddress, claims.Network, nil
  66. }
  67. return "", "", err
  68. }