You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.0 KiB

  1. package Auth
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "net/http"
  6. "net/http/httptest"
  7. "os"
  8. "path"
  9. "runtime"
  10. "strings"
  11. "testing"
  12. "time"
  13. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
  14. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  15. "github.com/gorilla/mux"
  16. )
  17. var (
  18. r *mux.Router
  19. letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  20. )
  21. func init() {
  22. // Fix working directory for tests
  23. _, filename, _, _ := runtime.Caller(0)
  24. dir := path.Join(path.Dir(filename), "..")
  25. err := os.Chdir(dir)
  26. if err != nil {
  27. panic(err)
  28. }
  29. Database.InitTest()
  30. r = mux.NewRouter()
  31. }
  32. func randString(n int) string {
  33. b := make([]rune, n)
  34. for i := range b {
  35. b[i] = letterRunes[rand.Intn(len(letterRunes))]
  36. }
  37. return string(b)
  38. }
  39. func createTestUser(random bool) (Models.User, error) {
  40. now := time.Now()
  41. email := "email@email.com"
  42. if random {
  43. email = fmt.Sprintf("%s@email.com", randString(16))
  44. }
  45. password, err := HashPassword("password")
  46. if err != nil {
  47. return Models.User{}, err
  48. }
  49. userData := Models.User{
  50. Email: email,
  51. Password: password,
  52. LastLogin: &now,
  53. FirstName: "Hugh",
  54. LastName: "Mann",
  55. }
  56. err = Database.CreateUser(&userData)
  57. return userData, err
  58. }
  59. func Test_Login(t *testing.T) {
  60. t.Log("Testing Login...")
  61. r.HandleFunc("/admin/login", Login).Methods("POST")
  62. ts := httptest.NewServer(r)
  63. defer ts.Close()
  64. userData, err := createTestUser(true)
  65. if err != nil {
  66. t.Errorf("Expected nil, recieved %s", err.Error())
  67. t.FailNow()
  68. }
  69. postJson := `
  70. {
  71. "email": "%s",
  72. "password": "password"
  73. }
  74. `
  75. postJson = fmt.Sprintf(postJson, userData.Email)
  76. res, err := http.Post(ts.URL+"/admin/login", "application/json", strings.NewReader(postJson))
  77. if err != nil {
  78. t.Errorf("Expected nil, recieved %s", err.Error())
  79. return
  80. }
  81. if res.StatusCode != http.StatusOK {
  82. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  83. return
  84. }
  85. if len(res.Cookies()) != 1 {
  86. t.Errorf("Expected cookies len 1, recieved %d", len(res.Cookies()))
  87. return
  88. }
  89. }