-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
115 lines (100 loc) · 2.51 KB
/
server.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/pkg/errors"
)
func samlSuccessHTML(redirectURL string) string {
var redirectHTML string
var message string = "You can close this now"
if redirectURL != "" {
redirectHTML = fmt.Sprintf(`
<meta http-equiv="refresh" content="5; url=%s" />`, redirectURL)
message = fmt.Sprintf("Redirecting you to %s...", redirectURL)
}
return fmt.Sprintf(`
<html>
<head>
<title>SamlVPN</title>
%s
</head>
<body>
<h2>Got SAML response!</h2>
<p>%s</p>
<br>
<small>
Thank you for using <a href="github.com/donotnoot/samlvpn">SamlVPN</a>!
</small>
</body>
</html>`, redirectHTML, message)
}
type Server struct {
httpServer *http.Server
response chan string
timeout time.Duration
}
func NewServer(address, redirectURL string, timeout time.Duration) *Server {
response := make(chan string)
return &Server{
timeout: timeout,
response: response,
httpServer: &http.Server{
Addr: address,
ReadTimeout: time.Second,
IdleTimeout: time.Second,
WriteTimeout: time.Second,
ReadHeaderTimeout: time.Second,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("handling HTTP request", r.Method, r.URL)
defer r.Body.Close()
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("hey there! you might want to try POST"))
return
}
if err := r.ParseForm(); err != nil {
err := errors.Wrap(err, "could not parse SAML form data")
log.Println(err)
writeError(w, err)
return
}
samlResponse := r.FormValue("SAMLResponse")
if len(samlResponse) == 0 {
err := fmt.Errorf("SAMLResponse from field has zero length")
log.Println(err)
writeError(w, err)
return
}
response <- samlResponse
w.WriteHeader(200)
w.Write([]byte(samlSuccessHTML(redirectURL)))
}),
},
}
}
func writeError(w http.ResponseWriter, err error) {
w.WriteHeader(500)
w.Write([]byte(fmt.Sprint(err)))
}
func (s *Server) Start() {
go func() {
if err := s.httpServer.ListenAndServe(); err != nil {
log.Println(err)
}
}()
}
func (s *Server) WaitForResponse() (string, error) {
defer func() {
if err := s.httpServer.Close(); err != nil {
log.Fatal(errors.Wrap(err, "could not close server"))
}
}()
select {
case response := <-s.response:
return response, nil
case <-time.After(s.timeout):
return "", fmt.Errorf("timed out waiting for response after %v", s.timeout)
}
}