feat: add manually managed domain blacklist
Some checks failed
/ test (push) Has been cancelled

This commit is contained in:
ptrcnull 2024-09-06 11:56:58 +02:00
parent 8c8f2f55ef
commit a4b8c8c33f
2 changed files with 31 additions and 1 deletions

View file

@ -9,3 +9,8 @@ Environmental variables:
- `SHORTEN_BIND` - bind address (default: `127.0.0.1:4488`) - `SHORTEN_BIND` - bind address (default: `127.0.0.1:4488`)
- `SHORTEN_MAIL` - optional email for support/abuse reports - `SHORTEN_MAIL` - optional email for support/abuse reports
- `POSTGRES_URI` - lib/pq connection string (see [here](https://pkg.go.dev/github.com/lib/pq#section-documentation)) - `POSTGRES_URI` - lib/pq connection string (see [here](https://pkg.go.dev/github.com/lib/pq#section-documentation))
### Maintenance
shorten supports a domain blacklist to ban certain domains (e.g. spam, malware, etc.);
you can use it by connecting to the database and inserting rows into the `blacklist` table.

27
main.go
View file

@ -7,6 +7,7 @@ import (
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
neturl "net/url"
"os" "os"
"strings" "strings"
"time" "time"
@ -71,6 +72,13 @@ func main() {
panic(err) panic(err)
} }
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS blacklist (
domain text not null
);`)
if err != nil {
panic(err)
}
bind := os.Getenv("SHORTEN_BIND") bind := os.Getenv("SHORTEN_BIND")
if bind == "" { if bind == "" {
bind = "127.0.0.1:4488" bind = "127.0.0.1:4488"
@ -167,8 +175,25 @@ func (h *Handler) GetCode(url string, ip string) (string, error) {
return "", fmt.Errorf("invalid URL") return "", fmt.Errorf("invalid URL")
} }
parsed, err := neturl.Parse(url)
if err != nil {
return "", fmt.Errorf("invalid URL")
}
hostname := parsed.Hostname()
// tbh we don't care about the value here but why not
var res string
err = h.db.QueryRow(`SELECT domain FROM blacklist WHERE domain = $1`, hostname).Scan(&res)
if err != sql.ErrNoRows {
if err != nil {
log.Println("sql error:", err)
return "", fmt.Errorf("query: %w", err)
}
return "", fmt.Errorf("invalid URL")
}
var code string var code string
err := h.db.QueryRow(`SELECT code FROM urls WHERE url = $1 LIMIT 1`, url).Scan(&code) err = h.db.QueryRow(`SELECT code FROM urls WHERE url = $1 LIMIT 1`, url).Scan(&code)
if err == nil { if err == nil {
return code, nil return code, nil
} }