code.gitea.io/gitea@v1.21.7/tests/integration/api_twofa_test.go (about)

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