auth_test.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package auth
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "strings"
  11. "sync"
  12. "testing"
  13. "devt.de/common/httputil"
  14. "devt.de/common/httputil/user"
  15. )
  16. const TESTPORT = ":9090"
  17. const TESTQUERYURL = "http://localhost" + TESTPORT + "/foo"
  18. var handleCallback = func(w http.ResponseWriter, r *http.Request) {}
  19. var originalHandleFunction = func(w http.ResponseWriter, r *http.Request) {
  20. session, _ := user.UserSessionManager.GetSession("", w, r, false)
  21. handleCallback(w, r)
  22. if session == nil {
  23. w.Write([]byte("Content"))
  24. } else {
  25. w.Write([]byte(fmt.Sprint("Content - User session: ", session.User())))
  26. }
  27. }
  28. var wrappedHandleFunction = originalHandleFunction
  29. func TestMain(m *testing.M) {
  30. flag.Parse()
  31. // Create a test file
  32. ioutil.WriteFile("test.jpg", []byte("testpic"), 0777)
  33. // Setup a simple webserver
  34. hs, wg := startServer()
  35. if hs == nil {
  36. return
  37. }
  38. // Make sure the webserver shuts down
  39. defer stopServer(hs, wg)
  40. // Register a simple content delivery function
  41. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  42. // Call the wrapped handle function which then adds the authentication
  43. wrappedHandleFunction(w, r)
  44. })
  45. // Run the tests
  46. res := m.Run()
  47. // Remove test file
  48. os.Remove("test.jpg")
  49. os.Exit(res)
  50. }
  51. func TestNoAuthNoSession(t *testing.T) {
  52. // By default there is no session and no authentication
  53. res, _ := sendTestRequest(TESTQUERYURL, "GET", nil, nil, nil)
  54. if res != "Content" {
  55. t.Error("Unexpected result:", res)
  56. return
  57. }
  58. // Trying to create an anonymous session should fail
  59. r, _ := http.NewRequest("GET", "", nil)
  60. _, err := user.UserSessionManager.GetSession("", nil, r, true)
  61. if err.Error() != "Cannot create a session without a user" {
  62. t.Error("Unexpected error:", err)
  63. return
  64. }
  65. }
  66. /*
  67. Send a request to a HTTP test server
  68. */
  69. func sendTestRequest(url string, method string, headers map[string]string,
  70. cookies []*http.Cookie, content []byte) (string, *http.Response) {
  71. var req *http.Request
  72. var err error
  73. // Create request
  74. if content != nil {
  75. req, err = http.NewRequest(method, url, bytes.NewBuffer(content))
  76. } else {
  77. req, err = http.NewRequest(method, url, nil)
  78. }
  79. // Add headers
  80. req.Header.Set("Content-Type", "application/json")
  81. for k, v := range headers {
  82. req.Header.Set(k, v)
  83. }
  84. // Add cookies
  85. for _, v := range cookies {
  86. req.AddCookie(v)
  87. }
  88. client := &http.Client{}
  89. resp, err := client.Do(req)
  90. if err != nil {
  91. panic(err)
  92. }
  93. defer resp.Body.Close()
  94. body, _ := ioutil.ReadAll(resp.Body)
  95. bodyStr := strings.Trim(string(body), " \n")
  96. // Try json decoding first
  97. out := bytes.Buffer{}
  98. err = json.Indent(&out, []byte(bodyStr), "", " ")
  99. if err == nil {
  100. return out.String(), resp
  101. }
  102. // Just return the body
  103. return bodyStr, resp
  104. }
  105. /*
  106. Start a HTTP test server.
  107. */
  108. func startServer() (*httputil.HTTPServer, *sync.WaitGroup) {
  109. hs := &httputil.HTTPServer{}
  110. var wg sync.WaitGroup
  111. wg.Add(1)
  112. go hs.RunHTTPServer(TESTPORT, &wg)
  113. wg.Wait()
  114. // Server is started
  115. if hs.LastError != nil {
  116. panic(hs.LastError)
  117. }
  118. return hs, &wg
  119. }
  120. /*
  121. Stop a started HTTP test server.
  122. */
  123. func stopServer(hs *httputil.HTTPServer, wg *sync.WaitGroup) {
  124. if hs.Running == true {
  125. wg.Add(1)
  126. // Server is shut down
  127. hs.Shutdown()
  128. wg.Wait()
  129. } else {
  130. panic("Server was not running as expected")
  131. }
  132. }