File tree 3 files changed +29
-6
lines changed
3 files changed +29
-6
lines changed Original file line number Diff line number Diff line change 1
1
// events are used by pages/components packages.
2
2
package events
3
3
4
- import "github.com/ItsNotGoodName/smtpbridge/pkg/htmx"
4
+ import (
5
+ "fmt"
6
+
7
+ "github.com/ItsNotGoodName/smtpbridge/pkg/htmx"
8
+ )
5
9
6
10
const (
7
11
EnvelopeCreated htmx.Event = "envelope-created"
8
12
RetentionPolicyRun htmx.Event = "retention-policy-run"
9
13
)
14
+
15
+ func CSRFToken (csrfToken string ) htmx.Event {
16
+ return htmx .Event (fmt .Sprintf (`{ "csrfToken": "%s" }` , csrfToken ))
17
+ }
Original file line number Diff line number Diff line change 9
9
"github.com/ItsNotGoodName/smtpbridge/internal/core"
10
10
"github.com/ItsNotGoodName/smtpbridge/web"
11
11
c "github.com/ItsNotGoodName/smtpbridge/web/components"
12
+ "github.com/ItsNotGoodName/smtpbridge/web/events"
12
13
"github.com/ItsNotGoodName/smtpbridge/web/meta"
13
14
"github.com/ItsNotGoodName/smtpbridge/web/routes"
14
15
"github.com/a-h/templ"
@@ -54,10 +55,15 @@ func (ct Controller) Meta(r *http.Request) meta.Meta {
54
55
55
56
func (ct Controller ) Page (w http.ResponseWriter , r * http.Request , body templ.Component ) {
56
57
csrfToken := csrf .Token (r )
58
+ events .CSRFToken (csrfToken ).SetTrigger (w )
59
+
57
60
c .Base (ct .head , body , csrfToken ).Render (r .Context (), w )
58
61
}
59
62
60
63
func (ct Controller ) Component (w http.ResponseWriter , r * http.Request , body templ.Component ) {
64
+ csrfToken := csrf .Token (r )
65
+ events .CSRFToken (csrfToken ).SetTrigger (w )
66
+
61
67
body .Render (r .Context (), w )
62
68
}
63
69
Original file line number Diff line number Diff line change @@ -4,11 +4,20 @@ import "./index.css"
4
4
5
5
import "htmx.org"
6
6
7
- const csrfToken = ( document . getElementsByName ( "gorilla.csrf.Token" ) . item ( 0 ) as HTMLMetaElement ) . content
8
-
9
- document . body . addEventListener ( 'htmx:configRequest' , function ( evt : any ) {
10
- evt . detail . headers [ 'X-CSRF-Token' ] = csrfToken ;
11
- } ) ;
7
+ // csrfToken is first loaded from meta tag and then is updated through HX-Trigger HTTP response headers.
8
+ // This allows HX-Boost to happen without invalidating previous csrfToken.
9
+ {
10
+ let csrfToken = ( document . getElementsByName ( "gorilla.csrf.Token" ) . item ( 0 ) as HTMLMetaElement ) . content
11
+
12
+ document . body . addEventListener ( "csrfToken" , function ( evt : any ) {
13
+ csrfToken = evt . detail . value
14
+ } )
15
+
16
+ document . body . addEventListener ( 'htmx:configRequest' , function ( evt : any ) {
17
+ // TODO: why can't I use console.log here?
18
+ evt . detail . headers [ 'X-CSRF-Token' ] = csrfToken ;
19
+ } ) ;
20
+ }
12
21
13
22
// ------------- Toastify
14
23
You can’t perform that action at this time.
0 commit comments