forked from play-with-docker/play-with-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayground.go
94 lines (79 loc) · 2.58 KB
/
playground.go
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
88
89
90
91
92
93
94
package handlers
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/play-with-docker/play-with-docker/config"
"github.com/play-with-docker/play-with-docker/pwd/types"
)
func NewPlayground(rw http.ResponseWriter, req *http.Request) {
if !ValidateToken(req) {
rw.WriteHeader(http.StatusForbidden)
return
}
var playground types.Playground
err := json.NewDecoder(req.Body).Decode(&playground)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "Error creating playground. Got: %v", err)
return
}
newPlayground, err := core.PlaygroundNew(playground)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "Error creating playground. Got: %v", err)
return
}
json.NewEncoder(rw).Encode(newPlayground)
}
func ListPlaygrounds(rw http.ResponseWriter, req *http.Request) {
if !ValidateToken(req) {
rw.WriteHeader(http.StatusForbidden)
return
}
playgrounds, err := core.PlaygroundList()
if err != nil {
log.Printf("Error listing playgrounds. Got: %v\n", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
json.NewEncoder(rw).Encode(playgrounds)
}
type PlaygroundConfigurationResponse struct {
Id string `json:"id"`
Domain string `json:"domain"`
DefaultDinDInstanceImage string `json:"default_dind_instance_image"`
AvailableDinDInstanceImages []string `json:"available_dind_instance_images"`
AllowWindowsInstances bool `json:"allow_windows_instances"`
DefaultSessionDuration time.Duration `json:"default_session_duration"`
DindVolumeSize string `json:"dind_volume_size"`
}
func GetCurrentPlayground(rw http.ResponseWriter, req *http.Request) {
playground := core.PlaygroundFindByDomain(req.Host)
if playground == nil {
log.Printf("Playground for domain %s was not found!", req.Host)
rw.WriteHeader(http.StatusBadRequest)
return
}
json.NewEncoder(rw).Encode(PlaygroundConfigurationResponse{
Id: playground.Id,
Domain: playground.Domain,
DefaultDinDInstanceImage: playground.DefaultDinDInstanceImage,
AvailableDinDInstanceImages: playground.AvailableDinDInstanceImages,
AllowWindowsInstances: playground.AllowWindowsInstances,
DefaultSessionDuration: playground.DefaultSessionDuration,
DindVolumeSize: playground.DindVolumeSize,
})
}
func ValidateToken(req *http.Request) bool {
_, password, ok := req.BasicAuth()
if !ok {
return false
}
if password != config.AdminToken {
return false
}
return true
}