auth.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package functions
  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. fmt.Println("Error reading token. Logging in to retrieve new token.")
  20. err = AutoLogin(client, network)
  21. if err != nil {
  22. return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong with Auto Login: %v", err))
  23. }
  24. tokentext, err = ioutil.ReadFile(home + "/nettoken-"+network)
  25. if err != nil {
  26. return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong: %v", err))
  27. }
  28. }
  29. token := string(tokentext)
  30. // Anything linked to this variable will transmit request headers.
  31. md := metadata.New(map[string]string{"authorization": token})
  32. ctx := context.Background()
  33. ctx = metadata.NewOutgoingContext(ctx, md)
  34. return ctx, nil
  35. }
  36. func AutoLogin(client nodepb.NodeServiceClient, network string) error {
  37. //home, err := os.UserHomeDir()
  38. home := "/etc/netclient"
  39. //nodecfg := config.Config.Node
  40. cfg, err := config.ReadConfig(network)
  41. if err != nil {
  42. return err
  43. }
  44. login := &nodepb.LoginRequest{
  45. Password: cfg.Node.Password,
  46. Macaddress: cfg.Node.MacAddress,
  47. Network: network,
  48. }
  49. // RPC call
  50. res, err := client.Login(context.TODO(), login)
  51. if err != nil {
  52. return err
  53. }
  54. tokenstring := []byte(res.Accesstoken)
  55. err = ioutil.WriteFile(home + "/nettoken-"+network, tokenstring, 0644)
  56. if err != nil {
  57. return err
  58. }
  59. return err
  60. }
  61. type Configuration struct {
  62. MacAddress string
  63. Password string
  64. }