auth.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package auth
  2. import (
  3. "github.com/gravitl/netmaker/netclient/config"
  4. "fmt"
  5. // "os"
  6. "context"
  7. "io/ioutil"
  8. "google.golang.org/grpc/metadata"
  9. "google.golang.org/grpc/status"
  10. "google.golang.org/grpc/codes"
  11. nodepb "github.com/gravitl/netmaker/grpc"
  12. )
  13. // CreateJWT func will used to create the JWT while signing in and signing out
  14. func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, error) {
  15. //home, err := os.UserHomeDir()
  16. home := "/etc/netclient"
  17. tokentext, err := ioutil.ReadFile(home + "/nettoken-"+network)
  18. if err != nil {
  19. err = AutoLogin(client, network)
  20. if err != nil {
  21. return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong with Auto Login: %v", err))
  22. }
  23. tokentext, err = ioutil.ReadFile(home + "/nettoken-"+network)
  24. if err != nil {
  25. return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong: %v", err))
  26. }
  27. }
  28. token := string(tokentext)
  29. // Anything linked to this variable will transmit request headers.
  30. md := metadata.New(map[string]string{"authorization": token})
  31. ctx := context.Background()
  32. ctx = metadata.NewOutgoingContext(ctx, md)
  33. return ctx, nil
  34. }
  35. func AutoLogin(client nodepb.NodeServiceClient, network string) error {
  36. //home, err := os.UserHomeDir()
  37. home := "/etc/netclient"
  38. //nodecfg := config.Config.Node
  39. cfg, err := config.ReadConfig(network)
  40. if err != nil {
  41. return err
  42. }
  43. login := &nodepb.LoginRequest{
  44. Password: cfg.Node.Password,
  45. Macaddress: cfg.Node.MacAddress,
  46. Network: network,
  47. }
  48. // RPC call
  49. res, err := client.Login(context.TODO(), login)
  50. if err != nil {
  51. return err
  52. }
  53. tokenstring := []byte(res.Accesstoken)
  54. err = ioutil.WriteFile(home + "/nettoken-"+network, tokenstring, 0644)
  55. if err != nil {
  56. return err
  57. }
  58. return err
  59. }
  60. type Configuration struct {
  61. MacAddress string
  62. Password string
  63. }