/
result.go
84 lines (72 loc) · 2.09 KB
/
result.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
package webapp
import (
"encoding/json"
"net/http"
"net/url"
"github.com/authgear/authgear-server/pkg/util/httputil"
"github.com/authgear/authgear-server/pkg/util/setutil"
)
type Result struct {
UILocales string `json:"ui_locales,omitempty"`
ColorScheme string `json:"color_scheme,omitempty"`
RedirectURI string `json:"redirect_uri,omitempty"`
NavigationAction string `json:"navigation_action,omitempty"`
Cookies []*http.Cookie `json:"cookies,omitempty"`
IsInteractionErr bool `json:"is_interaction_err,omitempty"`
RemoveQueries setutil.Set[string] `json:"remove_queries,omitempty"`
}
func (r *Result) WriteResponse(w http.ResponseWriter, req *http.Request) {
redirectURI, err := url.Parse(r.RedirectURI)
if err != nil {
panic(err)
}
q := redirectURI.Query()
if r.UILocales != "" {
q.Set("ui_locales", r.UILocales)
}
if r.ColorScheme != "" {
q.Set("x_color_scheme", r.ColorScheme)
}
// Navigate to self. Preserve query.
if redirectURI.Host == "" {
original := PreserveQuery(req.URL.Query())
for key := range original {
_, ignoreKey := r.RemoveQueries[key]
// preserve the query only if it doesn't exist in the new query
if q.Get(key) == "" && !ignoreKey {
q.Set(key, original.Get(key))
}
}
}
redirectURI.RawQuery = q.Encode()
for _, cookie := range r.Cookies {
httputil.UpdateCookie(w, cookie)
}
if req.Header.Get("X-Authgear-XHR") == "true" {
type xhrResponse struct {
RedirectURI string `json:"redirect_uri"`
Action string `json:"action"`
}
action := r.NavigationAction
if action == "" {
action = "advance"
}
data, err := json.Marshal(xhrResponse{
RedirectURI: redirectURI.String(),
Action: action,
})
if err != nil {
http.Error(w, err.Error(), 500)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
if _, err := w.Write(data); err != nil {
panic(err)
}
} else {
http.Redirect(w, req, redirectURI.String(), http.StatusFound)
}
}
func (r *Result) IsInternalError() bool {
return false
}