69 lines
1.5 KiB
Go

package frontend
import (
"encoding/json"
"log"
"net/http"
"os"
b "streifling.com/jason/cpolis/cmd/backend"
)
func tokenIsVerified(w http.ResponseWriter, r *http.Request) bool {
idToken := r.Header.Get("Authorization")
if idToken == "" {
log.Println("Authorization header missing")
http.Error(w, "Authorization header missing", http.StatusUnauthorized)
return false
}
client, err := b.NewClient()
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
_, err = client.Verify(idToken)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusUnauthorized)
return false
}
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
}
}
}
}
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"))
}
}
}