-
Notifications
You must be signed in to change notification settings - Fork 0
/
callback_endpoint.go
97 lines (83 loc) · 2.47 KB
/
callback_endpoint.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
package oidc
import (
"context"
"embed"
"fmt"
"html/template"
"net"
"net/http"
"os"
"time"
)
//go:embed html/*
var content embed.FS
type callbackEndpoint struct {
server *http.Server
code string
errorMsg string
errorDescription string
shutdownSignal chan string
}
func (h *callbackEndpoint) start(addr, path string) {
h.shutdownSignal = make(chan string)
server := &http.Server{
Addr: addr,
Handler: nil,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
h.server = server
http.Handle(path, h)
ln, err := net.Listen("tcp", server.Addr)
if err != nil {
fmt.Fprintf(os.Stderr, "cannot listen on callback endpoint, port not available %s\n", server.Addr)
os.Exit(1)
}
ln.Close()
go func() {
server.ListenAndServe()
}()
fmt.Fprintf(os.Stderr, "started http server for callback endpoint %s%s\n", server.Addr, path)
}
func (h *callbackEndpoint) stop() {
h.server.Shutdown(context.Background())
}
func (h *callbackEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(os.Stderr, "receiving callback: %s\n", r.URL.String())
h.code = r.URL.Query().Get("code")
h.errorDescription = r.URL.Query().Get("error_description")
h.errorMsg = r.URL.Query().Get("error")
if h.code != "" {
h.renderSuccess(w)
} else {
h.renderError(w)
}
h.shutdownSignal <- "shutdown"
}
func (h *callbackEndpoint) renderError(w http.ResponseWriter) {
tmpl, err := template.ParseFS(content, "html/callback-error.html")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
fmt.Fprintf(os.Stderr, "error parsing error template: %v\n", err)
return
}
if err := tmpl.Execute(w, map[string]string{"errorMsg": h.errorMsg, "errorDescription": h.errorDescription}); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
fmt.Fprintf(os.Stderr, "error executing error template: %v\n", err)
return
}
}
func (h *callbackEndpoint) renderSuccess(w http.ResponseWriter) {
tmpl, err := template.ParseFS(content, "html/callback-success.html")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
fmt.Fprintf(os.Stderr, "error parsing success template: %v\n", err)
return
}
if err := tmpl.Execute(w, nil); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
fmt.Fprintf(os.Stderr, "error executing success template: %v\n", err)
return
}
}