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.

api_twofa_test.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package integration
  4. import (
  5. "net/http"
  6. "testing"
  7. "time"
  8. auth_model "code.gitea.io/gitea/models/auth"
  9. "code.gitea.io/gitea/models/db"
  10. "code.gitea.io/gitea/models/unittest"
  11. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/tests"
  13. "github.com/pquerna/otp/totp"
  14. "github.com/stretchr/testify/assert"
  15. )
  16. func TestAPITwoFactor(t *testing.T) {
  17. defer tests.PrepareTestEnv(t)()
  18. user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 16})
  19. req := NewRequest(t, "GET", "/api/v1/user").
  20. AddBasicAuth(user.Name)
  21. MakeRequest(t, req, http.StatusOK)
  22. otpKey, err := totp.Generate(totp.GenerateOpts{
  23. SecretSize: 40,
  24. Issuer: "gitea-test",
  25. AccountName: user.Name,
  26. })
  27. assert.NoError(t, err)
  28. tfa := &auth_model.TwoFactor{
  29. UID: user.ID,
  30. }
  31. assert.NoError(t, tfa.SetSecret(otpKey.Secret()))
  32. assert.NoError(t, auth_model.NewTwoFactor(db.DefaultContext, tfa))
  33. req = NewRequest(t, "GET", "/api/v1/user").
  34. AddBasicAuth(user.Name)
  35. MakeRequest(t, req, http.StatusUnauthorized)
  36. passcode, err := totp.GenerateCode(otpKey.Secret(), time.Now())
  37. assert.NoError(t, err)
  38. req = NewRequest(t, "GET", "/api/v1/user").
  39. AddBasicAuth(user.Name)
  40. req.Header.Set("X-Gitea-OTP", passcode)
  41. MakeRequest(t, req, http.StatusOK)
  42. }