69 lines
1.5 KiB
Go
Raw Normal View History

2024-08-17 18:21:56 +02:00
package frontend
import (
"encoding/json"
2024-08-17 18:21:56 +02:00
"log"
"net/http"
"os"
2024-08-17 18:21:56 +02:00
b "streifling.com/jason/cpolis/cmd/backend"
)
func tokenIsVerified(w http.ResponseWriter, r *http.Request) bool {
idToken := r.Header.Get("Authorization")
if idToken == "" {
2024-08-17 20:18:53 +02:00
log.Println("Authorization header missing")
http.Error(w, "Authorization header missing", http.StatusUnauthorized)
2024-08-17 20:18:53 +02:00
return false
}
2024-08-17 18:21:56 +02:00
client, err := b.NewClient()
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
2024-08-17 18:21:56 +02:00
_, err = client.Verify(idToken)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusUnauthorized)
return false
}
2024-08-17 18:21:56 +02:00
return true
}
func ServePDFList(c *b.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if tokenIsVerified(w, r) {
files, err := os.ReadDir(c.PDFDir)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fileNames := make([]string, 0)
for _, file := range files {
fileNames = append(fileNames, file.Name())
}
w.Header().Set("Content-Type", "application/json")
if err = json.NewEncoder(w).Encode(fileNames); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-08-17 18:21:56 +02:00
}
}
}
2024-08-17 18:21:56 +02:00
func ServePDF(c *b.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if tokenIsVerified(w, r) {
http.ServeFile(w, r, r.PathValue("id"))
2024-08-17 18:21:56 +02:00
}
}
}