1
0
Fork 0
forked from jriou/coller

feat: Add password protection

Fixes #37.

BREAKING CHANGE: API routes are prefixed by /api/note.

Signed-off-by: Julien Riou <julien@riou.xyz>
This commit is contained in:
Julien Riou 2025-09-27 08:35:26 +02:00
commit 9e0254c0b5
Signed by: jriou
GPG key ID: 9A099EDA51316854
16 changed files with 713 additions and 135 deletions

View file

@ -1,11 +1,14 @@
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"syscall"
@ -21,6 +24,10 @@ var (
GitCommit string
)
type NotePayload struct {
Password string `json:"password"`
}
func handleMain() int {
flag.Usage = usage
@ -34,6 +41,7 @@ func handleMain() int {
fileName := flag.String("file", "", "Write content of the note to a file")
bearer := flag.String("bearer", os.Getenv("COLLER_BEARER"), "Bearer token")
askBearer := flag.Bool("ask-bearer", false, "Read bearer token from input")
password := flag.String("password", os.Getenv("COLLER_PASSWORD"), "Password to access the note")
flag.Parse()
@ -47,7 +55,7 @@ func handleMain() int {
return internal.RC_ERROR
}
url := flag.Args()[0]
rawURL := flag.Args()[0]
var level slog.Level
if *debug {
@ -81,21 +89,50 @@ func handleMain() int {
fmt.Print("\n")
}
logger.Debug("creating http request")
req, err := http.NewRequest("GET", url, nil)
logger.Debug("parsing url", slog.Any("url", rawURL))
u, err := url.Parse(rawURL)
if err != nil {
return internal.ReturnError(logger, "could not create request", err)
return internal.ReturnError(logger, "could not parse url", err)
}
u.Path = "api/note" + u.Path
rawURL = u.String()
logger.Debug("creating http request")
var req *http.Request
if *password != "" {
body := &NotePayload{
Password: *password,
}
payload, err := json.Marshal(body)
if err != nil {
return internal.ReturnError(logger, "could not create note payload", err)
}
req, err = http.NewRequest("POST", rawURL, bytes.NewBuffer(payload))
if err != nil {
return internal.ReturnError(logger, "could not create request", err)
}
} else {
req, err = http.NewRequest("GET", rawURL, nil)
if err != nil {
return internal.ReturnError(logger, "could not create request", err)
}
}
if *bearer != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *bearer))
}
logger.Debug("parsing url", slog.Any("url", url))
logger.Debug("executing http request", slog.Any("method", req.Method), slog.Any("url", rawURL))
r, err := http.DefaultClient.Do(req)
if err != nil {
return internal.ReturnError(logger, "could not retreive note", err)
}
if r.StatusCode >= 300 {
return internal.ReturnError(logger, "could not retreive note", fmt.Errorf("status code %d", r.StatusCode))
}
logger.Debug("decoding body")
body, err := io.ReadAll(r.Body)
if err != nil {