Add some very basic authentication

This commit is contained in:
Paul Brinkmeier 2024-07-17 07:42:51 +02:00
parent 3fe42e1ff0
commit 69704a38ae
2 changed files with 13 additions and 1 deletions

View File

@ -4,6 +4,6 @@
- [x] Use timeout for fetching departures - [x] Use timeout for fetching departures
- [ ] Write ESP8266 client - [ ] Write ESP8266 client
- [ ] Add basic auth - [x] Add basic auth
- [ ] Create Nix package - [ ] Create Nix package
- [ ] Create container - [ ] Create container

12
main.go
View File

@ -5,6 +5,7 @@ import "fmt"
import "log" import "log"
import "net/http" import "net/http"
import "net/url" import "net/url"
import "os"
import "slices" import "slices"
import "strconv" import "strconv"
import "time" import "time"
@ -81,7 +82,18 @@ func FetchDepartures(stopId string) (*DMResponse, error) {
} }
func main() { func main() {
password := os.Getenv("VRNP_PASSWORD")
if len(password) == 0 {
panic("Required environment variable VRNP_PASSWORD is not set");
}
http.HandleFunc("/departures", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/departures", func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !(ok && user == "admin" && pass == password) {
http.Error(w, "You shall not pass", http.StatusUnauthorized)
return
}
query := r.URL.Query() query := r.URL.Query()
if query["stop_id"] == nil || len(query["stop_id"]) < 1 { if query["stop_id"] == nil || len(query["stop_id"]) < 1 {