Skip to content

Commit

Permalink
Revert "Revert "Flash Error msg upon invalid token in provider def""
Browse files Browse the repository at this point in the history
This reverts commit 3c04140.
  • Loading branch information
uzaxirr committed Aug 13, 2024
1 parent cb5c153 commit 77abe7f
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions civo/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package civo

import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
Expand Down Expand Up @@ -114,13 +115,15 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {
var regionValue, tokenValue, apiURL string
var client *civogo.Client
var err error
var tokenSource string

if region, ok := d.GetOk("region"); ok {
regionValue = region.(string)
}

if token, ok := getToken(d); ok {
if token, ok, source := getToken(d); ok {
tokenValue = token.(string)
tokenSource = source
} else {
return nil, fmt.Errorf("[ERR] No token configuration found in $CIVO_TOKEN or ~/.civo.json. Please go to https://dashboard.civo.com/security to fetch one")
}
Expand All @@ -141,23 +144,35 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {
}
client.SetUserAgent(userAgent)

// Validate token by making a simple API request
_, err = client.ListRegions()
if err != nil {

// Check if the error is DatabaseAccountNotFoundError
if errors.Is(err, civogo.DatabaseAccountNotFoundError) {
return nil, fmt.Errorf("the Civo token from %s is invalid. Please go to https://dashboard.civo.com/security to generate one", tokenSource)
}

return nil, fmt.Errorf("an error occoured while connecting to Civo's API: %s", err)
}

log.Printf("[DEBUG] Civo API URL: %s\n", apiURL)
return client, nil
}

func getToken(d *schema.ResourceData) (interface{}, bool) {
func getToken(d *schema.ResourceData) (interface{}, bool, string) {
var exists = true

// Gets you the token atrribute value or falls back to reading CIVO_TOKEN environment variable
if token, ok := d.GetOk("token"); ok {
return token, exists
return token, exists, "environment variable"
}

// Check for credentials file specified in provider config
if credFile, ok := d.GetOk("credentials_file"); ok {
token, err := readTokenFromFile(credFile.(string))
if err == nil {
return token, exists
return token, exists, "credentials file"
}
}

Expand All @@ -166,11 +181,11 @@ func getToken(d *schema.ResourceData) (interface{}, bool) {
if err == nil {
token, err := readTokenFromFile(filepath.Join(homeDir, ".civo.json"))
if err == nil {
return token, exists
return token, exists, "CLI config file"
}
}

return nil, !exists
return nil, !exists, ""

}

Expand Down

0 comments on commit 77abe7f

Please sign in to comment.