Skip to content

Commit

Permalink
validation is broken
Browse files Browse the repository at this point in the history
  • Loading branch information
Jmfwolf committed Jun 8, 2023
1 parent cebd8da commit 2cdfbdc
Show file tree
Hide file tree
Showing 19 changed files with 800 additions and 183 deletions.
20 changes: 7 additions & 13 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,23 @@ package main
import (
"fmt"

"github.com/onelogin/onelogin-go-sdk/internal/models"
"github.com/onelogin/onelogin-go-sdk/pkg/onelogin"
)

func main() {

// Create a new instance of the Onelogin SDK
ol := onelogin.NewOneloginSDK()

// Use the Onelogin SDK to make API calls

token, err := ol.GetToken()
ol, err := onelogin.NewOneloginSDK()
if err != nil {
fmt.Printf("Failed to get token: %s\n", err)
fmt.Println("Unable to initialize client:", err)
return
}

fmt.Printf("Testing to see token: %s\n", token)
query := make(map[string]string)
resp, err := ol.GetUsers(query)
userQuery := models.UserQuery{}
userList, err := ol.GetUsers(&userQuery)
if err != nil {
fmt.Printf("Failed to get user: %s\n", err)
fmt.Println("Failed to get user:", err)
return
}
fmt.Println(userList)

fmt.Printf("Testing to see user: %s\n", resp)
}
84 changes: 31 additions & 53 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"

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

