Skip to content

Commit 70f8710

Browse files
committed
refactor
1 parent abc4e6d commit 70f8710

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed

modules/context/csrf.go

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -172,25 +172,20 @@ func NewCSRFProtector(opt CsrfOptions, ctx *Context) CSRFProtector {
172172
}
173173
}
174174

175-
needsNew := false
176175
oldUID := ctx.Session.Get(opt.oldSessionKey)
177-
if oldUID == nil || oldUID.(string) != x.ID {
178-
needsNew = true
179-
_ = ctx.Session.Set(opt.oldSessionKey, x.ID)
180-
} else {
181-
// If cookie present, map existing token, else generate a new one.
182-
if val := ctx.GetCookie(opt.Cookie); val != "" {
183-
x.Token = val // FIXME: test coverage.
184-
} else {
185-
needsNew = true
186-
}
187-
}
176+
uidChanged := oldUID == nil || oldUID.(string) != x.ID
177+
cookieToken := ctx.GetCookie(opt.Cookie)
188178

189-
if !needsNew {
179+
needsNew := true
180+
if uidChanged {
181+
_ = ctx.Session.Set(opt.oldSessionKey, x.ID)
182+
} else if cookieToken != "" {
183+
// If cookie token presents, re-use existing unexpired token, else generate a new one.
190184
if issueTime, ok := ParseCsrfToken(x.Token); ok {
191185
dur := time.Since(issueTime)
192-
if dur < -CsrfTokenRegenerationDuration || dur > CsrfTokenRegenerationDuration {
193-
needsNew = true
186+
if dur >= -CsrfTokenRegenerationDuration && dur <= CsrfTokenRegenerationDuration {
187+
x.Token = cookieToken
188+
needsNew = false
194189
}
195190
}
196191
}

0 commit comments

Comments
 (0)