package main import ( "context" "encoding/json" "fmt" "net/http" "strings" "time" "github.com/dgrijalva/jwt-go" "github.com/gorilla/mux" ) // Define contextKey globally within the package type contextKey string // Define your key as a constant of the custom type const userKey contextKey = "user" // LoginRequest represents the request body for the /login endpoint. type LoginRequest struct { Username string `json:"username"` Password string `json:"password"` } // LoginResponse represents the response body for the /login endpoint. type LoginResponse struct { Token string `json:"token"` } // loginHandler handles the /login endpoint. func LoginHandler(w http.ResponseWriter, r *http.Request) { var req LoginRequest fmt.Println(db, config) fmt.Println("LoginHandler called") err := json.NewDecoder(r.Body).Decode(&req) if err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) return } // Check if the user exists and the password matches var user User db.Where("username = ?", req.Username).First(&user) if user.ID == 0 || user.Password != req.Password { http.Error(w, "Invalid username or password", http.StatusUnauthorized) return } // Generate JWT token token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "username": user.Username, "exp": time.Now().Add(time.Hour * 24).Unix(), // Token expires in 24 hours }) tokenString, err := token.SignedString([]byte(config.JWTSecret)) if err != nil { http.Error(w, "Failed to generate token", http.StatusInternalServerError) return } // Return the token in the response json.NewEncoder(w).Encode(LoginResponse{Token: tokenString}) } // getBoxesHandler handles the GET /boxes endpoint. func GetBoxesHandler(w http.ResponseWriter, r *http.Request) { var boxes []Box db.Find(&boxes) json.NewEncoder(w).Encode(boxes) } // createBoxHandler handles the POST /boxes endpoint. func CreateBoxHandler(w http.ResponseWriter, r *http.Request) { var box Box err := json.NewDecoder(r.Body).Decode(&box) if err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) return } db.Create(&box) // Create a response struct to include the ID type createBoxResponse struct { ID uint `json:"id"` Name string `json:"name"` } response := createBoxResponse{ ID: box.ID, Name: box.Name, } json.NewEncoder(w).Encode(response) } // deleteBoxHandler handles the DELETE /boxes/{id} endpoint. func DeleteBoxHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] // Retrieve the box from the database var box Box if err := db.First(&box, id).Error; err != nil { http.Error(w, "Box not found", http.StatusNotFound) return } // Optionally, delete associated items (if you want cascading delete) // db.Where("box_id = ?", id).Delete(&Item{}) // Delete the box db.Delete(&box) w.WriteHeader(http.StatusNoContent) // 204 No Content } // getItemsHandler handles the GET /items endpoint. func GetItemsHandler(w http.ResponseWriter, r *http.Request) { var items []Item db.Find(&items) json.NewEncoder(w).Encode(items) } // createItemHandler handles the POST /items endpoint. func CreateItemHandler(w http.ResponseWriter, r *http.Request) { var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) return } db.Create(&item) // Create a response struct to include the ID type createItemResponse struct { ID uint `json:"id"` Name string `json:"name"` } response := createItemResponse{ ID: item.ID, Name: item.Name, } json.NewEncoder(w).Encode(response) } // getItemHandler handles the GET /items/{id} endpoint. func GetItemHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] var item Item if err := db.First(&item, id).Error; err != nil { http.Error(w, "Item not found", http.StatusNotFound) return } json.NewEncoder(w).Encode(item) } // getItemsInBoxHandler handles the GET /items/{id}/items endpoint. func GetItemsInBoxHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] var items []Item if err := db.Where("box_id = ?", id).Find(&items).Error; err != nil { http.Error(w, "Items not found", http.StatusNotFound) return } json.NewEncoder(w).Encode(items) } // updateItemHandler handles the PUT /items/{id} endpoint. func UpdateItemHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] var item Item if err := db.First(&item, id).Error; err != nil { http.Error(w, "Item not found", http.StatusNotFound) return } err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) return } db.Save(&item) json.NewEncoder(w).Encode(item) } // deleteItemHandler handles the DELETE /items/{id} endpoint. func DeleteItemHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] var item Item if err := db.First(&item, id).Error; err != nil { http.Error(w, "Item not found", http.StatusNotFound) return } db.Delete(&item) w.WriteHeader(http.StatusNoContent) } // authMiddleware is a middleware function that checks for a valid JWT token in the request header and enables CORS. func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Set CORS headers w.Header().Set("Access-Control-Allow-Origin", "*") // Replace "*" with your allowed frontend origin if needed w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") // Handle preflight request for CORS if r.Method == http.MethodOptions { w.WriteHeader(http.StatusOK) return } // Get the token from the request header tokenString := r.Header.Get("Authorization") if tokenString == "" { http.Error(w, "Authorization header missing", http.StatusUnauthorized) return } // Remove "Bearer " prefix from token string tokenString = strings.Replace(tokenString, "Bearer ", "", 1) // Parse and validate the JWT token token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { // Make sure that the signing method is HMAC if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte(config.JWTSecret), nil }) if err != nil || !token.Valid { http.Error(w, "Invalid token", http.StatusUnauthorized) return } // Extract the user claims from the token if claims, ok := token.Claims.(jwt.MapClaims); ok { // Add the "user" claim to the request context newCtx := context.WithValue(r.Context(), userKey, claims["username"]) r = r.WithContext(newCtx) } else { http.Error(w, "Invalid token claims", http.StatusUnauthorized) return } // Call the next handler in the chain next.ServeHTTP(w, r) }) }