// Client represents the API client.
Expand All @@ -29,45 +30,38 @@ type HTTPClient interface {
// Authenticator is an interface that defines the GetToken method for retrieving authentication tokens.
type Authenticator interface {
GetToken() (string, error)
NewAuthenticator() *authentication.Authenticator
}

// NewClient creates a new instance of the API client.
func NewClient() *Client {
authenticator := authentication.NewAuthenticator()
token, err := authenticator.GetToken()

if err != nil || token == "" {
_, err := authenticator.GenerateToken()
if err != nil {
// Handle error
fmt.Printf("Failed to generate token: %s", err.Error())
os.Exit(1)
}
func NewClient() (*Client, error) {
old := fmt.Sprintf("https://%s.onelogin.com", os.Getenv("ONELOGIN_SUBDOMAIN"))
authenticator := authentication.NewAuthenticator(old)
err := authenticator.GenerateToken()
if err != nil {
return nil, olerror.NewSDKError("Failed to initialize client")
}

return &Client{
HttpClient: http.DefaultClient,
Auth: authenticator,
OLdomain: fmt.Sprintf("https://%s.onelogin.com", os.Getenv("ONELOGIN_SUBDOMAIN")),
}
OLdomain: old,
}, nil
}

// newRequest creates a new HTTP request with the specified method, path, query parameters, and request body.
func (c *Client) newRequest(method, path string, queryParams *map[string]string, body io.Reader) (*http.Request, error) {
// Parse the OneLogin domain and path
u, err := url.Parse(c.OLdomain + path)
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
if err != nil {
return nil, err
}

// Add query parameters to the URL
query := u.Query()
if queryParams != nil {
for key, value := range *queryParams {
query.Add(key, value)
}
// Parse the OneLogin domain and path
u, err := url.Parse(c.OLdomain + *path)
if err != nil {
return nil, err
}
u.RawQuery = query.Encode()

// Create a new HTTP request
req, err := http.NewRequest(method, u.String(), body)
Expand All @@ -82,14 +76,14 @@ func (c *Client) newRequest(method, path string, queryParams *map[string]string,
}

// 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 *map[string]string) ([]byte, 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 All @@ -99,8 +93,8 @@ func (c *Client) Get(path string, queryParams *map[string]string) ([]byte, error
}

// Delete sends a DELETE request to the specified path with the given query parameters.
func (c *Client) Delete(path string, queryParams *map[string]string) ([]byte, error) {
req, err := c.newRequest(http.MethodDelete, path, queryParams, http.NoBody)
func (c *Client) Delete(path *string) (*http.Response, error) {
req, err := c.newRequest(http.MethodDelete, path, nil, http.NoBody)
if err != nil {
return nil, err
}
Expand All @@ -109,7 +103,7 @@ func (c *Client) Delete(path string, queryParams *map[string]string) ([]byte, er
}

// Post sends a POST request to the specified path with the given query parameters and request body.
func (c *Client) Post(path string, queryParams *map[string]string, body interface{}) ([]byte, error) {
func (c *Client) Post(path *string, body interface{}) (*http.Response, error) {
var bodyReader io.Reader

if body != nil {
Expand All @@ -121,7 +115,7 @@ func (c *Client) Post(path string, queryParams *map[string]string, body interfac
bodyReader = bytes.NewReader(jsonBody)
}

req, err := c.newRequest(http.MethodPost, path, queryParams, bodyReader)
req, err := c.newRequest(http.MethodPost, path, nil, bodyReader)
if err != nil {
return nil, err
}
Expand All @@ -130,38 +124,32 @@ func (c *Client) Post(path string, queryParams *map[string]string, body interfac
}

// Put sends a PUT request to the specified path with the given query parameters and request body.
func (c *Client) Put(path string, queryParams *map[string]string, body interface{}) ([]byte, error) {
func (c *Client) Put(path *string, body interface{}) (*http.Response, error) {
// Convert request body to JSON
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, err
}

req, err := c.newRequest(http.MethodPut, path, queryParams, bytes.NewReader(jsonBody))
req, err := c.newRequest(http.MethodPut, path, nil, bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}

return c.sendRequest(req)
}

// sendRequest sends the specified HTTP request and returns the response body.
func (c *Client) sendRequest(req *http.Request) ([]byte, error) {
// sendRequest sends the specified HTTP request and returns the HTTP response.
func (c *Client) sendRequest(req *http.Request) (*http.Response, error) {
resp, err := c.HttpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}

// Check for API errors
if resp.StatusCode == http.StatusUnauthorized {
// Regenerate the token and reattempt the request
_, err := c.Auth.GenerateToken()
err := c.Auth.GenerateToken()
if err != nil {
return nil, olerror.NewAuthenticationError("Failed to refresh access token")
}
Expand All @@ -171,17 +159,7 @@ func (c *Client) sendRequest(req *http.Request) ([]byte, error) {
if err != nil {
return nil, err
}
defer resp.Body.Close()

respBody, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
} else if resp.StatusCode >= http.StatusBadRequest {
message := fmt.Sprintf("%b", respBody)
apiError := olerror.NewAPIError(message, resp.StatusCode)
return nil, apiError
}

return respBody, nil
return resp, nil
}
30 changes: 15 additions & 15 deletions internal/authentication/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
)

const (
Domain string = "https://api.onelogin.com"
TokenPath string = "/auth/oauth2/v2/token"
RevokePath string = "/auth/oauth2/revoke"
)
Expand All @@ -23,23 +22,24 @@ type Authenticator struct {
OLDomain *string
}

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

func (a *Authenticator) GenerateToken() (string, error) {
func (a *Authenticator) GenerateToken() error {
// Read & Check environment variables
clientID := os.Getenv("ONELOGIN_CLIENT_ID")
if len(clientID) == 0 {
return "", olError.NewAuthenticationError("Missing ONELOGIN_CLIENT_ID Env Variable")
return olError.NewAuthenticationError("Missing ONELOGIN_CLIENT_ID Env Variable")
}
clientSecret := os.Getenv("ONELOGIN_CLIENT_SECRET")
if len(clientSecret) == 0 {
return "", olError.NewAuthenticationError("Missing ONELOGIN_CLIENT_SECRET Env Variable")
return olError.NewAuthenticationError("Missing ONELOGIN_CLIENT_SECRET Env Variable")
}

// Construct the authentication URL
Expand All @@ -53,13 +53,13 @@ func (a *Authenticator) GenerateToken() (string, error) {
// Convert payload to JSON
jsonData, err := json.Marshal(data)
if err != nil {
return "", olError.NewSerializationError("Unable to convert payload to JSON")
return olError.NewSerializationError("Unable to convert payload to JSON")
}

// Create HTTP request
req, err := http.NewRequest(http.MethodPost, authURL, strings.NewReader(string(jsonData)))
if err != nil {
return "", olError.NewRequestError("Failed to create authentication request")
return olError.NewRequestError("Failed to create authentication request")
}

// Add authorization header with base64-encoded credentials
Expand All @@ -71,31 +71,31 @@ func (a *Authenticator) GenerateToken() (string, error) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", olError.NewRequestError("Failed to send authentication request")
return olError.NewRequestError("Failed to send authentication request")
}

// Parse the authentication response
var result map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return "", olError.NewSerializationError("Failed to read authentication response")
return olError.NewSerializationError("Failed to read authentication response")
}

// Check if authentication failed
if resp.StatusCode != http.StatusOK {
return "", olError.NewAuthenticationError("Authentication failed")
return olError.NewAuthenticationError("Authentication failed")
}

// Extract access token from the response
accessToken, ok := result["access_token"].(string)
if !ok {
return "", olError.NewAuthenticationError("Authentication Failed at Endpoint")
return olError.NewAuthenticationError("Authentication Failed at Endpoint")
}

// Store access token
*a.accessToken = accessToken

return accessToken, nil
return nil
}

func (a *Authenticator) RevokeToken(token, domain *string) error {
Expand Down Expand Up @@ -153,6 +153,6 @@ func (a *Authenticator) RevokeToken(token, domain *string) error {
return nil
}

func (a *Authenticator) GetToken() (string, error) {
return *a.accessToken, nil
func (a *Authenticator) GetToken() (*string, error) {
return a.accessToken, nil
}
13 changes: 12 additions & 1 deletion internal/error/sdk_error.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
package error

import "fmt"

type SDKError struct {
Message string
Code string
}

func (e *SDKError) Error() string {
return fmt.Sprintf("SDK error: %s", e.Message)
}

func NewSDKError(message string) *SDKError {
return &SDKError{
Message: message,
}
}
20 changes: 20 additions & 0 deletions internal/models/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,23 @@ const (
UnitMinutes = 1
UnitHours = 2
)

type AppQuery struct {
Limit string
Page string
Cursor string
Name *string `json:"name,omitempty"`
ConnectorID *int `json:"connector_id,omitempty"`
AuthMethod *int `json:"auth_method,omitempty"`
}

func (q *AppQuery) GetKeyValidators() map[string]func(interface{}) bool {
return map[string]func(interface{}) bool{
"limit": validateString,
"page": validateString,
"cursor": validateString,
"name": validateString,
"connector_id": validateInt,
"auth_method": validateInt,
}
}
24 changes: 24 additions & 0 deletions internal/models/app_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,27 @@ type AppRule struct {
Conditions []Condition `json:"conditions"`
Actions []Action `json:"actions"`
}

type AppRuleQuery struct {
Limit string
Page string
Cursor string
Enabled bool `json:"enabled,omitempty"`
HasCondition *string `json:"has_condition,omitempty"`
HasConditionType *string `json:"has_condition_type,omitempty"`
HasAction *string `json:"has_action,omitempty"`
HasActionType *string `json:"has_action_type,omitempty"`
}

func (q *AppRuleQuery) GetKeyValidators() map[string]func(interface{}) bool {
return map[string]func(interface{}) bool{
"limit": validateString,
"page": validateString,
"cursor": validateString,
"enabled": validateBool,
"has_condition": validateString,
"has_condition_type": validateString,
"has_action": validateString,
"has_action_type": validateString,
}
}
Loading

0 comments on commit 2cdfbdc

Please sign in to comment.