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.

117 lines
2.5 KiB
Go

1 year ago
package main
import (
"encoding/json"
"fmt"
"io"
"log"
1 year ago
"net/http"
"os"
"strings"
"github.com/joho/godotenv"
)
var (
Host string
AuthPDSToken string
Secret string
1 year ago
)
func main() {
godotenv.Load()
if v, present := os.LookupEnv("HOST"); present {
Host = v
} else {
Host = ":8080"
}
if v, present := os.LookupEnv("AUTHPDS_TOKEN"); present {
AuthPDSToken = v
} else {
log.Fatal(`missing AUTHPDS_TOKEN`)
}
1 year ago
if v, present := os.LookupEnv("SECRET"); present {
Secret = v
} else {
log.Fatal(`missing SECRET`)
}
r := http.NewServeMux()
r.HandleFunc("/check-maths-user", checkMathsUserHandler)
log.Printf("Starting server on %s...\n", Host)
http.ListenAndServe(Host, r)
1 year ago
}
func checkMathsUserHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
// Get the username from the query parameters
userName := r.URL.Query().Get("user")
1 year ago
// Check if the provided authorization header matches the expected secret token
if r.Header.Get("Authorization") != "Bearer "+Secret {
1 year ago
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
userApiUrl := fmt.Sprintf("https://api.unipi.it/authPds/api/Carriera/studente/uid/%s/", userName)
1 year ago
// Create a GET request to the external API
ateneoRequest, err := http.NewRequest("GET", userApiUrl, nil)
1 year ago
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ateneoRequest.Header.Add("Accept", "*/*")
ateneoRequest.Header.Add("Authorization", "Bearer "+AuthPDSToken)
1 year ago
// Make the request to the external API
ateneoResponse, err := http.DefaultClient.Do(ateneoRequest)
1 year ago
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer ateneoResponse.Body.Close()
1 year ago
isMatematica, err := checkUtenteDiMatematica(ateneoResponse)
1 year ago
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(
map[string]any{
"result": isMatematica,
},
); err != nil {
log.Printf(`encode error: %v`, err)
return
}
}
func checkUtenteDiMatematica(r *http.Response) (bool, error) {
// Check if the response contains the desired keywords
body, err := io.ReadAll(r.Body)
if err != nil {
return false, err
}
1 year ago
keywords := []string{"MATEMATICA", "Mobilit", "Transizione"}
for _, keyword := range keywords {
if strings.Contains(string(body), keyword) {
return true, nil
1 year ago
}
}
return false, nil
1 year ago
}