user_test.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "sync"
  9. "testing"
  10. "time"
  11. controller "github.com/gravitl/netmaker/controllers"
  12. "github.com/gravitl/netmaker/models"
  13. "github.com/gravitl/netmaker/mongoconn"
  14. "github.com/stretchr/testify/assert"
  15. )
  16. //change this --- there is an existing type
  17. type AuthorizationResponse struct {
  18. Username string
  19. AuthToken string
  20. }
  21. type goodResponse struct {
  22. Code int
  23. Message string
  24. Response AuthorizationResponse
  25. }
  26. type badResponse struct {
  27. Code int
  28. Message string
  29. }
  30. type AuthorizeTestCase struct {
  31. testname string
  32. name string
  33. password string
  34. code int
  35. tokenExpected bool
  36. errMessage string
  37. }
  38. func TestMain(m *testing.M) {
  39. mongoconn.ConnectDatabase()
  40. var waitgroup sync.WaitGroup
  41. waitgroup.Add(1)
  42. go controller.HandleRESTRequests(&waitgroup)
  43. //wait for http server to start
  44. time.Sleep(time.Second * 1)
  45. os.Exit(m.Run())
  46. }
  47. func TestUsers(t *testing.T) {
  48. // t.Run("check that admin user does not exist", func(t *testing.T) {
  49. // response := checkAdminExists(t)
  50. // assert.Equal(t, false, response)
  51. // })
  52. t.Run("Admin Creation", func(t *testing.T) {
  53. var admin, user models.User
  54. admin.UserName = "admin"
  55. admin.Password = "password"
  56. if !adminExists(t) {
  57. t.Run("AdminCreationValid", func(t *testing.T) {
  58. response, err := api(admin, http.MethodPost, "http://localhost:8081/users/createadmin", "")
  59. if err != nil {
  60. t.Error("error calling createadmin", err)
  61. }
  62. defer response.Body.Close()
  63. json.NewDecoder(response.Body).Decode(&user)
  64. assert.Equal(t, admin.UserName, user.UserName)
  65. assert.Equal(t, true, user.IsAdmin)
  66. assert.Equal(t, http.StatusOK, response.StatusCode)
  67. assert.True(t, adminExists(t), "Admin creation failed")
  68. })
  69. t.Run("AdminCreationInvalid", func(t *testing.T) {
  70. response, err := api(admin, http.MethodPost, "http://localhost:8081/users/createadmin", "")
  71. if err != nil {
  72. t.Error("error calling createadmin", err)
  73. }
  74. defer response.Body.Close()
  75. var message badResponse
  76. json.NewDecoder(response.Body).Decode(&message)
  77. assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
  78. assert.Equal(t, http.StatusUnauthorized, message.Code)
  79. assert.Equal(t, "W1R3: Admin already exists! ", message.Message)
  80. })
  81. } else {
  82. t.Run("AdminCreationInvalid", func(t *testing.T) {
  83. response, err := api(admin, http.MethodPost, "http://localhost:8081/users/createadmin", "")
  84. if err != nil {
  85. t.Error("error calling createadmin", err)
  86. }
  87. defer response.Body.Close()
  88. var message badResponse
  89. json.NewDecoder(response.Body).Decode(&message)
  90. assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
  91. assert.Equal(t, http.StatusUnauthorized, message.Code)
  92. assert.Equal(t, "W1R3: Admin already exists! ", message.Message)
  93. })
  94. //deleteAdmin()
  95. t.Run("Admin Creation - Valid", func(t *testing.T) {
  96. t.Skip()
  97. response, err := api(admin, http.MethodPost, "http://localhost:8081/users/createadmin", "")
  98. if err != nil {
  99. t.Error("error calling createadmin", err)
  100. }
  101. defer response.Body.Close()
  102. json.NewDecoder(response.Body).Decode(&user)
  103. assert.Equal(t, admin.UserName, user.UserName)
  104. assert.Equal(t, true, user.IsAdmin)
  105. assert.Equal(t, http.StatusOK, response.StatusCode)
  106. assert.True(t, adminExists(t), "Admin creation failed")
  107. })
  108. }
  109. })
  110. t.Run("GetUser", func(t *testing.T) {
  111. //ensure admin exists
  112. if !adminExists(t) {
  113. t.Error("admin account does not exist")
  114. return
  115. }
  116. //authenticate
  117. t.Run("GetUser ValidToken", func(t *testing.T) {
  118. token, err := authenticate()
  119. if err != nil {
  120. t.Error("could not authenticate")
  121. }
  122. response, err := api("", http.MethodGet, "http://localhost:8081/users/admin", token)
  123. if err != nil {
  124. t.Error("could not get user")
  125. }
  126. defer response.Body.Close()
  127. var user models.User
  128. json.NewDecoder(response.Body).Decode(&user)
  129. assert.Equal(t, http.StatusOK, response.StatusCode)
  130. assert.Equal(t, "admin", user.UserName)
  131. assert.Equal(t, true, user.IsAdmin)
  132. })
  133. t.Run("GetUser InvalidToken", func(t *testing.T) {
  134. //skip until sort out what should be returned
  135. t.Skip()
  136. response, err := api("", http.MethodGet, "http://localhost:8081/users/admin", "xxxx")
  137. if err != nil {
  138. t.Error("error getting user")
  139. }
  140. defer response.Body.Close()
  141. ///not sure what this should be
  142. var something string
  143. json.NewDecoder(response.Body).Decode(something)
  144. assert.Equal(t, "Some error message", something)
  145. })
  146. })
  147. t.Run("Update User", func(t *testing.T) {
  148. t.Skip()
  149. if !adminExists(t) {
  150. addAdmin(t)
  151. }
  152. //token, err := authenticate()
  153. //if err != nil {
  154. // t.Error("could not authenticate")
  155. //}
  156. var admin, user models.User
  157. admin.UserName = "admin"
  158. admin.Password = "admin"
  159. //payload := map[string]string{"username": "admin", "password": "admin"}
  160. payload, _ := json.Marshal(admin)
  161. request, err := http.NewRequest(http.MethodPut, "http://localhost:8081/users/admin", bytes.NewBuffer(payload))
  162. if err != nil {
  163. t.Error(err)
  164. }
  165. request.Header.Set("Authorization", "Bearer secretkey")
  166. request.Header.Set("Content-Type", "application/json")
  167. client := &http.Client{}
  168. response, err := client.Do(request)
  169. if err != nil {
  170. t.Error("error calling createadmin", err)
  171. }
  172. defer response.Body.Close()
  173. body, _ := ioutil.ReadAll(response.Body)
  174. t.Log(string(body))
  175. _ = json.Unmarshal(body, &user)
  176. assert.Equal(t, admin.UserName, user.UserName)
  177. assert.Equal(t, true, user.IsAdmin)
  178. assert.Equal(t, http.StatusOK, response.StatusCode)
  179. })
  180. t.Run("Authenticate User", func(t *testing.T) {
  181. cases := []AuthorizeTestCase{
  182. AuthorizeTestCase{
  183. testname: "Invalid User",
  184. name: "invaliduser",
  185. password: "password",
  186. code: http.StatusBadRequest,
  187. tokenExpected: false,
  188. errMessage: "W1R3: It's not you it's me.",
  189. },
  190. AuthorizeTestCase{
  191. testname: "empty user",
  192. name: "",
  193. password: "password",
  194. code: http.StatusBadRequest,
  195. tokenExpected: false,
  196. errMessage: "W1R3: Username can't be empty",
  197. },
  198. AuthorizeTestCase{
  199. testname: "empty password",
  200. name: "admin",
  201. password: "",
  202. code: http.StatusBadRequest,
  203. tokenExpected: false,
  204. errMessage: "W1R3: Password can't be empty",
  205. },
  206. AuthorizeTestCase{
  207. testname: "Invalid Passord",
  208. name: "admin",
  209. password: "xxxxxxx",
  210. code: http.StatusBadRequest,
  211. tokenExpected: false,
  212. errMessage: "W1R3: It's not you it's me.",
  213. },
  214. AuthorizeTestCase{
  215. testname: "Valid User",
  216. name: "admin",
  217. password: "password",
  218. code: http.StatusOK,
  219. tokenExpected: true,
  220. errMessage: "W1R3: Device Admin Authorized",
  221. },
  222. }
  223. for _, tc := range cases {
  224. t.Run(tc.testname, func(t *testing.T) {
  225. if !adminExists(t) {
  226. addAdmin(t)
  227. }
  228. var admin models.User
  229. admin.UserName = tc.name
  230. admin.Password = tc.password
  231. response, err := api(admin, http.MethodPost, "http://localhost:8081/users/authenticate", "secretkey")
  232. if err != nil {
  233. t.Error("authenticate api call failed")
  234. }
  235. if tc.tokenExpected {
  236. var body goodResponse
  237. json.NewDecoder(response.Body).Decode(&body)
  238. assert.NotEmpty(t, body.Response.AuthToken, "token not returned")
  239. assert.Equal(t, "W1R3: Device admin Authorized", body.Message)
  240. } else {
  241. var body badResponse
  242. json.NewDecoder(response.Body).Decode(&body)
  243. assert.Equal(t, tc.errMessage, body.Message)
  244. }
  245. assert.Equal(t, tc.code, response.StatusCode)
  246. })
  247. }
  248. })
  249. }
  250. func adminExists(t *testing.T) bool {
  251. response, err := http.Get("http://localhost:8081/users/hasadmin")
  252. if err != nil {
  253. t.Fatal("error calling users/hasadmin", err)
  254. }
  255. assert.Equal(t, http.StatusOK, response.StatusCode)
  256. defer response.Body.Close()
  257. var body bool
  258. json.NewDecoder(response.Body).Decode(&body)
  259. return body
  260. }
  261. func api(data interface{}, method, url, authorization string) (*http.Response, error) {
  262. payload, err := json.Marshal(data)
  263. if err != nil {
  264. return nil, err
  265. }
  266. request, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
  267. if err != nil {
  268. return nil, err
  269. }
  270. request.Header.Set("Content-Type", "application/json")
  271. if authorization != "" {
  272. request.Header.Set("Authorization", "Bearer "+authorization)
  273. }
  274. client := http.Client{}
  275. return client.Do(request)
  276. }
  277. func addAdmin(t *testing.T) {
  278. var admin models.User
  279. admin.UserName = "admin"
  280. admin.Password = "password"
  281. payload, _ := json.Marshal(admin)
  282. request, err := http.NewRequest(http.MethodPost, "http://localhost:8081/users/createadmin",
  283. bytes.NewBuffer(payload))
  284. assert.NotNilf(t, err, "none nil error creating http request")
  285. request.Header.Set("Authorization", "Bearer secretkey")
  286. request.Header.Set("Content-Type", "application/json")
  287. client := &http.Client{}
  288. response, err := client.Do(request)
  289. assert.NotNilf(t, err, "non nil err response from createadmin")
  290. assert.Equal(t, http.StatusOK, response.StatusCode)
  291. }
  292. func authenticate() (string, error) {
  293. var admin models.User
  294. admin.UserName = "admin"
  295. admin.Password = "password"
  296. response, err := api(admin, http.MethodPost, "http://localhost:8081/users/authenticate", "secretkey")
  297. if err != nil {
  298. return "", err
  299. }
  300. var body goodResponse
  301. json.NewDecoder(response.Body).Decode(&body)
  302. token := body.Response.AuthToken
  303. return token, nil
  304. }