Skip to content

Commit

Permalink
move 'authenticate' function to CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
consolethinks committed Aug 16, 2024
1 parent 2621e3b commit 273916f
Show file tree
Hide file tree
Showing 11 changed files with 46 additions and 44 deletions.
28 changes: 24 additions & 4 deletions cmd/commands/utilityFuncs.go → cmd/commands/authenticate.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,36 @@ import (
"golang.org/x/term"
)

// An interface with the methods so that we can mock them in tests
type Authenticator interface {
AuthenticateUser(httpClient *http.Client, APIServer string, username string, password string) (map[string]string, []string)
GetUserInfoFromToken(httpClient *http.Client, APIServer string, token string) (map[string]string, []string)
}

type RealAuthenticator struct{}

func (r RealAuthenticator) AuthenticateUser(httpClient *http.Client, APIServer string, username string, password string) (map[string]string, []string) {
return datasetUtils.AuthenticateUser(httpClient, APIServer, username, password)
}

func (r RealAuthenticator) GetUserInfoFromToken(httpClient *http.Client, APIServer string, token string) (map[string]string, []string) {
return datasetUtils.GetUserInfoFromToken(httpClient, APIServer, token)
}

// Authenticate handles user authentication by prompting the user for their credentials,
// validating these credentials against the authentication server,
// and returning an authentication token if the credentials are valid.
// This token can then be used for authenticated requests to the server.
// If the credentials are not valid, the function returns an error.
func authenticate(authenticator datasetUtils.RealAuthenticator, httpClient *http.Client, apiServer string, userpass string, token string) (map[string]string, []string) {
func authenticate(authenticator Authenticator, httpClient *http.Client, apiServer string, userpass string, token string, overrideFatalExit ...func(v ...any)) (map[string]string, []string) {
fatalExit := log.Fatal // by default, call log fatal
if len(overrideFatalExit) == 1 {
fatalExit = overrideFatalExit[0]
}
if token != "" {
user, accessGroups := authenticator.GetUserInfoFromToken(httpClient, apiServer, token)
uSplit := strings.Split(userpass, ":")
if len(uSplit) >= 1 {
if len(uSplit) > 1 {
user["password"] = uSplit[1]
}
return user, accessGroups
Expand All @@ -46,12 +66,12 @@ func authenticate(authenticator datasetUtils.RealAuthenticator, httpClient *http
fmt.Print("Username: ")
_, err := fmt.Scan(&username)
if err != nil {
log.Fatal(err)
fatalExit(err)
}
fmt.Print("Password: ")
pw, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
log.Fatal(err)
fatalExit(err)
}
return authenticator.AuthenticateUser(httpClient, apiServer, username, string(pw))
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package datasetUtils
package cmd

import (
"net/http"
Expand All @@ -23,20 +23,23 @@ func (m *MockAuthenticator) GetUserInfoFromToken(httpClient *http.Client, APISer

func TestAuthenticate(t *testing.T) {
var auth Authenticator = &MockAuthenticator{}
noExit := func(v ...any) {

}
// Mock HTTP server
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte(`{"username": "testuser", "accessGroups": ["group1", "group2"]}`))
}))
defer server.Close()

// Test cases
tests := []struct {
name string
token string
userpass string
wantUser map[string]string
wantGroup []string
}{
}{
{
name: "Test with token",
token: "testtoken",
Expand All @@ -48,10 +51,10 @@ func TestAuthenticate(t *testing.T) {
wantGroup: []string{"group3", "group4"},
},
{
name: "Test with empty token and userpass",
token: "",
userpass: "",
wantUser: map[string]string{},
name: "Test with empty token and userpass",
token: "",
userpass: "",
wantUser: map[string]string{},
wantGroup: []string{},
},
{
Expand All @@ -75,16 +78,16 @@ func TestAuthenticate(t *testing.T) {
wantGroup: []string{"group3", "group4"},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
httpClient := server.Client()
user, group := Authenticate(auth, httpClient, server.URL, &tt.token, &tt.userpass)
user, group := authenticate(auth, httpClient, server.URL, tt.userpass, tt.token, noExit)

if !reflect.DeepEqual(user, tt.wantUser) {
t.Errorf("got %v, want %v", user, tt.wantUser)
}

if !reflect.DeepEqual(group, tt.wantGroup) {
t.Errorf("got %v, want %v", group, tt.wantGroup)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/datasetArchiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ For further help see "` + MANUAL + `"`,
inputdatasetList = args[0:]
}

user, _ := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, _ := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)

archivableDatasets := datasetUtils.GetArchivableDatasets(client, APIServer, ownerGroup, inputdatasetList, user["accessToken"])
if len(archivableDatasets) <= 0 {
Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/datasetCleaner.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ For further help see "` + MANUAL + `"`,
}
pid := args[0]

user, _ := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, _ := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)

if user["username"] != "archiveManager" {
log.Fatalf("You must be archiveManager to be allowed to delete datasets\n")
Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/datasetGetProposal.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ For further help see "` + MANUAL + `"`,
}
ownerGroup := args[0]

user, accessGroups := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, accessGroups := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)
proposal, err := datasetUtils.GetProposal(client, APIServer, ownerGroup, user, accessGroups)
if err != nil {
log.Fatal(err)
Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/datasetIngestor.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ For Windows you need instead to specify -user username:password on the command l
color.Unset()

// TODO: change pointer parameter types to values as they shouldn't be modified by the function
user, accessGroups := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, accessGroups := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)

/* TODO Add info about policy settings and that autoarchive will take place or not */

Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/datasetPublishData.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ To update the PublishedData entry with the downloadLink you have to run the scri

// set value in publishedData ==============================

user, _ := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, _ := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)

type PublishedDataPart struct {
DownloadLink string `json:"downloadLink"`
Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/datasetPublishDataRetrieve.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ var datasetPublishDataRetrieveCmd = &cobra.Command{
return
}

user, _ := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, _ := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)

datasetList, _, _ := datasetUtils.GetDatasetsOfPublication(client, APIServer, publishedDataId)

Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/datasetRetriever.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ For further help see "` + MANUAL + `"`,
}
destinationPath = args[0]

user, _ := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, _ := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)

datasetList, err := datasetUtils.GetAvailableDatasets(user["username"], RSYNCServer, datasetId)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/commands/waitForJobFinished.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ var waitForJobFinishedCmd = &cobra.Command{
return
}

user, _ := authenticate(datasetUtils.RealAuthenticator{}, client, APIServer, userpass, token)
user, _ := authenticate(RealAuthenticator{}, client, APIServer, userpass, token)

filter := `{"where":{"id":"` + jobId + `"}}`

Expand Down
21 changes: 0 additions & 21 deletions datasetUtils/authenticate.go

This file was deleted.

0 comments on commit 273916f

Please sign in to comment.