179 lines
5.9 KiB
Go
179 lines
5.9 KiB
Go
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("/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_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("/cluster_replicationcontrollers", handler.Cluster_replicationcontrollers)
|
|
|
|
router.HandleFunc("/pod_logs", handler.Pod_logs)
|
|
router.HandleFunc("/pod_exec", handler.Pod_exec)
|
|
router.HandleFunc("/pod_delete", handler.Pod_delete)
|
|
router.HandleFunc("/service_delete", handler.Service_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("/replicaset_delete", handler.Replicaset_delete)
|
|
router.HandleFunc("/replicationcontroller_delete", handler.Replicationcontroller_delete)
|
|
router.HandleFunc("/cronjob_delete", handler.Cronjob_delete)
|
|
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))
|
|
}
|