Extracted verification logic for frontend into seperate function tokenIsVerified() and created ServePDFListe()

This commit is contained in:
Jason Streifling 2024-08-17 20:15:35 +02:00
parent bebfe994ae
commit 472f00a107

View File

@ -1,15 +1,16 @@
package frontend package frontend
import ( import (
"encoding/json"
"log" "log"
"net/http" "net/http"
"os"
"strings" "strings"
b "streifling.com/jason/cpolis/cmd/backend" b "streifling.com/jason/cpolis/cmd/backend"
) )
func ServePDFs(c *b.Config) http.HandlerFunc { func tokenIsVerified(w http.ResponseWriter, r *http.Request) bool {
return func(w http.ResponseWriter, r *http.Request) {
idToken := r.Header.Get("Authorization") idToken := r.Header.Get("Authorization")
if idToken == "" { if idToken == "" {
http.Error(w, "Authorization header missing", http.StatusUnauthorized) http.Error(w, "Authorization header missing", http.StatusUnauthorized)
@ -19,23 +20,48 @@ func ServePDFs(c *b.Config) http.HandlerFunc {
if err != nil { if err != nil {
log.Println(err) log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return false
} }
_, err = client.Verify(idToken) _, err = client.Verify(idToken)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
http.Error(w, err.Error(), http.StatusUnauthorized) http.Error(w, err.Error(), http.StatusUnauthorized)
return return false
} }
pdfIDsString := r.PathValue("ids") 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 { if err != nil {
log.Println(err) log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return 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 ServePDFs(c *b.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if tokenIsVerified(w, r) {
pdfIDsString := r.PathValue("ids")
pdfIDs := strings.Split(pdfIDsString, ",") pdfIDs := strings.Split(pdfIDsString, ",")
for _, id := range pdfIDs { for _, id := range pdfIDs {
@ -43,3 +69,4 @@ func ServePDFs(c *b.Config) http.HandlerFunc {
} }
} }
} }
}