-
Notifications
You must be signed in to change notification settings - Fork 28
/
success_page_middleware.go
58 lines (50 loc) · 1.73 KB
/
success_page_middleware.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
package webapp
import (
"net/http"
"net/url"
"github.com/authgear/authgear-server/pkg/api/apierrors"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/lib/successpage"
"github.com/authgear/authgear-server/pkg/util/httputil"
)
type SuccessPageMiddlewareEndpointsProvider interface {
ErrorEndpointURL(uiImpl config.UIImplementation) *url.URL
}
type SuccessPageMiddleware struct {
Endpoints SuccessPageMiddlewareEndpointsProvider
UIConfig *config.UIConfig
Cookies CookieManager
ErrorCookie *ErrorCookie
}
func (m *SuccessPageMiddleware) Pop(r *http.Request, rw http.ResponseWriter) string {
cookie, err := m.Cookies.GetCookie(r, successpage.PathCookieDef)
if err != nil {
return ""
}
path := cookie.Value
clearCookie := m.Cookies.ClearCookie(successpage.PathCookieDef)
httputil.UpdateCookie(rw, clearCookie)
return path
}
// SuccessPageMiddleware check the success path cookie to determine
// whether it is valid to visit the success page
// the cookie should be set right before redirecting to the success page
func (m *SuccessPageMiddleware) Handle(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
currentPath := r.URL.Path
pathInCookie := m.Pop(r, w)
if currentPath != pathInCookie {
// Show invalid session error when the path cookie doesn't match
// the current path
apierror := apierrors.AsAPIError(ErrInvalidSession)
errorCookie, err := m.ErrorCookie.SetRecoverableError(r, apierror)
if err != nil {
panic(err)
}
httputil.UpdateCookie(w, errorCookie)
http.Redirect(w, r, m.Endpoints.ErrorEndpointURL(m.UIConfig.Implementation).Path, http.StatusFound)
} else {
next.ServeHTTP(w, r)
}
})
}