Skip to content

Commit

Permalink
saved the jwt without the refresh token + unit tests
Browse files Browse the repository at this point in the history
Signed-off-by: Fiona Ampofo <64271621+Akyiaa@users.noreply.github.com>
  • Loading branch information
Akyiaa committed May 8, 2024
1 parent 7c6f65b commit 73c8936
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 4 deletions.
34 changes: 30 additions & 4 deletions pkg/auth/authLogin.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package auth

import (
"context"
"encoding/json"
"log"
"net/http"

Expand All @@ -18,6 +19,10 @@ import (
"github.com/galasa-dev/cli/pkg/utils"
)

type JwtJson struct {
Jwt string `json:"jwt"`
}

// Login - performs all the logic to implement the `galasactl auth login` command
func Login(apiServerUrl string, fileSystem files.FileSystem, galasaHome utils.GalasaHome, env utils.Environment) error {

Expand Down Expand Up @@ -57,16 +62,37 @@ func GetJwtFromRestApi(apiServerUrl string, authProperties galasaapi.AuthPropert
err = galasaErrors.NewGalasaError(galasaErrors.GALASA_ERROR_RETRIEVING_BEARER_TOKEN_FROM_API_SERVER, err.Error())
} else {
defer httpResponse.Body.Close()
var tokenResponseJson []byte
tokenResponseJson, err = tokenResponse.MarshalJSON()
jwtJsonStr = string(tokenResponseJson)
log.Println("Bearer token received from API server OK")

jwtJsonStr, err = getJWTJsonStringFromTokenResponse(tokenResponse)
}
}

return jwtJsonStr, err
}

// Saves the JWT in a new structure that only saves the JWT and not refresh token, and returns the JSON string
func getJWTJsonStringFromTokenResponse(tokenResponse *galasaapi.TokenResponse) (string, error){
var err error
var jwtJsonBytes []byte
var jwtJsonStr string

// new structure defined to only store jwt
// and not refresh token
jwtJson := JwtJson{
Jwt: tokenResponse.GetJwt(),
}

jwtJsonBytes, err = json.Marshal(jwtJson)
if err == nil{
jwtJsonStr = string(jwtJsonBytes)
log.Println("Bearer token received from API server OK")
} else {
err = galasaErrors.NewGalasaError(galasaErrors.GALASA_ERROR_UNABLE_TO_MARSHAL_JWT_JSON, err.Error())
}

return jwtJsonStr, err
}

// Gets a new authenticated API client, attempting to log in if a bearer token file does not exist
func GetAuthenticatedAPIClient(
apiServerUrl string,
Expand Down
62 changes: 62 additions & 0 deletions pkg/auth/authLogin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"time"

"github.com/galasa-dev/cli/pkg/files"
"github.com/galasa-dev/cli/pkg/galasaapi"
"github.com/galasa-dev/cli/pkg/utils"
"github.com/stretchr/testify/assert"

Expand Down Expand Up @@ -257,3 +258,64 @@ func TestGetAuthenticatedAPIClientWithMissingBearerTokenFileAttemptsLogin(t *tes
assert.NotNil(t, apiClient, "API client should not be nil if the login was successful")
}

func TestLoginWithoutRefreshTokenReturnsError(t *testing.T) {
// Given...
mockFileSystem := files.NewMockFileSystem()
mockEnvironment := utils.NewMockEnv()
mockGalasaHome, _ := utils.NewGalasaHome(mockFileSystem, mockEnvironment, "")

galasactlPropertiesFilePath := mockGalasaHome.GetNativeFolderPath() + "/galasactl.properties"

mockClientId := "dummyId"
mockRefreshToken := ""
tokenPropertyValue := mockRefreshToken + TOKEN_SEPARATOR + mockClientId
mockFileSystem.WriteTextFile(galasactlPropertiesFilePath, fmt.Sprintf("GALASA_TOKEN=%s", tokenPropertyValue))

mockResponse := `{"jwt":"blah"}`
server := NewAuthServletMock(t, 200, mockResponse)
defer server.Close()

apiServerUrl := server.URL

// When...
err := Login(apiServerUrl, mockFileSystem, mockGalasaHome, mockEnvironment)

bearerTokenFilePath := mockGalasaHome.GetNativeFolderPath() + "/bearer-token.json"
bearerTokenFileExists, _ := mockFileSystem.Exists(bearerTokenFilePath)

// Then...
assert.NotNil(t, err, "Should return an error as the refresh token is absent")
assert.ErrorContains(t, err, "GAL1125E")
assert.False(t, bearerTokenFileExists, "Bearer token file should not exist")
}

func TestGetJWTJsonStringFromReponseTokenWithRefreshTokenReturnsJWTStringWithoutToken(t *testing.T) {
//Given...
var tokenResponse = galasaapi.NewTokenResponse()
tokenResponse.SetJwt("blah")
tokenResponse.SetRefreshToken("refresh")

mockResponse := `{"jwt":"blah"}`

//When...
jwtJsonStr, err := getJWTJsonStringFromTokenResponse(tokenResponse)

//Then...
assert.Nil(t, err, "No error should have been thrown")
assert.Equal(t, mockResponse, jwtJsonStr)
}

func TestGetJWTJsonStringFromReponseTokenWithoutRefreshTokenReturnsJWTStringWithoutToken(t *testing.T) {
//Given...
var tokenResponse = galasaapi.NewTokenResponse()
tokenResponse.SetJwt("blah")

mockResponse := `{"jwt":"blah"}`

//When...
jwtJsonStr, err := getJWTJsonStringFromTokenResponse(tokenResponse)

//Then...
assert.Nil(t, err, "No error should have been thrown")
assert.Equal(t, mockResponse, jwtJsonStr)
}
1 change: 1 addition & 0 deletions pkg/errors/errorMessage.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ var (
"The %s field value must start with a character in the 'a-z' or 'A-Z' range, followed by any characters in the 'a'-'z', 'A'-'Z', '0'-'9', '.' (period), '-' (dash) or '_' (underscore) ranges only.", 1142, STACK_TRACE_NOT_WANTED)
GALASA_ERROR_QUERY_RUNS_NON_OK_STATUS = NewMessageType("GAL1143E: Could not query run results. Server returned a non-200 code (%s)", 1143, STACK_TRACE_NOT_WANTED)
GALASA_ERROR_GET_TEST_CATALOG_CONTENTS_FAILED = NewMessageType("GAL1144E: Could not use url '%s' to retrieve the contents of the test catalog from stream '%s'. Http error from the Galasa server is '%v'", 1144, STACK_TRACE_NOT_WANTED)
GALASA_ERROR_UNABLE_TO_MARSHAL_JWT_JSON = NewMessageType("GAL1145E: Failed to unmarshal the JWT json. Reason: %s", 1145, STACK_TRACE_NOT_WANTED)

// Warnings...
GALASA_WARNING_MAVEN_NO_GALASA_OBR_REPO = NewMessageType("GAL2000W: Warning: Maven configuration file settings.xml should contain a reference to a Galasa repository so that the galasa OBR can be resolved. The official release repository is '%s', and 'pre-release' repository is '%s'", 2000, STACK_TRACE_WANTED)
Expand Down

0 comments on commit 73c8936

Please sign in to comment.