package api import ( "encoding/json" "net/http" "time" "git.freecumextremist.com/grumbulon/pomme/internal" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" ) func Login(w http.ResponseWriter, r *http.Request) { var result internal.User r.ParseForm() username := r.Form.Get("username") if username == "" { username = autoUname() } password := r.Form.Get("password") if password == "" { http.Error(w, "No password provided", http.StatusInternalServerError) // this should prob be handled by the frontend } db, ok := r.Context().Value("DB").(*gorm.DB) if !ok { http.Error(w, "internal server error", http.StatusInternalServerError) return } db.Model(internal.User{Username: username}).First(&result) err := bcrypt.CompareHashAndPassword([]byte(result.HashedPassword), []byte(password)) if err != nil { basicAuthFailed(w, "user") return } token := makeToken(username) http.SetCookie(w, &http.Cookie{ HttpOnly: true, Expires: time.Now().Add(7 * 24 * time.Hour), SameSite: http.SameSiteLaxMode, // Uncomment below for HTTPS: // Secure: true, Name: "jwt", // Must be named "jwt" or else the token cannot be searched for by jwtauth.Verifier. Value: token, }) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode( internal.Response{ Message: "Successfully logged in", HTTPResponse: 200, Username: token, }) http.Redirect(w, r, "/", http.StatusSeeOther) } func Logout(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ HttpOnly: true, MaxAge: -1, // Delete the cookie. SameSite: http.SameSiteLaxMode, // Secure: true, Name: "jwt", Value: "", }) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode( internal.Response{ Message: "Successfully logged out", HTTPResponse: 200, }) http.Redirect(w, r, "/", http.StatusSeeOther) }