package main import ( "context" "encoding/json" "errors" "fmt" "main/db" "main/handler" "net/http" "regexp" "time" "github.com/golang-jwt/jwt/v4" "github.com/gorilla/mux" "github.com/rs/cors" "go.mongodb.org/mongo-driver/bson" "golang.org/x/crypto/bcrypt" ) var jwtKey = []byte("mysecret123") type User struct { ID string `json:"id,omitempty"` Username string `json:"username"` Email string `json:"email"` Password string `json:"password,omitempty"` } type Claims struct { Username string `json:"username"` jwt.RegisteredClaims } func isValidEmail(email string) error { const emailRegex = `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` re := regexp.MustCompile(emailRegex) if !re.MatchString(email) { return errors.New("invalid email format") } return nil } func registerHnadler(w http.ResponseWriter, r *http.Request) { var user User _ = json.NewDecoder(r.Body).Decode(&user) w.Header().Set("Content-Type", "application/json") fmt.Print(user) if user.Email == "" || user.Username == "" || user.Password == "" { http.Error(w, `{"message": "please fill required fileds"}`, http.StatusBadRequest) return } if err := isValidEmail(user.Email); err != nil { http.Error(w, `{"message": "Email format is not correct"}`, http.StatusBadRequest) return } var existUser User _ = db.UserCollection.FindOne(context.TODO(), bson.M{"email": user.Email}).Decode(&existUser) if existUser.Email == user.Email { http.Error(w, `{"message": "User already registered"}`, http.StatusUnauthorized) return } hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) user.Password = string(hashedPassword) _, err := db.UserCollection.InsertOne(context.TODO(), user) if err != nil { http.Error(w, `{"message": "Could not create user"}`, http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode("User registerd successfully") } func loginHandler(w http.ResponseWriter, r *http.Request) { var creds User _ = json.NewDecoder(r.Body).Decode(&creds) var storedUser User err := db.UserCollection.FindOne(context.TODO(), bson.M{"username": creds.Username}).Decode(&storedUser) if err != nil { http.Error(w, `{"message": "Invalid username or password"}`, http.StatusUnauthorized) return } err = bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(creds.Password)) if err != nil { http.Error(w, `{"message": "Invalid username or password"}`, http.StatusUnauthorized) return } expirationTime := time.Now().Add(120 * time.Minute) claims := &Claims{ Username: creds.Username, RegisteredClaims: jwt.RegisteredClaims{ ExpiresAt: jwt.NewNumericDate(expirationTime), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenString, err := token.SignedString(jwtKey) if err != nil { // Debugging: Log the error fmt.Printf("Error generating token: %v\n", err) http.Error(w, "Error generating token", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "token": tokenString, }) } func main() { db.InitDB() router := mux.NewRouter() router.HandleFunc("/register", registerHnadler) router.HandleFunc("/login", loginHandler) router.HandleFunc("/createcluster", handler.CreateClusterHandler) router.HandleFunc("/deletecluster", handler.Deletecluster) router.HandleFunc("/clusters", handler.ListUserClusters) router.HandleFunc("/cluster_stats", handler.ClusterStats) router.HandleFunc("/cluster_resource_usage", handler.Cluster_resource_usage) router.HandleFunc("/cluster_health", handler.Cluster_health) router.HandleFunc("/cluster_uptime", handler.Cluster_uptime) router.HandleFunc("/cluster_performance", handler.Cluster_performance) router.HandleFunc("/cluster_events", handler.Cluster_events) router.HandleFunc("/connect", handler.Connect) // router.HandleFunc("/cluster_nodes", handler.Cluster_nodes) router.HandleFunc("/cluster_namespaces", handler.Cluster_namespaces) router.HandleFunc("/cluster_services", handler.Cluster_services) router.HandleFunc("/cluster_configmap", handler.Cluster_configmap) router.HandleFunc("/cluster_secret", handler.Cluster_secret) router.HandleFunc("/cluster_deployments", handler.Cluster_deployments) router.HandleFunc("/cluster_pods", handler.Cluster_pods) router.HandleFunc("/cluster_statefulset", handler.Cluster_statefulset) router.HandleFunc("/cluster_daemonsets", handler.Cluster_daemonsets) router.HandleFunc("/cluster_jobs", handler.Cluster_jobs) router.HandleFunc("/cluster_replicasets", handler.Cluster_replicasets) router.HandleFunc("/replicaset_delete", handler.Replicaset_delete) router.HandleFunc("/cluster_replicationcontrollers", handler.Cluster_replicationcontrollers) router.HandleFunc("/deployment_manifest", handler.Deployment_manifest) router.HandleFunc("/daemonsets_manifest", handler.DaemonSet_manifest) router.HandleFunc("/statefulset_manifest", handler.StatefulSet_manifest) router.HandleFunc("/replicationcontroller_manifest", handler.Replicationcontroller_manifest) router.HandleFunc("/deployment_rollout", handler.Deployment_rollout) router.HandleFunc("/daemonsets_rollout", handler.DaemonSet_rollout) router.HandleFunc("/deployment_scale", handler.Deployment_scale) router.HandleFunc("/replicaset_scale", handler.ReplicaSet_scale) router.HandleFunc("/statefulset_scale", handler.StatefulSet_scale) router.HandleFunc("/replicationcontroller_scale", handler.Replicationcontroller_scale) router.HandleFunc("/statefulset_rollout", handler.StatefulSet_rollout) router.HandleFunc("/pod_logs", handler.Pod_logs) router.HandleFunc("/pod_manifest", handler.Pod_manifest) router.HandleFunc("/replicaset_manifest", handler.Replicaset_manifest) router.HandleFunc("/jobs_manifest", handler.Jobs_manifest) router.HandleFunc("/cronjobs_manifest", handler.CronJobs_manifest) router.HandleFunc("/configmap_manifest", handler.ConfigMap_manifest) router.HandleFunc("/secret_manifest", handler.Secret_manifest) router.HandleFunc("/service_manifest", handler.Service_manifest) router.HandleFunc("/cronjobs_trigger", handler.Cronjobs_trigger) router.HandleFunc("/cronjobs_suspend", handler.Cronjobs_suspend) router.HandleFunc("/jobs_logs", handler.Jobs_logs) router.HandleFunc("/pod_create", handler.Pod_fromYaml) router.HandleFunc("/deployment_create", handler.Deployment_fromYaml) router.HandleFunc("/daemonsets_create", handler.DaemonSet_fromYaml) router.HandleFunc("/jobs_create", handler.Job_fromYaml) router.HandleFunc("/statefulset_create", handler.StatefulSet_fromYaml) router.HandleFunc("/configmap_create", handler.ConfigMap_fromYaml) router.HandleFunc("/secret_create", handler.Secret_fromYaml) router.HandleFunc("/service_create", handler.Service_fromYaml) router.HandleFunc("/pod_exec", handler.Pod_exec) router.HandleFunc("/pod_delete", handler.Pod_delete) router.HandleFunc("/service_delete", handler.Service_delete) router.HandleFunc("/configmap_delete", handler.Configmap_delete) router.HandleFunc("/secret_delete", handler.Secret_delete) router.HandleFunc("/deployment_delete", handler.Deployment_delete) router.HandleFunc("/statefulSet_delete", handler.StatefulSet_delete) router.HandleFunc("/daemonsets_delete", handler.Daemonsets_delete) router.HandleFunc("/jobsName_delete", handler.JobsName_delete) router.HandleFunc("/replicationcontroller_delete", handler.Replicationcontroller_delete) router.HandleFunc("/cronjobs_delete", handler.Cronjob_delete) router.HandleFunc("/cronjobs_create", handler.CronJob_fromYaml) router.HandleFunc("/cluster_cronjobs", handler.Cluster_cronjobs) router.HandleFunc("/replicationcontroller_create", handler.ReplicationController_fromYaml) router.HandleFunc("/replicationcontroller_migrate", handler.Replicationcontroller_migrate) router.HandleFunc("/helm_install", handler.Helm_install) router.HandleFunc("/worker_nodes_plan", handler.Worker_nodes_plan) //handler.RegsiterClusterRoute(router) // Enable CORS // c := cors.New(cors.Options{ // AllowedOrigins: []string{"*"}, // Allow all origins // AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // AllowedHeaders: []string{"Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin"}, // ExposedHeaders: []string{"Content-Length"}, // AllowCredentials: true, // Debug: true, // Enable debug logging // }) c := cors.New(cors.Options{ AllowedOrigins: []string{"*", "http://localhost:4200"}, // frontend origin AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin"}, ExposedHeaders: []string{"Content-Length"}, AllowCredentials: false, Debug: true, }) http.ListenAndServe("0.0.0.0:8082", c.Handler(router)) }