-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponentsRequest.go
More file actions
87 lines (72 loc) · 2.13 KB
/
componentsRequest.go
File metadata and controls
87 lines (72 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"html"
"github.com/SUASecLab/workadventure_admin_extensions/extensions"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func handleComponentsRequest(w http.ResponseWriter, r *http.Request) {
// CORS and MIME type
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "text/plain")
// Get workplace number
variables := mux.Vars(r)
nr := variables["nr"]
// Get user ID
userToken := r.URL.Query().Get("token")
// escape input
nr = html.EscapeString(nr)
userToken = html.EscapeString(userToken)
// Find out if user is allowed to receive workplace information
decision, err := extensions.GetAuthDecision("http://" + sidecarUrl +
"/auth?token=" + userToken + "&service=showComponents")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
errorMsg := "Could not receive authentication decision"
log.Println(errorMsg, err)
fmt.Fprintf(w, "%s", errorMsg)
return
}
if !decision.Allowed {
w.WriteHeader(http.StatusForbidden)
errorMsg := "You are not allowed to access the components information"
log.Println(errorMsg)
fmt.Fprintf(w, "%s", errorMsg)
return
}
// Get workplace description
nrVal, err := strconv.Atoi(nr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid workplace number")
log.Println("Could not convert workplace to number")
return
}
ctx, cancel, client, collection, success := connectToCollection(w)
defer cancel()
defer client.Disconnect(ctx)
if !success {
w.WriteHeader(http.StatusInternalServerError)
log.Println("Could not connect to collection")
return
}
var result bson.M
err = collection.FindOne(ctx, bson.D{{Key: "nr", Value: nrVal}}).Decode(&result)
if err != nil {
if err == mongo.ErrNoDocuments {
fmt.Fprintln(w, "No information stored")
} else {
w.WriteHeader(http.StatusInternalServerError)
log.Println("Could not fetch document:", err)
fmt.Fprintf(w, "An error occured while fetching the document")
}
} else {
// We found the document
fmt.Fprintf(w, "%v", result["components"])
}
}