netmaker/netclient/functions/auth.go

71 lines
2.3 KiB
Go
Raw Normal View History

2021-03-26 00:17:52 +08:00
package functions
import (
"github.com/gravitl/netmaker/netclient/config"
"fmt"
2021-03-26 10:29:36 +08:00
// "os"
2021-03-26 00:17:52 +08:00
"context"
"io/ioutil"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/grpc/codes"
nodepb "github.com/gravitl/netmaker/grpc"
)
// CreateJWT func will used to create the JWT while signing in and signing out
func SetJWT(client nodepb.NodeServiceClient, network string) (context.Context, error) {
2021-03-26 10:29:36 +08:00
//home, err := os.UserHomeDir()
home := "/etc/netclient"
tokentext, err := ioutil.ReadFile(home + "/nettoken-"+network)
2021-03-26 00:17:52 +08:00
if err != nil {
fmt.Println("Error reading token. Logging in to retrieve new token.")
err = AutoLogin(client, network)
2021-03-26 00:17:52 +08:00
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong with Auto Login: %v", err))
}
tokentext, err = ioutil.ReadFile(home + "/nettoken-"+network)
2021-03-26 00:17:52 +08:00
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, fmt.Sprintf("Something went wrong: %v", err))
}
}
token := string(tokentext)
// Anything linked to this variable will transmit request headers.
md := metadata.New(map[string]string{"authorization": token})
ctx := context.Background()
ctx = metadata.NewOutgoingContext(ctx, md)
return ctx, nil
}
func AutoLogin(client nodepb.NodeServiceClient, network string) error {
2021-03-26 10:29:36 +08:00
//home, err := os.UserHomeDir()
home := "/etc/netclient"
//nodecfg := config.Config.Node
2021-04-07 21:39:40 +08:00
cfg, err := config.ReadConfig(network)
if err != nil {
return err
}
login := &nodepb.LoginRequest{
2021-04-07 21:39:40 +08:00
Password: cfg.Node.Password,
Macaddress: cfg.Node.MacAddress,
Network: network,
2021-03-26 00:17:52 +08:00
}
// RPC call
res, err := client.Login(context.TODO(), login)
if err != nil {
return err
}
tokenstring := []byte(res.Accesstoken)
err = ioutil.WriteFile(home + "/nettoken-"+network, tokenstring, 0644)
2021-03-26 00:17:52 +08:00
if err != nil {
return err
}
return err
}
type Configuration struct {
MacAddress string
Password string
}