You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
104 lines
2.4 KiB
104 lines
2.4 KiB
package web
|
|
|
|
import (
|
|
"html/template"
|
|
"log"
|
|
"marmic/servicetrade-toolbox/internal/api"
|
|
"marmic/servicetrade-toolbox/internal/middleware"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == "GET" {
|
|
tmpl := template.Must(template.ParseFiles("templates/login.html"))
|
|
tmpl.Execute(w, nil)
|
|
return
|
|
}
|
|
|
|
if r.Method == "POST" {
|
|
email := r.FormValue("email")
|
|
password := r.FormValue("password")
|
|
|
|
session := api.NewSession()
|
|
err := session.Login(email, password)
|
|
if err != nil {
|
|
if r.Header.Get("HX-Request") == "true" {
|
|
w.Write([]byte("<div class='error'>Login failed: " + err.Error() + "</div>"))
|
|
} else {
|
|
http.Error(w, "Login failed", http.StatusUnauthorized)
|
|
}
|
|
return
|
|
}
|
|
|
|
cookieParts := strings.Split(session.Cookie, ";")
|
|
sessionID := strings.TrimPrefix(cookieParts[0], "PHPSESSID=")
|
|
|
|
middleware.SessionStore.Set(sessionID, session)
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "PHPSESSID",
|
|
Value: sessionID,
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: r.TLS != nil,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
|
|
if r.Header.Get("HX-Request") == "true" {
|
|
w.Header().Set("HX-Redirect", "/")
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write([]byte("Login successful"))
|
|
} else {
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
}
|
|
}
|
|
}
|
|
|
|
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
|
cookie, err := r.Cookie("PHPSESSID")
|
|
if err != nil {
|
|
log.Printf("No session cookie found: %v", err)
|
|
redirectToLogin(w, r)
|
|
return
|
|
}
|
|
|
|
sessionID := cookie.Value
|
|
session, exists := middleware.SessionStore.Get(sessionID)
|
|
if !exists {
|
|
log.Println("No session found in store")
|
|
redirectToLogin(w, r)
|
|
return
|
|
}
|
|
|
|
err = session.Logout()
|
|
if err != nil {
|
|
log.Printf("Logout failed: %v", err)
|
|
http.Error(w, "Logout failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
middleware.SessionStore.Delete(sessionID)
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "PHPSESSID",
|
|
Value: "",
|
|
Path: "/",
|
|
MaxAge: -1,
|
|
HttpOnly: true,
|
|
Secure: r.TLS != nil,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
|
|
log.Println("Logout successful, redirecting to login page")
|
|
redirectToLogin(w, r)
|
|
}
|
|
|
|
func redirectToLogin(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("HX-Request") != "" {
|
|
w.Header().Set("HX-Redirect", "/login")
|
|
w.WriteHeader(http.StatusOK)
|
|
} else {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
}
|
|
}
|
|
|