github.com/10ego/gthp@v0.0.0-20241025155251-e1514fa71fbb/internal/handlers/auth-handler.go (about)

     1  package handlers
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/10ego/gthp/internal/templ/templates"
     7  )
     8  
     9  func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {
    10  	if r.Method == http.MethodGet {
    11  		err := templates.Login().Render(r.Context(), w)
    12  		if err != nil {
    13  			h.log.Errorw("Failed to render login template", "error", err)
    14  			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
    15  		}
    16  		return
    17  	}
    18  	if r.Method != http.MethodPost {
    19  		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    20  		return
    21  	}
    22  
    23  	username := r.FormValue("username")
    24  	password := r.FormValue("password")
    25  
    26  	// Create a context with a timeout
    27  	// ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
    28  	// defer cancel()
    29  
    30  	h.log.Info("Attempting to authenticate with LDAP..")
    31  	authenticated, err := h.ldapClient.Authenticate(r.Context(), username, password)
    32  	if err != nil {
    33  		h.log.Errorw("Authentication error", "error", err, "username", username)
    34  		http.Error(w, "Authentication error", http.StatusInternalServerError)
    35  		return
    36  	}
    37  	if authenticated {
    38  		h.log.Infow("User authenticated successfully", "username", username)
    39  		w.Write([]byte("<div>Login successful! Redirecting...</div>"))
    40  		http.Redirect(w, r, "/", http.StatusSeeOther)
    41  	} else {
    42  		h.log.Warnw("Invalid credentials", "username", username)
    43  		w.Write([]byte("<div>Login failed!div>"))
    44  		w.WriteHeader(http.StatusUnauthorized)
    45  		templates.Login().Render(r.Context(), w)
    46  	}
    47  }
    48  
    49  func (h *Handler) LogoutHandler(w http.ResponseWriter, r *http.Request) {
    50  	if r.Method != http.MethodPost {
    51  		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    52  		return
    53  	}
    54  	// Implement logout logic here
    55  	http.Redirect(w, r, "/", http.StatusSeeOther)
    56  }