You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.0 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
func main() {
http.HandleFunc("/check-maths-user", CheckMathsUserHandler)
port := ":8080"
fmt.Printf("Listening on port %s...\n", port)
http.ListenAndServe(port, nil)
}
func CheckMathsUserHandler(w http.ResponseWriter, r *http.Request) {
// Get the SANITIZED_USER from the query parameters
sanitizedUser := r.URL.Query().Get("SANITIZED_USER")
// Get the AUTHORIZATION header value, which should include the secret token
authHeader := r.Header.Get("Authorization")
expectedAuthHeader := "Bearer " + os.Getenv("SECRET")
// Check if the provided authorization header matches the expected secret token
if authHeader != expectedAuthHeader {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Get the AUTHPDS_TOKEN from an environment variable
authPdsToken := os.Getenv("AUTHPDS_TOKEN")
// Make a GET request to the external API
apiURL := fmt.Sprintf("https://api.unipi.it/authPds/api/Carriera/studente/uid/%s/", sanitizedUser)
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req.Header.Add("accept", "*/*")
req.Header.Add("Authorization", "Bearer "+authPdsToken)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
// Check if the response contains the desired keywords
body := make([]byte, 0)
_, err = resp.Body.Read(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
containsKeywords := false
keywords := []string{"MATEMATICA", "Mobilit", "Transizione"}
for _, keyword := range keywords {
if strings.Contains(string(body), keyword) {
containsKeywords = true
break
}
}
// Create a JSON response
response := map[string]bool{
"result": containsKeywords,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}