auth.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package auth
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gravitl/netmaker/models"
  6. "github.com/gravitl/netmaker/netclient/config"
  7. "github.com/gravitl/netmaker/netclient/ncutils"
  8. // "os"
  9. "context"
  10. "io/ioutil"
  11. nodepb "github.com/gravitl/netmaker/grpc"
  12. "google.golang.org/grpc/codes"
  13. "google.golang.org/grpc/metadata"
  14. "google.golang.org/grpc/status"
  15. )
  16. // CreateJWT func will used to create the JWT while signing in and signing out
  17. func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, error) {
  18. home := ncutils.GetNetclientPathSpecific()
  19. tokentext, err := ioutil.ReadFile(home + "nettoken-" + network)
  20. if err != nil {
  21. err = AutoLogin(client, network)
  22. if err != nil {
  23. return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong with Auto Login: %v", err))
  24. }
  25. tokentext, err = ioutil.ReadFile(home + "nettoken-" + network)
  26. if err != nil {
  27. return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong: %v", err))
  28. }
  29. }
  30. token := string(tokentext)
  31. // Anything linked to this variable will transmit request headers.
  32. md := metadata.New(map[string]string{"authorization": token})
  33. ctx := context.Background()
  34. ctx = metadata.NewOutgoingContext(ctx, md)
  35. return ctx, nil
  36. }
  37. func AutoLogin(client nodepb.NodeServiceClient, network string) error {
  38. home := ncutils.GetNetclientPathSpecific()
  39. cfg, err := config.ReadConfig(network)
  40. if err != nil {
  41. return err
  42. }
  43. pass, err := RetrieveSecret(network)
  44. if err != nil {
  45. return err
  46. }
  47. node := models.Node{
  48. Password: pass,
  49. MacAddress: cfg.Node.MacAddress,
  50. Network: network,
  51. }
  52. data, err := json.Marshal(&node)
  53. if err != nil {
  54. return nil
  55. }
  56. login := &nodepb.Object{
  57. Data: string(data),
  58. }
  59. // RPC call
  60. res, err := client.Login(context.TODO(), login)
  61. if err != nil {
  62. return err
  63. }
  64. tokenstring := []byte(res.Data)
  65. err = ioutil.WriteFile(home+"nettoken-"+network, tokenstring, 0644)
  66. if err != nil {
  67. return err
  68. }
  69. return err
  70. }
  71. func StoreSecret(key string, network string) error {
  72. d1 := []byte(key)
  73. err := ioutil.WriteFile(ncutils.GetNetclientPathSpecific()+"secret-"+network, d1, 0644)
  74. return err
  75. }
  76. func RetrieveSecret(network string) (string, error) {
  77. dat, err := ioutil.ReadFile(ncutils.GetNetclientPathSpecific() + "secret-" + network)
  78. return string(dat), err
  79. }
  80. type Configuration struct {
  81. MacAddress string
  82. Password string
  83. }