package main
import (
"database/sql"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
_ "github.com/mattn/go-sqlite3"
"gobin/config"
"gobin/datastore"
"gobin/handler"
"gobin/mail"
"gobin/middleware"
)
func main() {
db := datastore.Must(sql.Open("sqlite3", "data.db"))
cfg := config.Must(config.New("config.json"))
mail.SetConfig(cfg)
log.SetFlags(log.Ldate | log.Ltime | log.Llongfile)
router := mux.NewRouter()
router.Handle("/edit", handler.EditPaste(db))
router.PathPrefix("/").
HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "public, max-age=2592000")
http.FileServer(http.Dir("static/")).ServeHTTP(w, r)
})
http.Handle("/", middleware.Headers(middleware.Nocsrf(middleware.
Authentication(db, router))))
go http.ListenAndServe(":8080", http.HandlerFunc(redirect))
log.Fatal(http.ListenAndServeTLS(":8081", os.Getenv("CRT"), os.Getenv("KEY"), nil))
}
func EditPaste(db *sql.DB) http.Handler {
return Handler(func(w http.ResponseWriter, r *http.Request) error {
if r.Method != http.MethodPost {
return errors.New("only post allowed")
}
varID := r.FormValue("id")
slug := r.FormValue("slug")
id, err := strconv.Atoi(varID)
if err != nil {
return StatusError{Err: err,
Code: http.StatusBadRequest,
Msg: "You have inserted a incorrect ID"}
}
authUser, err := auth.GetAuthenticatedUser(r.Context())
if err != nil {
return ErrNotAuthorized
}
if !authUser.Validated {
return StatusError{
Code: http.StatusUnauthorized,
Err: errors.New("user not fully authenticated"),
Msg: "Your user has to be fully authenticated, please log in.",
}
}
paste, err := datastore.FetchPasteByID(db, id)
if err != nil {
return err
}
pasteBySlug, err := datastore.FetchPasteBySlug(db, slug)
if err != nil {
return err
}
if paste.ID != pasteBySlug.ID {
return StatusError{http.StatusNotFound,
errors.New("slug and id do not match"),
"Couldn't find this paste!"}
}
if paste.UserID != authUser.ID {
return ErrNotAuthorized
}
title := r.FormValue("title")
content := r.FormValue("content")
statusStr := r.FormValue("status")
status, err := strconv.Atoi(statusStr)
if err != nil {
return err
}
paste.Title = title
paste.Content = content
paste.Status = status
err = datastore.UpdatePaste(db, paste)
if err != nil {
return err
}
http.Redirect(w, r, filepath.Join("/view/", paste.Slug), http.StatusFound)
return nil
})
}