Skip to content

Commit

Permalink
Fetch banned IPs from db
Browse files Browse the repository at this point in the history
  • Loading branch information
ezynda3 committed Sep 25, 2024
1 parent 0ad817c commit c4e87ff
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 11 deletions.
24 changes: 13 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,16 +91,6 @@ type SourcifyResponse struct {
Version int `json:"version"`
}

var (
bannedIPs = map[string]bool{
"104.154.76.147": true,
"34.122.246.162": true,
"34.45.228.219": true,
"35.193.6.125": true,
"34.122.96.134": true,
}
)

func main() {
godotenv.Load()
sentry.Init(sentry.ClientOptions{
Expand All @@ -110,6 +100,15 @@ func main() {

app := pocketbase.New()

// loosely check if it was executed using "go run"
isGoRun := strings.HasPrefix(os.Args[0], os.TempDir())

migratecmd.MustRegister(app, app.RootCmd, &migratecmd.Options{
// enable auto creation of migration files when making collection changes in the Admin UI
// (the isGoRun check is to enable it only during development)
Automigrate: isGoRun,
})

app.OnBeforeServe().Add(func(e *core.ServeEvent) error {

e.Router.GET(
Expand Down Expand Up @@ -152,7 +151,10 @@ func main() {

e.Router.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if _, ok := bannedIPs[c.Request().Header.Get("Fly-Client-IP")]; ok {
ip := c.Request().Header.Get("Fly-Client-IP")
record, err := app.Dao().
FindFirstRecordByData("bannedIPs", "ip", ip)
if err == nil && record.Get("ip") == ip {
return echo.NewHTTPError(http.StatusForbidden)
}
return next(c)
Expand Down
60 changes: 60 additions & 0 deletions migrations/1727272311_created_bannedIPs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package migrations

import (
"encoding/json"

"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)

func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "ggalodjt1jwro34",
"created": "2024-09-25 13:51:51.754Z",
"updated": "2024-09-25 13:51:51.754Z",
"name": "bannedIPs",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "pyv6mkxb",
"name": "ip",
"type": "text",
"required": true,
"unique": true,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}
],
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"options": {}
}`

collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}

return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);

collection, err := dao.FindCollectionByNameOrId("ggalodjt1jwro34")
if err != nil {
return err
}

return dao.DeleteCollection(collection)
})
}

0 comments on commit c4e87ff

Please sign in to comment.