auth_test.go 3.4 KB

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