auth.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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) (context.Context, error) {
  15. home, err := os.UserHomeDir()
  16. tokentext, err := ioutil.ReadFile(home + "/.wctoken")
  17. if err != nil {
  18. fmt.Println("Error reading token. Logging in to retrieve new token.")
  19. err = AutoLogin(client)
  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 + "/.wctoken")
  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) error {
  36. home, err := os.UserHomeDir()
  37. nodecfg := config.Config.Node
  38. login := &nodepb.LoginRequest{
  39. Password: nodecfg.Password,
  40. Macaddress: nodecfg.MacAddress,
  41. }
  42. // RPC call
  43. res, err := client.Login(context.TODO(), login)
  44. if err != nil {
  45. return err
  46. }
  47. fmt.Printf("Token: %s\n", res.Accesstoken)
  48. tokenstring := []byte(res.Accesstoken)
  49. err = ioutil.WriteFile(home + "/.wctoken", tokenstring, 0644)
  50. if err != nil {
  51. return err
  52. }
  53. return err
  54. }
  55. type Configuration struct {
  56. MacAddress string
  57. Password string
  58. }