Skip to content

Commit

Permalink
added logging and request fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Jmfwolf committed Jun 8, 2023
1 parent 2cdfbdc commit fe4ed6d
Show file tree
Hide file tree
Showing 13 changed files with 103 additions and 71 deletions.
1 change: 0 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ func main() {
fmt.Println("Unable to initialize client:", err)
return
}

userQuery := models.UserQuery{}
userList, err := ol.GetUsers(&userQuery)
if err != nil {
Expand Down
23 changes: 14 additions & 9 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -35,11 +36,12 @@ type Authenticator interface {

// NewClient creates a new instance of the API client.
func NewClient() (*Client, error) {
old := fmt.Sprintf("https://%s.onelogin.com", os.Getenv("ONELOGIN_SUBDOMAIN"))
authenticator := authentication.NewAuthenticator(old)
subdomain := os.Getenv("ONELOGIN_SUBDOMAIN")
old := fmt.Sprintf("https://%s.onelogin.com", subdomain)
authenticator := authentication.NewAuthenticator()
err := authenticator.GenerateToken()
if err != nil {
return nil, olerror.NewSDKError("Failed to initialize client")
return nil, err
}

return &Client{
Expand All @@ -50,15 +52,15 @@ func NewClient() (*Client, error) {
}

// newRequest creates a new HTTP request with the specified method, path, query parameters, and request body.
func (c *Client) newRequest(method string, path *string, queryParams *mod.Queryable, body io.Reader) (*http.Request, error) {
func (c *Client) newRequest(method string, path *string, queryParams mod.Queryable, body io.Reader) (*http.Request, error) {

p, err := utl.AddQueryToPath(path, queryParams)
*path = p
p, err := utl.AddQueryToPath(*path, queryParams)
if err != nil {
return nil, err
}
log.Println("Path:", p)
// Parse the OneLogin domain and path
u, err := url.Parse(c.OLdomain + *path)
u, err := url.Parse(c.OLdomain + p)
if err != nil {
return nil, err
}
Expand All @@ -70,20 +72,23 @@ func (c *Client) newRequest(method string, path *string, queryParams *mod.Querya
}

// Get authentication token
log.Println("Getting authentication token...")
tk, err := c.Auth.GetToken()
if err != nil {
log.Println("Error getting authentication token:", err)
return nil, olerror.NewAuthenticationError("Access Token Retrieval Error")
}
log.Println("Authentication token retrieved successfully.")

// Set request headers
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *tk))
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", tk))
req.Header.Set("Content-Type", "application/json")

return req, nil
}

// Get sends a GET request to the specified path with the given query parameters.
func (c *Client) Get(path *string, queryParams *mod.Queryable) (*http.Response, error) {
func (c *Client) Get(path *string, queryParams mod.Queryable) (*http.Response, error) {
req, err := c.newRequest(http.MethodGet, path, queryParams, http.NoBody)
if err != nil {
return nil, err
Expand Down
22 changes: 8 additions & 14 deletions internal/authentication/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,11 @@ const (
)

type Authenticator struct {
accessToken *string
OLDomain *string
accessToken string
}

func NewAuthenticator(Domain string) *Authenticator {
var domain = Domain
var token string = ""
return &Authenticator{
accessToken: &token,
OLDomain: &domain,
}
func NewAuthenticator() *Authenticator {
return &Authenticator{}
}

func (a *Authenticator) GenerateToken() error {
Expand All @@ -37,13 +31,14 @@ func (a *Authenticator) GenerateToken() error {
if len(clientID) == 0 {
return olError.NewAuthenticationError("Missing ONELOGIN_CLIENT_ID Env Variable")
}
//fmt.Println("clientID", clientID)
clientSecret := os.Getenv("ONELOGIN_CLIENT_SECRET")
if len(clientSecret) == 0 {
return olError.NewAuthenticationError("Missing ONELOGIN_CLIENT_SECRET Env Variable")
}

// Construct the authentication URL
authURL := fmt.Sprintf("%s%s", *a.OLDomain, TokenPath)
authURL := fmt.Sprintf("https://api.onelogin.com%s", TokenPath)

// Create authentication request payload
data := map[string]string{
Expand Down Expand Up @@ -91,9 +86,8 @@ func (a *Authenticator) GenerateToken() error {
if !ok {
return olError.NewAuthenticationError("Authentication Failed at Endpoint")
}

// Store access token
*a.accessToken = accessToken
a.accessToken = accessToken

return nil
}
Expand All @@ -109,7 +103,7 @@ func (a *Authenticator) RevokeToken(token, domain *string) error {
}

// Construct the revoke URL
revokeURL := fmt.Sprintf("%s%s", *domain, RevokePath)
revokeURL := fmt.Sprintf("api.onelogin.com%s", RevokePath)

// Create revoke request payload
data := struct {
Expand Down Expand Up @@ -153,6 +147,6 @@ func (a *Authenticator) RevokeToken(token, domain *string) error {
return nil
}

func (a *Authenticator) GetToken() (*string, error) {
func (a *Authenticator) GetToken() (string, error) {
return a.accessToken, nil
}
6 changes: 3 additions & 3 deletions internal/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ const (

// UserQuery represents available query parameters
type UserQuery struct {
Limit string
Page string
Cursor string
Limit string `json:"limit,omitempty"`
Page string `json:"page,omitempty"`
Cursor string `json:"cursor,omitempty"`
CreatedSince *time.Time `json:"created_since,omitempty"`
CreatedUntil *time.Time `json:"created_until,omitempty"`
UpdatedSince *time.Time `json:"updated_since,omitempty"`
Expand Down
10 changes: 9 additions & 1 deletion internal/utilities/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,21 @@ import (
// ValidateQueryParams validates the query parameters based on the provided validators.
func ValidateQueryParams(query interface{}, validators map[string]func(interface{}) bool) bool {
queryValue := reflect.ValueOf(query)
if queryValue.Kind() == reflect.Ptr {
queryValue = queryValue.Elem()
}
queryType := queryValue.Type()

for i := 0; i < queryValue.NumField(); i++ {
fieldValue := queryValue.Field(i)
fieldType := queryType.Field(i)

// Skip empty fields
// Skip non-pointer fields
if fieldValue.Kind() != reflect.Ptr {
continue
}

// Skip nil fields
if fieldValue.IsNil() {
continue
}
Expand Down
67 changes: 46 additions & 21 deletions internal/utilities/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"

olerror "github.com/onelogin/onelogin-go-sdk/internal/error"
mod "github.com/onelogin/onelogin-go-sdk/internal/models"
)

// receive http response, check error code status, if good return json of resp.Body
Expand All @@ -32,13 +33,24 @@ func CheckHTTPResponse(resp *http.Response) (interface{}, error) {
}

// Try to unmarshal the response body into a map[string]interface{}
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
// If unmarshaling fails, return the response body as a string
return string(body), nil
var data interface{}
if strings.HasPrefix(string(body), "[") {
var slice []interface{}
err = json.Unmarshal(body, &slice)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal response body into []interface{}: %w", err)
}
data = slice
} else {
var dict map[string]interface{}
err = json.Unmarshal(body, &dict)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal response body into map[string]interface{}: %w", err)
}
data = dict
}

log.Printf("Response body unmarshaled successfully: %v\n", data)
return data, nil
}

Expand Down Expand Up @@ -74,26 +86,39 @@ func BuildAPIPath(parts ...interface{}) (string, error) {
}

// AddQueryToPath adds the model as a JSON-encoded query parameter to the path and returns the new path.
func AddQueryToPath(path *string, model *mod.Queryable) (string, error) {
// Convert the model to a JSON string
jsonBytes, err := json.Marshal(model)
if err != nil {
return "", err
func AddQueryToPath(path string, query interface{}) (string, error) {
if query == nil {
return path, nil
}

// URL-encode the JSON string
encodedModel := url.QueryEscape(string(jsonBytes))

// Parse the original path
u, err := url.Parse(*path)
// Convert query parameters to URL-encoded string
values, err := queryToValues(query)
if err != nil {
return "", err
}

// Add the encoded model to the path's query string
q := u.Query()
q.Set("model", encodedModel)
u.RawQuery = q.Encode()
// Append query parameters to path
if values.Encode() != "" {
path += "?" + values.Encode()
}

return path, nil
}

func queryToValues(query interface{}) (url.Values, error) {
values := url.Values{}

// Convert query parameters to URL-encoded string
if query != nil {
queryBytes, err := json.Marshal(query)
if err != nil {
return nil, err
}
err = json.Unmarshal(queryBytes, &values)
if err != nil {
return nil, err
}
}

return u.String(), nil
return values, nil
}
6 changes: 3 additions & 3 deletions pkg/onelogin/api_authorizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (sdk *OneloginSDK) CreateAuthServer(authServer *mod.AuthServer) (interface{
return utl.CheckHTTPResponse(resp)
}

func (sdk *OneloginSDK) GetAuthServers(queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetAuthServers(queryParams mod.Queryable) (interface{}, error) {
p, err := utl.BuildAPIPath(APIAuthPath)
if err != nil {
return nil, err
Expand All @@ -33,7 +33,7 @@ func (sdk *OneloginSDK) GetAuthServers(queryParams *mod.Queryable) (interface{},
return utl.CheckHTTPResponse(resp)
}

func (sdk *OneloginSDK) GetAuthServerByID(id int, queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetAuthServerByID(id int, queryParams mod.Queryable) (interface{}, error) {
p, err := utl.BuildAPIPath(APIAuthPath)
if err != nil {
return nil, err
Expand Down Expand Up @@ -94,7 +94,7 @@ func (sdk *OneloginSDK) DeleteAuthClaim(id, claimID int) (interface{}, error) {
return utl.CheckHTTPResponse(resp)
}

func (sdk *OneloginSDK) GetAuthClaims(id int, queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetAuthClaims(id int, queryParams mod.Queryable) (interface{}, error) {
p, err := utl.BuildAPIPath(APIAuthPath, id, "claims")
if err != nil {
return nil, err
Expand Down
8 changes: 4 additions & 4 deletions pkg/onelogin/apps.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func (sdk *OneloginSDK) CreateApp(app *mod.App) (interface{}, error) {

}

func (sdk *OneloginSDK) GetApps(queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetApps(queryParams mod.Queryable) (interface{}, error) {
p := AppPath
resp, err := sdk.Client.Get(&p, queryParams)
if err != nil {
Expand All @@ -28,7 +28,7 @@ func (sdk *OneloginSDK) GetApps(queryParams *mod.Queryable) (interface{}, error)
return utl.CheckHTTPResponse(resp)
}

func (sdk *OneloginSDK) GetAppByID(id int, queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetAppByID(id int, queryParams mod.Queryable) (interface{}, error) {
p, err := utl.BuildAPIPath(AppPath, id)
if err != nil {
return nil, err
Expand Down Expand Up @@ -80,7 +80,7 @@ func (sdk *OneloginSDK) CreateAppRule(id int, appRule *mod.AppRule) (interface{}

}

func (sdk *OneloginSDK) GetAppRules(id int, queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetAppRules(id int, queryParams mod.Queryable) (interface{}, error) {
p, err := utl.BuildAPIPath(AppPath, id)
if err != nil {
return nil, err
Expand All @@ -93,7 +93,7 @@ func (sdk *OneloginSDK) GetAppRules(id int, queryParams *mod.Queryable) (interfa

}

func (sdk *OneloginSDK) GetAppRuleByID(id, ruleID int, queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetAppRuleByID(id, ruleID int, queryParams mod.Queryable) (interface{}, error) {
p, err := utl.BuildAPIPath(AppPath, id)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion pkg/onelogin/onelogin.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func (sdk *OneloginSDK) GetToken() (string, error) {
if err != nil {
return "", olerror.NewSDKError("Access Token retrieval unsuccessful")
}
return *accessTk, nil
return accessTk, nil
}

// MFA-related endpoints
Expand Down
4 changes: 2 additions & 2 deletions pkg/onelogin/roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func (sdk *OneloginSDK) CreateRole(role *mod.Role) (interface{}, error) {
return utl.CheckHTTPResponse(resp)
}

func (sdk *OneloginSDK) GetRoles(queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetRoles(queryParams mod.Queryable) (interface{}, error) {
p := RolePath
resp, err := sdk.Client.Get(&p, queryParams)
if err != nil {
Expand All @@ -27,7 +27,7 @@ func (sdk *OneloginSDK) GetRoles(queryParams *mod.Queryable) (interface{}, error
return utl.CheckHTTPResponse(resp)
}

func (sdk *OneloginSDK) GetRoleByID(id int, queryParams *mod.Queryable) (interface{}, error) {
func (sdk *OneloginSDK) GetRoleByID(id int, queryParams mod.Queryable) (interface{}, error) {
p, err := utl.BuildAPIPath(RolePath, id)
if err != nil {
return nil, err
Expand Down
Loading

0 comments on commit fe4ed6d

Please sign in to comment.