rushlink/handlers/handlers.go

263 lines
6.3 KiB
Go
Raw Normal View History

package handlers
2019-08-25 21:33:56 +02:00
import (
2019-09-01 01:41:01 +02:00
"crypto/subtle"
"encoding/base64"
2019-08-25 21:33:56 +02:00
"fmt"
"log"
"net/http"
"net/url"
"time"
2019-08-29 23:40:24 +02:00
"github.com/gorilla/mux"
"github.com/pkg/errors"
2019-08-25 21:33:56 +02:00
bolt "go.etcd.io/bbolt"
2019-09-15 17:43:09 +02:00
"gitea.hashru.nl/dsprenkels/rushlink/db"
2019-08-25 21:33:56 +02:00
)
2019-09-21 13:11:38 +02:00
type viewPaste uint
const (
_ viewPaste = 1 << iota
viewNoRedirect
viewShowMeta
)
const CookieDeleteToken = "owner_token"
2019-09-01 01:41:01 +02:00
2019-09-01 12:04:43 +02:00
// These keys are designated reserved, and will not be randomly chosen
2019-09-15 22:54:07 +02:00
var ReservedPasteKeys = []string{"xd42", "example"}
2019-09-01 12:04:43 +02:00
2019-09-01 01:41:01 +02:00
// Base64 encoding and decoding
var base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
var base64Encoder = base64.RawURLEncoding.WithPadding(base64.NoPadding)
2019-09-01 01:41:01 +02:00
2019-09-21 13:11:38 +02:00
func (t pasteType) String() string {
2019-09-01 01:41:01 +02:00
switch t {
2019-09-21 13:11:38 +02:00
case typeUndef:
return "unknown"
case typePaste:
2019-09-15 22:54:07 +02:00
return "paste"
2019-09-21 13:11:38 +02:00
case typeRedirect:
2019-09-15 22:54:07 +02:00
return "redirect"
2019-09-01 01:41:01 +02:00
default:
2019-09-15 22:54:07 +02:00
return "invalid"
2019-09-01 01:41:01 +02:00
}
}
2019-09-21 13:11:38 +02:00
func (t pasteState) String() string {
2019-09-01 01:41:01 +02:00
switch t {
2019-09-21 13:11:38 +02:00
case stateUndef:
return "unknown"
case statePresent:
2019-09-15 22:54:07 +02:00
return "present"
2019-09-21 13:11:38 +02:00
case stateDeleted:
2019-09-15 22:54:07 +02:00
return "deleted"
2019-09-01 01:41:01 +02:00
default:
2019-09-15 22:54:07 +02:00
return "invalid"
2019-09-01 01:41:01 +02:00
}
}
2019-09-19 21:29:25 +02:00
func indexGetHandler(w http.ResponseWriter, r *http.Request) {
2019-09-21 13:11:38 +02:00
render(w, r, "index", map[string]interface{}{})
2019-08-25 21:33:56 +02:00
}
2019-09-21 13:11:38 +02:00
func viewPasteHandler(w http.ResponseWriter, r *http.Request) {
viewPasteHandlerInner(w, r, 0)
}
2019-09-21 13:11:38 +02:00
func viewPasteHandlerNoRedirect(w http.ResponseWriter, r *http.Request) {
viewPasteHandlerInner(w, r, viewNoRedirect)
}
2019-09-21 13:11:38 +02:00
func viewPasteHandlerMeta(w http.ResponseWriter, r *http.Request) {
viewPasteHandlerInner(w, r, viewShowMeta)
2019-09-01 01:41:01 +02:00
}
2019-09-21 13:11:38 +02:00
func viewPasteHandlerInner(w http.ResponseWriter, r *http.Request, flags viewPaste) {
2019-08-29 00:50:26 +02:00
vars := mux.Vars(r)
key := vars["key"]
var p *paste
if err := db.DB.View(func(tx *bolt.Tx) error {
2019-08-29 00:50:26 +02:00
var err error
p, err = getPaste(tx, key)
2019-08-29 00:50:26 +02:00
return err
}); err != nil {
log.Printf("error: %v\n", err)
2019-09-19 21:42:01 +02:00
renderInternalServerError(w, r, err)
2019-08-29 00:50:26 +02:00
return
}
if p == nil {
2019-09-19 21:42:01 +02:00
renderError(w, r, http.StatusNotFound, "url key not found in the database")
2019-09-01 01:41:01 +02:00
return
}
2019-09-21 13:11:38 +02:00
if flags&viewShowMeta != 0 {
canDelete := struct {
Bool bool
String string
}{Bool: false}
2019-09-21 21:03:31 +02:00
deleteToken := getDeleteTokenFromRequest(r)
if deleteToken == "" {
2019-09-21 13:11:38 +02:00
canDelete.String = "undefined"
} else {
if subtle.ConstantTimeCompare([]byte(deleteToken), []byte(p.DeleteToken)) == 1 {
2019-09-21 13:11:38 +02:00
canDelete.Bool = true
canDelete.String = "correct"
} else {
canDelete.String = "invalid"
}
2019-09-01 01:41:01 +02:00
}
2019-09-15 22:54:07 +02:00
data := map[string]interface{}{
"Paste": p,
2019-09-21 13:11:38 +02:00
"CanDelete": canDelete,
2019-09-15 22:54:07 +02:00
}
2019-09-19 21:42:01 +02:00
render(w, r, "pasteMeta", data)
return
2019-08-29 00:50:26 +02:00
}
2019-09-01 01:41:01 +02:00
switch p.State {
2019-09-21 13:11:38 +02:00
case statePresent:
if flags&viewNoRedirect == 0 {
rawurl := string(p.Content)
urlParse, err := url.Parse(rawurl)
if err != nil {
log.Printf("error: invalid URL ('%v') in database for key '%v': %v\n", rawurl, p.Key, err)
2019-09-19 21:42:01 +02:00
renderInternalServerError(w, r, "invalid url in database")
return
}
http.Redirect(w, r, urlParse.String(), http.StatusSeeOther)
}
w.Write(p.Content)
2019-09-21 13:11:38 +02:00
case stateDeleted:
2019-09-21 21:03:31 +02:00
renderError(w, r, http.StatusGone, "paste has been deleted")
2019-08-29 00:50:26 +02:00
default:
log.Printf("error: invalid paste.State (%v) for key '%v'\n", p.State, p.Key)
msg := fmt.Sprintf("internal server error: invalid paste.State (%v\n)", p.State)
2019-09-19 21:42:01 +02:00
renderInternalServerError(w, r, msg)
2019-08-29 00:50:26 +02:00
}
}
2019-09-21 13:11:38 +02:00
func newPasteHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(50 * 1000 * 1000); err != nil {
log.Printf("error: %v\n", err)
renderInternalServerError(w, r, err)
return
}
// Determine what kind of post this is, currently only `shorten=...`
if len(r.PostForm) == 0 {
renderError(w, r, http.StatusBadRequest, "empty body in POST request\n")
return
}
shorten_values, prs := r.PostForm["shorten"]
if !prs {
renderError(w, r, http.StatusBadRequest, "no 'shorten' param given\n")
return
}
if len(shorten_values) != 1 {
renderError(w, r, http.StatusBadRequest, "only one 'shorten' param is allowed per request\n")
return
}
newRedirectPasteHandler(w, r)
}
func newRedirectPasteHandler(w http.ResponseWriter, r *http.Request) {
2019-08-25 21:33:56 +02:00
rawurl := r.PostForm.Get("shorten")
userURL, err := url.ParseRequestURI(rawurl)
if err != nil {
2019-09-15 21:34:41 +02:00
msg := fmt.Sprintf("invalid url (%v): %v", err, rawurl)
2019-09-19 21:42:01 +02:00
renderError(w, r, http.StatusBadRequest, msg)
2019-08-25 21:33:56 +02:00
return
}
if userURL.Scheme == "" {
2019-09-19 21:42:01 +02:00
renderError(w, r, http.StatusBadRequest, "invalid url (unspecified scheme)")
2019-08-25 21:33:56 +02:00
return
}
if userURL.Host == "" {
2019-09-19 21:42:01 +02:00
renderError(w, r, http.StatusBadRequest, "invalid url (unspecified host)")
2019-08-25 21:33:56 +02:00
return
}
var paste *paste
if err := db.DB.Update(func(tx *bolt.Tx) error {
2019-09-21 13:11:38 +02:00
// Generate a new delete token for this paste
2019-09-21 21:03:31 +02:00
var err error
paste, err = shortenURL(tx, userURL)
2019-08-25 21:33:56 +02:00
return err
}); err != nil {
2019-08-29 00:50:26 +02:00
log.Printf("error: %v\n", err)
2019-09-19 21:42:01 +02:00
renderInternalServerError(w, r, err)
2019-08-25 21:33:56 +02:00
return
}
data := map[string]interface{}{"Paste": paste}
2019-09-21 21:03:31 +02:00
render(w, r, "newRedirectPasteSuccess", data)
2019-09-21 13:11:38 +02:00
}
// Delete a URL from the database
func deletePasteHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["key"]
2019-09-21 21:03:31 +02:00
deleteToken := getDeleteTokenFromRequest(r)
if deleteToken == "" {
2019-09-21 13:11:38 +02:00
renderError(w, r, http.StatusBadRequest, "no delete token provided")
return
}
var errorCode int
if err := db.DB.Update(func(tx *bolt.Tx) error {
p, err := getPaste(tx, key)
2019-09-21 13:11:38 +02:00
if err != nil {
errorCode = http.StatusNotFound
return err
}
if subtle.ConstantTimeCompare([]byte(deleteToken), []byte(p.DeleteToken)) == 1 {
p.delete(tx)
2019-09-21 13:11:38 +02:00
}
errorCode = http.StatusForbidden
return errors.New("invalid delete token")
}); err != nil {
log.Printf("error: %v\n", err)
renderError(w, r, errorCode, fmt.Sprintf("error: %v", err))
return
}
2019-08-29 00:50:26 +02:00
}
2019-08-25 21:33:56 +02:00
// Add a new URL to the database
//
// Returns the new ID if the url was successfully shortened
func shortenURL(tx *bolt.Tx, userURL *url.URL) (*paste, error) {
pasteKey, err := generatePasteKey(tx)
if err != nil {
return nil, errors.Wrap(err, "generating paste key")
2019-08-25 21:33:56 +02:00
}
2019-09-21 21:03:31 +02:00
// Also generate a deleteToken
deleteToken, err := generateDeleteToken()
if err != nil {
return nil, errors.Wrap(err, "generating delete token")
}
2019-08-25 21:33:56 +02:00
// Store the new key
p := paste{
2019-09-21 13:11:38 +02:00
Type: typeRedirect,
State: statePresent,
Content: []byte(userURL.String()),
Key: pasteKey,
2019-09-21 13:11:38 +02:00
DeleteToken: deleteToken,
2019-08-25 21:33:56 +02:00
TimeCreated: time.Now().UTC(),
}
if err := p.save(tx); err != nil {
2019-09-21 13:11:38 +02:00
return nil, err
}
return &p, nil
2019-09-01 01:41:01 +02:00
}
2019-09-21 21:03:31 +02:00
func getDeleteTokenFromRequest(r *http.Request) string {
return r.URL.Query().Get("deleteToken")
2019-09-01 01:41:01 +02:00
}