// Package goctk provides methods for interacting with the CTKAPI of Core package goctk import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "strings" "time" "github.com/sirupsen/logrus" ) const ( // URLProd defines the ctkapi url in an exported fashion so // we can use the same url const across packages. URLProd = "https://ws.core.rackspace.com/ctkapi" // URLStage defines the ctkapi url in an exported fashion so // we can use the same url const across packages. URLStage = "https://staging.core.rackspace.com/ctkapi" ) var ( // ErrNoToken defines a specific error when a client // gets initialized with a blank token value. ErrNoToken = errors.New("token cannot be empty") // ErrInvalidToken defines the specific error when a token // is no longer valid for use with CTK. ErrInvalidToken = errors.New("goctk: Invalid token") // sub is a replacer type intended for formatting payloads to CTK. // TBH, I have no idea why were doing this. Leaving it for now. sub = strings.NewReplacer( "\\u003e", ">", "\\u0026", "&", "\\u003c", "<", ) ) type ( // Client type describes the parameters needed to // interact with CTK. A Client must be initialized to access // CTK methods. Client struct { Token string Type string url string staging bool user, pass string } // Auth defines a signature for an auth type passed into the // CTK init function. Auth func(c *Client) // Option defines a signature for an Option passed into the // CTK init function. Option func(c *Client) // Info type represents the values returned from CTK as a // result of calling the /session/token resource. Info struct { UserName string `json:"username"` Valid bool `json:"valid"` ContactID int `json:"contact_id"` EmployeeNum int `json:"employee_number"` Departments []string `json:"departments"` } AuthPayload struct { Password string `json:"password"` AuthToken string `json:"authtoken"` } LoadArg struct { Values []interface{} `json:"values"` Class string `json:"class"` Limit *int `json:"limit,omitempty"` Offset *int `json:"offset,omitempty"` } ctkWhereQuery struct { Class string `json:"class"` LoadArg LoadArg `json:"load_arg"` Attributes interface{} `json:"attributes"` } ctkMethod struct { Class string `json:"class"` LoadArg interface{} `json:"load_arg"` Method string `json:"method"` KeywordArgs map[string]string `json:"keyword_args"` ResultMap map[string]string `json:"result_map"` Args []interface{} `json:"args"` } ctkMethodResp []struct { Count int `json:"count"` LoadArg json.RawMessage `json:"load_arg"` Success bool `json:"success"` Method string `json:"method"` Limit int `json:"limit"` Result json.RawMessage `json:"result"` Offset int `json:"offset"` Class string `json:"class"` } ctkQuery struct { Class string `json:"class"` LoadArg interface{} `json:"load_arg"` Attributes interface{} `json:"attributes"` } ctkError struct { ErrorMessage string `json:"error_message"` } coreResponse []struct { Count int `json:"count"` LoadArg json.RawMessage `json:"load_arg"` Limit int `json:"limit"` Result []json.RawMessage `json:"result"` Offset int `json:"offset"` Class string `json:"class"` } // CoreClass is the generic class used to reference other objects in CTKAPI responses CoreClass struct { ClassType string `json:"class_type"` ClassName string `json:"class_name"` LoadValue int `json:"load_value"` LoadKey string `json:"load_key"` Attributes string `json:"attributes"` Methods string `json:"methods"` } ) // WithStaging sets the client to staging during the init function. func WithStaging(staging bool) Option { return func(c *Client) { c.staging = staging } } // SSO sets the username/password value in the client type. func SSO(user, pass string) Auth { return func(c *Client) { c.Type = "X-Auth" c.user = user c.pass = pass } } // Token sets the token value in the client type. func Token(token string) Auth { return func(c *Client) { c.Type = "X-Auth" if len(token) > 35 { c.Type = "X-Auth-Token" } c.Token = token } } // NewCTK returns a CTK client created from the provided username and password func NewCTK(auth Auth, opts ...Option) (*Client, error) { var c = new(Client) // Set the authentication method. auth(c) // Sets any options applied to the initialization for _, opt := range opts { opt(c) } // Sets the URL to the correct value based on the staging // applied in Opts c.url = func() string { if c.staging { return URLStage } return URLProd }() if c.user != "" && c.pass != "" { ap := &AuthPayload{ Password: c.pass, } p, err := json.Marshal(&ap) if err != nil { return nil, err } res, err := c.Post(p, fmt.Sprintf("/login/%s", c.user)) if err != nil { return nil, err } if err := json.Unmarshal(res, ap); err != nil { return nil, err } c.Token = ap.AuthToken return c, nil } return c, nil } // UserInfo is a method to check CTK token information without having to initialize // a client. func UserInfo(token string, staging bool) (info Info, err error) { if token == "" { return info, ErrNoToken } var url = func() string { if staging { return URLStage } return URLProd }() // NewRequest returns a new Request given a method, URL, and optional body. req, err := http.NewRequest( http.MethodGet, fmt.Sprintf("%s/session/%s", url, token), nil, ) if err != nil { logrus.Errorf("goctk.UserInfo().NewRequest:%s", err) return } res, err := http.DefaultClient.Do(req) if res != nil { // Note: We use a func to error check defer as opposed to using // defer res.Body.Close(), which will never return an error. defer func() { if defErr := res.Body.Close(); defErr != nil { err = fmt.Errorf("%s:%s", err, defErr) } }() } if err != nil { logrus.Errorf("goctk.UserInfo().Do:%s", err) return } if err := json.NewDecoder(res.Body).Decode(&info); err != nil { logrus.Errorf("goctk.UserInfo().Decode:%s", err) } return } // Query method is used to craft a /query/ call to CTK and // retry if there are failures. func (c *Client) Query(payload []byte) ([]byte, error) { var ( res []byte err error attempts = 0 ) for true { attempts += 1 // Send the request res, err = c.Post(payload, "/query/") if err != nil { // If we've tried 5 times, quit and return error if attempts >= 5 { return nil, err } // Pause 1/2 second before retrying time.Sleep(time.Second / 2) continue } break } return res, nil } // Post is the base method for calls to CTK. func (c *Client) Post(payload []byte, path string) ([]byte, error) { // NewRequest returns a new Request given a method, URL, and optional body. req, err := http.NewRequest( http.MethodPost, fmt.Sprintf("%s%s", c.url, path), strings.NewReader(sub.Replace(string(payload))), ) if err != nil { return nil, err } // Setting the request header for CTK token auth req.Header.Set(c.Type, c.Token) res, err := http.DefaultClient.Do(req) if res != nil { // Note: We use a func to error check defer as opposed to using // defer res.Body.Close(), which will never return an error. defer func() { if defErr := res.Body.Close(); defErr != nil { err = fmt.Errorf("%s:%s", err, defErr) } }() } if err != nil { return nil, err } if res.StatusCode > http.StatusNoContent { em := new(ctkError) if err = json.NewDecoder(res.Body).Decode(em); err != nil { return nil, fmt.Errorf("unexpect response code: %d", res.StatusCode) } return nil, errors.New(em.ErrorMessage) } return ioutil.ReadAll(res.Body) } // Logout logs us out of CORE and sets token to nil func (c *Client) Logout() error { // NewRequest returns a new Request given a method, URL, and optional body. req, err := http.NewRequest( http.MethodGet, fmt.Sprintf("%s/logout/%s", c.url, c.Token), nil, ) if err != nil { return fmt.Errorf("goctk.Logout().NewRequest:%s", err) } res, err := http.DefaultClient.Do(req) if res != nil { defer func() { if defErr := res.Body.Close(); defErr != nil { err = fmt.Errorf("%s:%s", err, defErr) } }() } if err != nil { return fmt.Errorf("goctk.Logout().Do:%s", err) } if res.StatusCode != http.StatusOK { return fmt.Errorf("goctk.UserInfo():%s", res.Status) } c.Token = "" return nil } // SetAttribute sets a core attribute on a given class func (c *Client) SetAttribute(class, attribute, payload, loadValue string) error { req, err := http.NewRequest( http.MethodPost, fmt.Sprintf("%s/attribute/%s/%s/%s", c.url, class, loadValue, attribute), strings.NewReader(payload), ) if err != nil { return err } req.Header.Set(c.Type, c.Token) res, err := http.DefaultClient.Do(req) if err != nil { return err } if res != nil { defer func() { if defErr := res.Body.Close(); defErr != nil { err = fmt.Errorf("%s:%s", err, defErr) } }() } body, err := ioutil.ReadAll(res.Body) if err != nil { return err } if string(body) != "true" { return fmt.Errorf("error setting attribute. Response: %v", string(body)) } return nil } // NewTokenClient returns a CTK client using an existing token for Auth // // Deprecated: Use the NewCTK function to init goctk. This function will be // removed in the future. func NewTokenClient(token string, staging bool) (*Client, error) { if token == "" { return nil, ErrNoToken } info, err := UserInfo(token, staging) if err != nil { return nil, err } if !info.Valid { return nil, ErrInvalidToken } return &Client{ Token: token, Type: func() string { if len(token) > 35 { return "X-Auth-Token" } return "X-Auth" }(), url: func() string { if staging { return URLStage } return URLProd }(), staging: staging, }, nil } // New returns a CTK client created from the provided username and password // // Deprecated: Use the NewCTK function to init goctk. This function will be // removed in the future. func New(user, pass string, staging bool) (*Client, error) { ap := &AuthPayload{ Password: pass, } p, err := json.Marshal(&ap) if err != nil { return nil, err } var c = Client{ url: func() string { if staging { return URLStage } return URLProd }(), Type: "X-Auth", staging: staging, } res, err := c.Post(p, "/login/"+user) if err != nil { return nil, err } if err := json.Unmarshal(res, ap); err != nil { return nil, err } c.Token = ap.AuthToken return &c, nil } // Valid is a method that will return a boolean indicating if the // token used in initialization is valid. // // Deprecated: I'm not sure why this is here, you should be able to use the // UserInfo function to get this information. func (c *Client) Valid() bool { if c.Token == "" { return false } info, err := UserInfo(c.Token, c.staging) if err != nil { logrus.Errorf("goctk.Valid().UserInfo:%s", err) return false } return info.Valid }