add jwt token validation

This commit is contained in:
behrooz
2025-08-13 12:03:42 +03:30
parent 7200d913f6
commit 3834c84497
5 changed files with 41 additions and 8 deletions

View File

@@ -16,6 +16,7 @@ import (
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/kubectl/pkg/scheme"
@@ -31,6 +32,13 @@ import (
"k8s.io/client-go/tools/remotecommand"
)
type User struct {
ID string `json:"id,omitempty"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password,omitempty"`
}
type Cluster struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Name string `json:"name"`
@@ -175,14 +183,27 @@ func human(d time.Duration) string {
return fmt.Sprintf("%ds", secs)
}
var jwtKey = []byte("mysecret123")
func DecodeJwt(tokenString *string, user *User) {
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(*tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtKey), nil
})
if err != nil {
log.Println(err)
return
}
user.Username = claims["username"].(string)
}
func CreateClusterHandler(w http.ResponseWriter, r *http.Request) {
var cluster Cluster
_ = json.NewDecoder(r.Body).Decode(&cluster)
var header Header
header.Authorization = r.Header.Get("Authorization")
// vclusterCollection := db.Vclusters_details.FindOne(context.TODO(), bson.M{"name": Cluster.Name}).Decode(&existsCluster)
if cluster.Name == "" || cluster.ControlPlane == "" || cluster.PlatformVersion == "" || cluster.Cpu == "" || cluster.Memory == "" {
@@ -268,6 +289,18 @@ func getClientset(w http.ResponseWriter, clustername string) (*kubernetes.Client
func ListUserClusters(w http.ResponseWriter, r *http.Request) {
// var cluster Cluster
var header Header
var user User
header.Authorization = r.Header.Get("Authorization")
DecodeJwt(&header.Authorization, &user)
count, err := db.UserCollection.CountDocuments(context.TODO(), bson.M{"username": user.Username})
if err != nil || count <= 0 {
http.Error(w, `{"message": "Invalid username "}`, http.StatusUnauthorized)
return
}
_, clusterList := argohandler.ListUserClusters("userid")
w.Header().Set("Content-Type", "application/json")