Skip to content

Commit

Permalink
add token in global variable, refresh token if it's expired
Browse files Browse the repository at this point in the history
  • Loading branch information
yabinma committed Jul 1, 2024
1 parent 30898e0 commit 510ced4
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,42 @@ import (
"fmt"
"io"
"net/http"
"time"

"github.com/devilcove/httpclient"
"github.com/golang-jwt/jwt/v4"
"github.com/gravitl/netclient/config"
"github.com/gravitl/netclient/daemon"
"github.com/gravitl/netclient/wireguard"
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/models"
)

var (
jwtToken string
jwtSecretKey []byte
)

func isTokenExpired(tokenString string) bool {
claims := &models.Claims{}
token, _ := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtSecretKey, nil
})

if token != nil {
if claims.ExpiresAt.Unix() != 0 && claims.ExpiresAt.Unix() > time.Now().Unix() {
return false
}
}

return true
}

// Authenticate authenticates with netmaker api to permit subsequent interactions with the api
func Authenticate(server *config.Server, host *config.Config) (string, error) {
if jwtToken != "" && !isTokenExpired(jwtToken) {
return jwtToken, nil
}
data := models.AuthParams{
MacAddress: host.MacAddress.String(),
ID: host.ID.String(),
Expand Down Expand Up @@ -50,6 +75,7 @@ func Authenticate(server *config.Server, host *config.Config) (string, error) {
}
tokenData := resp.Response.(map[string]interface{})
token := tokenData["AuthToken"]
jwtToken = token.(string)
return token.(string), nil
}

Expand Down

0 comments on commit 510ced4

Please sign in to comment.