Skip to content

Commit

Permalink
url encode session cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremy5189 committed Nov 22, 2023
1 parent 4fbbbad commit 8214b1c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ banjax
*.tmp
tmp
logs

keys
13 changes: 8 additions & 5 deletions internal/session_cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"fmt"
"log"
"math/rand"
"net/url"
"strconv"
"strings"
"time"
Expand All @@ -25,7 +26,7 @@ import (
)

const (
CookieName = "deflect_session"
SessionCookieName = "deflect_session"
ExpireTimeByteLength = 8
IdByteLength = 4
HmacByteLength = 4
Expand Down Expand Up @@ -118,15 +119,16 @@ func sessionCookieEndPoint(c *gin.Context, config *Config) error {
set in the logs: dsc=cookie, dsc_new=False
*/
clientIp := c.Request.Header.Get("X-Client-IP")
dsc, err := c.Cookie(CookieName)
dsc, err := c.Cookie(SessionCookieName)
urlDecodedDsc, _ := url.QueryUnescape(dsc)

if err == nil {
// cookie exists, validate it
validateErr := validateSessionCookie(dsc, config.SessionCookieHmacSecret, time.Now(), clientIp)
validateErr := validateSessionCookie(urlDecodedDsc, config.SessionCookieHmacSecret, time.Now(), clientIp)
if validateErr == nil {
// cookie is valid, do not attach cookie but only report dsc_new=false
// fmt.Printf("DSC: [%s] cookie %s is valid, report dsc_new=false\n", clientIp, dsc)
attachSessionCookie(c, config, dsc, false)
attachSessionCookie(c, config, urlDecodedDsc, false)
} else {
// cookie is invalid, create a new one
newDsc := newSessionCookie(config.SessionCookieHmacSecret, config.SessionCookieTtlSeconds, clientIp)
Expand All @@ -145,7 +147,8 @@ func sessionCookieEndPoint(c *gin.Context, config *Config) error {

func attachSessionCookie(c *gin.Context, config *Config, dsc string, dsc_new bool) {
if dsc_new {
c.SetCookie(CookieName, dsc, config.SessionCookieTtlSeconds, "/", "", false, true)
urlEncodedDsc := url.QueryEscape(dsc)
c.SetCookie(SessionCookieName, urlEncodedDsc, config.SessionCookieTtlSeconds, "/", "", false, true)
}
// for nginx log
c.Header("X-Deflect-Session", dsc)
Expand Down

0 comments on commit 8214b1c

Please sign in to comment.