session_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package session
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/database/model"
  7. "github.com/gin-contrib/sessions"
  8. "github.com/gin-contrib/sessions/cookie"
  9. "github.com/gin-gonic/gin"
  10. )
  11. func TestSetLoginUserStoresOnlyUserID(t *testing.T) {
  12. gin.SetMode(gin.TestMode)
  13. router := gin.New()
  14. router.Use(sessions.Sessions(sessionCookieName, cookie.NewStore([]byte("01234567890123456789012345678901"))))
  15. router.GET("/", func(c *gin.Context) {
  16. if err := SetLoginUser(c, &model.User{Id: 7, Username: "admin", Password: "hash"}); err != nil {
  17. t.Fatal(err)
  18. }
  19. got := sessions.Default(c).Get(loginUserKey)
  20. if got != 7 {
  21. t.Fatalf("stored session payload = %#v, want user id only", got)
  22. }
  23. c.Status(http.StatusNoContent)
  24. })
  25. rec := httptest.NewRecorder()
  26. req := httptest.NewRequest(http.MethodGet, "/", nil)
  27. router.ServeHTTP(rec, req)
  28. if rec.Code != http.StatusNoContent {
  29. t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
  30. }
  31. }
  32. func TestSessionUserIDSupportsLegacyUserPayload(t *testing.T) {
  33. id, ok := sessionUserID(model.User{Id: 11, Username: "admin", Password: "hash"})
  34. if !ok || id != 11 {
  35. t.Fatalf("legacy session payload resolved to (%d, %v), want (11, true)", id, ok)
  36. }
  37. id, ok = sessionUserID(&model.User{Id: 12, Username: "admin", Password: "hash"})
  38. if !ok || id != 12 {
  39. t.Fatalf("legacy pointer session payload resolved to (%d, %v), want (12, true)", id, ok)
  40. }
  41. }