diff --git a/README.md b/README.md index 96a779d..baadcb6 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ and import this when you need: import "github.com/casdoor/casdoor-go-sdk/casdoorsdk" ``` -## Step2. Init Config +## Step2. Init Initialization requires 6 parameters, which are all string type: @@ -66,10 +66,18 @@ Initialization requires 6 parameters, which are all string type: | organizationName | Yes | Application.organization | | applicationName | Yes | Application.applicationName | +### You can either init the sdk with global config ```go func InitConfig(endpoint string, clientId string, clientSecret string, certificate string, organizationName string, applicationName string) -``` +// Then call sdk functions like +casdoorsdk.GetUsers() +``` +### or create a custom Client with unique config +```go +client := casdoorsdk.NewClient(endpoint, clientId, clientSecret, certificate, organizationName, applicationName) +client.GetUsers() +``` ## Step3. Get token and parse After casdoor verification passed, it will be redirected to your application with code and state, like `https://forum.casbin.com?code=xxx&state=yyyy`. diff --git a/casdoorsdk/application.go b/casdoorsdk/application.go index d9d8efd..907ca42 100644 --- a/casdoorsdk/application.go +++ b/casdoorsdk/application.go @@ -76,7 +76,7 @@ type Application struct { FormBackgroundUrl string `xorm:"varchar(200)" json:"formBackgroundUrl"` } -func AddApplication(application *Application) (bool, error) { +func (c *Client) AddApplication(application *Application) (bool, error) { if application.Owner == "" { application.Owner = "admin" } @@ -85,7 +85,7 @@ func AddApplication(application *Application) (bool, error) { return false, err } - resp, err := DoPost("add-application", nil, postBytes, false, false) + resp, err := c.DoPost("add-application", nil, postBytes, false, false) if err != nil { return false, err } @@ -93,7 +93,11 @@ func AddApplication(application *Application) (bool, error) { return resp.Data == "Affected", nil } -func DeleteApplication(name string) (bool, error) { +func AddApplication(application *Application) (bool, error) { + return globalClient.AddApplication(application) +} + +func (c *Client) DeleteApplication(name string) (bool, error) { application := Application{ Owner: "admin", Name: name, @@ -103,10 +107,14 @@ func DeleteApplication(name string) (bool, error) { return false, err } - resp, err := DoPost("delete-application", nil, postBytes, false, false) + resp, err := c.DoPost("delete-application", nil, postBytes, false, false) if err != nil { return false, err } return resp.Data == "Affected", nil } + +func DeleteApplication(name string) (bool, error) { + return globalClient.DeleteApplication(name) +} diff --git a/casdoorsdk/auth.go b/casdoorsdk/auth.go index 4cb576e..25a97dc 100644 --- a/casdoorsdk/auth.go +++ b/casdoorsdk/auth.go @@ -25,15 +25,30 @@ type AuthConfig struct { ApplicationName string } -var authConfig AuthConfig +type Client struct { + AuthConfig +} + +var globalClient *Client func InitConfig(endpoint string, clientId string, clientSecret string, certificate string, organizationName string, applicationName string) { - authConfig = AuthConfig{ - Endpoint: endpoint, - ClientId: clientId, - ClientSecret: clientSecret, - Certificate: certificate, - OrganizationName: organizationName, - ApplicationName: applicationName, + globalClient = NewClient(endpoint, clientId, clientSecret, certificate, organizationName, applicationName) +} + +func NewClient(endpoint string, clientId string, clientSecret string, certificate string, organizationName string, applicationName string) *Client { + return NewClientWithConf( + &AuthConfig{ + Endpoint: endpoint, + ClientId: clientId, + ClientSecret: clientSecret, + Certificate: certificate, + OrganizationName: organizationName, + ApplicationName: applicationName, + }) +} + +func NewClientWithConf(config *AuthConfig) *Client { + return &Client{ + *config, } } diff --git a/casdoorsdk/base.go b/casdoorsdk/base.go index 466d999..1449f4f 100644 --- a/casdoorsdk/base.go +++ b/casdoorsdk/base.go @@ -25,10 +25,8 @@ import ( "strings" ) -var ( - // client is a shared http Client. - client HttpClient = &http.Client{} -) +// client is a shared http Client. +var client HttpClient = &http.Client{} // SetHttpClient sets custom http Client. func SetHttpClient(httpClient HttpClient) { @@ -49,8 +47,8 @@ type Response struct { } // DoGetResponse is a general function to get response from param url through HTTP Get method. -func DoGetResponse(url string) (*Response, error) { - respBytes, err := doGetBytesRawWithoutCheck(url) +func (c *Client) DoGetResponse(url string) (*Response, error) { + respBytes, err := c.doGetBytesRawWithoutCheck(url) if err != nil { return nil, err } @@ -69,8 +67,8 @@ func DoGetResponse(url string) (*Response, error) { } // DoGetBytes is a general function to get response data in bytes from param url through HTTP Get method. -func DoGetBytes(url string) ([]byte, error) { - response, err := DoGetResponse(url) +func (c *Client) DoGetBytes(url string) ([]byte, error) { + response, err := c.DoGetResponse(url) if err != nil { return nil, err } @@ -84,23 +82,23 @@ func DoGetBytes(url string) ([]byte, error) { } // DoGetBytesRaw is a general function to get response from param url through HTTP Get method. -func DoGetBytesRaw(url string) ([]byte, error) { - respBytes, err := doGetBytesRawWithoutCheck(url) +func (c *Client) DoGetBytesRaw(url string) ([]byte, error) { + respBytes, err := c.doGetBytesRawWithoutCheck(url) if err != nil { return nil, err } var response Response err = json.Unmarshal(respBytes, &response) - if err == nil && response.Status == "error"{ + if err == nil && response.Status == "error" { return nil, errors.New(response.Msg) } return respBytes, nil } -func DoPost(action string, queryMap map[string]string, postBytes []byte, isForm, isFile bool) (*Response, error) { - url := GetUrl(action, queryMap) +func (c *Client) DoPost(action string, queryMap map[string]string, postBytes []byte, isForm, isFile bool) (*Response, error) { + url := c.GetUrl(action, queryMap) var err error var contentType string @@ -128,7 +126,7 @@ func DoPost(action string, queryMap map[string]string, postBytes []byte, isForm, body = bytes.NewReader(postBytes) } - respBytes, err := DoPostBytesRaw(url, contentType, body) + respBytes, err := c.DoPostBytesRaw(url, contentType, body) if err != nil { return nil, err } @@ -147,7 +145,7 @@ func DoPost(action string, queryMap map[string]string, postBytes []byte, isForm, } // DoPostBytesRaw is a general function to post a request from url, body through HTTP Post method. -func DoPostBytesRaw(url string, contentType string, body io.Reader) ([]byte, error) { +func (c *Client) DoPostBytesRaw(url string, contentType string, body io.Reader) ([]byte, error) { if contentType == "" { contentType = "text/plain;charset=UTF-8" } @@ -159,7 +157,7 @@ func DoPostBytesRaw(url string, contentType string, body io.Reader) ([]byte, err return nil, err } - req.SetBasicAuth(authConfig.ClientId, authConfig.ClientSecret) + req.SetBasicAuth(c.ClientId, c.ClientSecret) req.Header.Set("Content-Type", contentType) resp, err = client.Do(req) @@ -182,13 +180,13 @@ func DoPostBytesRaw(url string, contentType string, body io.Reader) ([]byte, err } // doGetBytesRawWithoutCheck is a general function to get response from param url through HTTP Get method without checking response status -func doGetBytesRawWithoutCheck(url string) ([]byte, error) { +func (c *Client) doGetBytesRawWithoutCheck(url string) ([]byte, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } - req.SetBasicAuth(authConfig.ClientId, authConfig.ClientSecret) + req.SetBasicAuth(c.ClientId, c.ClientSecret) resp, err := client.Do(req) if err != nil { @@ -211,11 +209,11 @@ func doGetBytesRawWithoutCheck(url string) ([]byte, error) { // modifyUser is an encapsulation of user CUD(Create, Update, Delete) operations. // possible actions are `add-user`, `update-user`, `delete-user`, -func modifyUser(action string, user *User, columns []string) (*Response, bool, error) { - return modifyUserById(action, user.GetId(), user, columns) +func (c *Client) modifyUser(action string, user *User, columns []string) (*Response, bool, error) { + return c.modifyUserById(action, user.GetId(), user, columns) } -func modifyUserById(action string, id string, user *User, columns []string) (*Response, bool, error) { +func (c *Client) modifyUserById(action string, id string, user *User, columns []string) (*Response, bool, error) { queryMap := map[string]string{ "id": id, } @@ -224,13 +222,13 @@ func modifyUserById(action string, id string, user *User, columns []string) (*Re queryMap["columns"] = strings.Join(columns, ",") } - user.Owner = authConfig.OrganizationName + user.Owner = c.OrganizationName postBytes, err := json.Marshal(user) if err != nil { return nil, false, err } - resp, err := DoPost(action, queryMap, postBytes, false, false) + resp, err := c.DoPost(action, queryMap, postBytes, false, false) if err != nil { return nil, false, err } @@ -240,7 +238,7 @@ func modifyUserById(action string, id string, user *User, columns []string) (*Re // modifyPermission is an encapsulation of permission CUD(Create, Update, Delete) operations. // possible actions are `add-permission`, `update-permission`, `delete-permission`, -func modifyPermission(action string, permission *Permission, columns []string) (*Response, bool, error) { +func (c *Client) modifyPermission(action string, permission *Permission, columns []string) (*Response, bool, error) { queryMap := map[string]string{ "id": fmt.Sprintf("%s/%s", permission.Owner, permission.Name), } @@ -249,13 +247,13 @@ func modifyPermission(action string, permission *Permission, columns []string) ( queryMap["columns"] = strings.Join(columns, ",") } - permission.Owner = authConfig.OrganizationName + permission.Owner = c.OrganizationName postBytes, err := json.Marshal(permission) if err != nil { return nil, false, err } - resp, err := DoPost(action, queryMap, postBytes, false, false) + resp, err := c.DoPost(action, queryMap, postBytes, false, false) if err != nil { return nil, false, err } @@ -265,7 +263,7 @@ func modifyPermission(action string, permission *Permission, columns []string) ( // modifyRole is an encapsulation of role CUD(Create, Update, Delete) operations. // possible actions are `add-role`, `update-role`, `delete-role`, -func modifyRole(action string, role *Role, columns []string) (*Response, bool, error) { +func (c *Client) modifyRole(action string, role *Role, columns []string) (*Response, bool, error) { queryMap := map[string]string{ "id": fmt.Sprintf("%s/%s", role.Owner, role.Name), } @@ -274,13 +272,13 @@ func modifyRole(action string, role *Role, columns []string) (*Response, bool, e queryMap["columns"] = strings.Join(columns, ",") } - role.Owner = authConfig.OrganizationName + role.Owner = c.OrganizationName postBytes, err := json.Marshal(role) if err != nil { return nil, false, err } - resp, err := DoPost(action, queryMap, postBytes, false, false) + resp, err := c.DoPost(action, queryMap, postBytes, false, false) if err != nil { return nil, false, err } diff --git a/casdoorsdk/email.go b/casdoorsdk/email.go index 0de58e7..0df5af3 100644 --- a/casdoorsdk/email.go +++ b/casdoorsdk/email.go @@ -26,7 +26,7 @@ type emailForm struct { Receivers []string `json:"receivers"` } -func SendEmail(title string, content string, sender string, receivers ...string) error { +func (c *Client) SendEmail(title string, content string, sender string, receivers ...string) error { form := emailForm{ Title: title, Content: content, @@ -38,7 +38,7 @@ func SendEmail(title string, content string, sender string, receivers ...string) return err } - resp, err := DoPost("send-email", nil, postBytes, false, false) + resp, err := c.DoPost("send-email", nil, postBytes, false, false) if err != nil { return err } @@ -49,3 +49,7 @@ func SendEmail(title string, content string, sender string, receivers ...string) return nil } + +func SendEmail(title string, content string, sender string, receivers ...string) error { + return globalClient.SendEmail(title, content, sender, receivers...) +} diff --git a/casdoorsdk/enforce.go b/casdoorsdk/enforce.go index 2cc80fa..0622eb5 100644 --- a/casdoorsdk/enforce.go +++ b/casdoorsdk/enforce.go @@ -32,13 +32,13 @@ type PermissionRule struct { type CasbinRequest = []interface{} -func Enforce(permissionId, modelId, resourceId string, casbinRequest CasbinRequest) (bool, error) { +func (c *Client) Enforce(permissionId, modelId, resourceId string, casbinRequest CasbinRequest) (bool, error) { postBytes, err := json.Marshal(casbinRequest) if err != nil { return false, err } - res, err := doEnforce("enforce", permissionId, modelId, resourceId, postBytes) + res, err := c.doEnforce("enforce", permissionId, modelId, resourceId, postBytes) if err != nil { return false, err } @@ -62,13 +62,17 @@ func Enforce(permissionId, modelId, resourceId string, casbinRequest CasbinReque return false, nil } -func BatchEnforce(permissionId, modelId, resourceId string, casbinRequests []CasbinRequest) ([][]bool, error) { +func Enforce(permissionId, modelId, resourceId string, casbinRequest CasbinRequest) (bool, error) { + return globalClient.Enforce(permissionId, modelId, resourceId, casbinRequest) +} + +func (c *Client) BatchEnforce(permissionId, modelId, resourceId string, casbinRequests []CasbinRequest) ([][]bool, error) { postBytes, err := json.Marshal(casbinRequests) if err != nil { return nil, err } - res, err := doEnforce("batch-enforce", permissionId, modelId, resourceId, postBytes) + res, err := c.doEnforce("batch-enforce", permissionId, modelId, resourceId, postBytes) if err != nil { return nil, err } @@ -98,15 +102,19 @@ func BatchEnforce(permissionId, modelId, resourceId string, casbinRequests []Cas return allows, nil } -func doEnforce(action string, permissionId, modelId, resourceId string, postBytes []byte) (*Response, error) { +func BatchEnforce(permissionId, modelId, resourceId string, casbinRequests []CasbinRequest) ([][]bool, error) { + return globalClient.BatchEnforce(permissionId, modelId, resourceId, casbinRequests) +} + +func (c *Client) doEnforce(action string, permissionId, modelId, resourceId string, postBytes []byte) (*Response, error) { queryMap := map[string]string{ "permissionId": permissionId, "modelId": modelId, "resourceId": resourceId, } - //bytes, err := DoPostBytesRaw(url, "", bytes.NewBuffer(postBytes)) - resp, err := DoPost(action, queryMap, postBytes, false, false) + // bytes, err := DoPostBytesRaw(url, "", bytes.NewBuffer(postBytes)) + resp, err := c.DoPost(action, queryMap, postBytes, false, false) if err != nil { return nil, err } diff --git a/casdoorsdk/jwt.go b/casdoorsdk/jwt.go index 69d1a13..11496d7 100644 --- a/casdoorsdk/jwt.go +++ b/casdoorsdk/jwt.go @@ -26,13 +26,13 @@ type Claims struct { jwt.RegisteredClaims } -func ParseJwtToken(token string) (*Claims, error) { +func (c *Client) ParseJwtToken(token string) (*Claims, error) { t, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } - publicKey, err := jwt.ParseRSAPublicKeyFromPEM([]byte(authConfig.Certificate)) + publicKey, err := jwt.ParseRSAPublicKeyFromPEM([]byte(c.Certificate)) if err != nil { return nil, err } @@ -48,3 +48,7 @@ func ParseJwtToken(token string) (*Claims, error) { return nil, err } + +func ParseJwtToken(token string) (*Claims, error) { + return globalClient.ParseJwtToken(token) +} diff --git a/casdoorsdk/organization.go b/casdoorsdk/organization.go index 6c65dce..bbc5142 100644 --- a/casdoorsdk/organization.go +++ b/casdoorsdk/organization.go @@ -45,7 +45,7 @@ type Organization struct { AccountItems []*AccountItem `xorm:"varchar(3000)" json:"accountItems"` } -func AddOrganization(organization *Organization) (bool, error) { +func (c *Client) AddOrganization(organization *Organization) (bool, error) { if organization.Owner == "" { organization.Owner = "admin" } @@ -54,7 +54,7 @@ func AddOrganization(organization *Organization) (bool, error) { return false, err } - resp, err := DoPost("add-organization", nil, postBytes, false, false) + resp, err := c.DoPost("add-organization", nil, postBytes, false, false) if err != nil { return false, err } @@ -62,7 +62,11 @@ func AddOrganization(organization *Organization) (bool, error) { return resp.Data == "Affected", nil } -func DeleteOrganization(name string) (bool, error) { +func AddOrganization(organization *Organization) (bool, error) { + return globalClient.AddOrganization(organization) +} + +func (c *Client) DeleteOrganization(name string) (bool, error) { organization := Organization{ Owner: "admin", Name: name, @@ -72,10 +76,14 @@ func DeleteOrganization(name string) (bool, error) { return false, err } - resp, err := DoPost("delete-organization", nil, postBytes, false, false) + resp, err := c.DoPost("delete-organization", nil, postBytes, false, false) if err != nil { return false, err } return resp.Data == "Affected", nil } + +func DeleteOrganization(name string) (bool, error) { + return globalClient.DeleteOrganization(name) +} diff --git a/casdoorsdk/permission.go b/casdoorsdk/permission.go index 5b379f0..0d96d2c 100644 --- a/casdoorsdk/permission.go +++ b/casdoorsdk/permission.go @@ -44,14 +44,14 @@ type Permission struct { State string `xorm:"varchar(100)" json:"state"` } -func GetPermissions() ([]*Permission, error) { +func (c *Client) GetPermissions() ([]*Permission, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, } - url := GetUrl("get-permissions", queryMap) + url := c.GetUrl("get-permissions", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -64,14 +64,18 @@ func GetPermissions() ([]*Permission, error) { return permissions, nil } -func GetPermissionsByRole(name string) ([]*Permission, error) { +func GetPermissions() ([]*Permission, error) { + return globalClient.GetPermissions() +} + +func (c *Client) GetPermissionsByRole(name string) ([]*Permission, error) { queryMap := map[string]string{ - "id": fmt.Sprintf("%s/%s", authConfig.OrganizationName, name), + "id": fmt.Sprintf("%s/%s", c.OrganizationName, name), } - url := GetUrl("get-permissions-by-role", queryMap) + url := c.GetUrl("get-permissions-by-role", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -84,14 +88,18 @@ func GetPermissionsByRole(name string) ([]*Permission, error) { return permissions, nil } -func GetPaginationPermissions(p int, pageSize int, queryMap map[string]string) ([]*Permission, int, error) { - queryMap["owner"] = authConfig.OrganizationName +func GetPermissionsByRole(name string) ([]*Permission, error) { + return globalClient.GetPermissionsByRole(name) +} + +func (c *Client) GetPaginationPermissions(p int, pageSize int, queryMap map[string]string) ([]*Permission, int, error) { + queryMap["owner"] = c.OrganizationName queryMap["p"] = strconv.Itoa(p) queryMap["pageSize"] = strconv.Itoa(pageSize) - url := GetUrl("get-permissions", queryMap) + url := c.GetUrl("get-permissions", queryMap) - response, err := DoGetResponse(url) + response, err := c.DoGetResponse(url) if err != nil { return nil, 0, err } @@ -113,14 +121,18 @@ func GetPaginationPermissions(p int, pageSize int, queryMap map[string]string) ( return permissions, int(response.Data2.(float64)), nil } -func GetPermission(name string) (*Permission, error) { +func GetPaginationPermissions(p int, pageSize int, queryMap map[string]string) ([]*Permission, int, error) { + return globalClient.GetPaginationPermissions(p, pageSize, queryMap) +} + +func (c *Client) GetPermission(name string) (*Permission, error) { queryMap := map[string]string{ - "id": fmt.Sprintf("%s/%s", authConfig.OrganizationName, name), + "id": fmt.Sprintf("%s/%s", c.OrganizationName, name), } - url := GetUrl("get-permission", queryMap) + url := c.GetUrl("get-permission", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -133,22 +145,42 @@ func GetPermission(name string) (*Permission, error) { return permission, nil } +func GetPermission(name string) (*Permission, error) { + return globalClient.GetPermission(name) +} + +func (c *Client) UpdatePermission(permission *Permission) (bool, error) { + _, affected, err := c.modifyPermission("update-permission", permission, nil) + return affected, err +} + func UpdatePermission(permission *Permission) (bool, error) { - _, affected, err := modifyPermission("update-permission", permission, nil) + return globalClient.UpdatePermission(permission) +} + +func (c *Client) UpdatePermissionForColumns(permission *Permission, columns []string) (bool, error) { + _, affected, err := c.modifyPermission("update-permission", permission, columns) return affected, err } func UpdatePermissionForColumns(permission *Permission, columns []string) (bool, error) { - _, affected, err := modifyPermission("update-permission", permission, columns) + return globalClient.UpdatePermissionForColumns(permission, columns) +} + +func (c *Client) AddPermission(permission *Permission) (bool, error) { + _, affected, err := c.modifyPermission("add-permission", permission, nil) return affected, err } func AddPermission(permission *Permission) (bool, error) { - _, affected, err := modifyPermission("add-permission", permission, nil) + return globalClient.AddPermission(permission) +} + +func (c *Client) DeletePermission(permission *Permission) (bool, error) { + _, affected, err := c.modifyPermission("delete-permission", permission, nil) return affected, err } func DeletePermission(permission *Permission) (bool, error) { - _, affected, err := modifyPermission("delete-permission", permission, nil) - return affected, err + return globalClient.DeletePermission(permission) } diff --git a/casdoorsdk/record.go b/casdoorsdk/record.go index 685f446..f3c61ca 100644 --- a/casdoorsdk/record.go +++ b/casdoorsdk/record.go @@ -35,12 +35,12 @@ type Record struct { IsTriggered bool `json:"isTriggered"` } -func AddRecord(record *Record) (bool, error) { +func (c *Client) AddRecord(record *Record) (bool, error) { if record.Owner == "" { - record.Owner = authConfig.OrganizationName + record.Owner = c.OrganizationName } if record.Organization == "" { - record.Organization = authConfig.OrganizationName + record.Organization = c.OrganizationName } postBytes, err := json.Marshal(record) @@ -48,10 +48,14 @@ func AddRecord(record *Record) (bool, error) { return false, err } - resp, err := DoPost("add-record", nil, postBytes, false, false) + resp, err := c.DoPost("add-record", nil, postBytes, false, false) if err != nil { return false, err } return resp.Data == "Affected", nil } + +func AddRecord(record *Record) (bool, error) { + return globalClient.AddRecord(record) +} diff --git a/casdoorsdk/resource.go b/casdoorsdk/resource.go index dc260ba..2890a61 100644 --- a/casdoorsdk/resource.go +++ b/casdoorsdk/resource.go @@ -39,15 +39,15 @@ type Resource struct { Description string `xorm:"varchar(1000)" json:"description"` } -func GetResource(id string) (*Resource, error) { +func (c *Client) GetResource(id string) (*Resource, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "id": id, } - url := GetUrl("get-resource", queryMap) + url := c.GetUrl("get-resource", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -61,11 +61,19 @@ func GetResource(id string) (*Resource, error) { return resource, nil } +func GetResource(id string) (*Resource, error) { + return globalClient.GetResource(id) +} + +func (c *Client) GetResourceEx(owner, name string) (*Resource, error) { + return c.GetResource(fmt.Sprintf("%s/%s", owner, name)) +} + func GetResourceEx(owner, name string) (*Resource, error) { - return GetResource(fmt.Sprintf("%s/%s", owner, name)) + return globalClient.GetResourceEx(owner, name) } -func GetResources(owner, user, field, value, sortField, sortOrder string) ([]*Resource, error) { +func (c *Client) GetResources(owner, user, field, value, sortField, sortOrder string) ([]*Resource, error) { queryMap := map[string]string{ "owner": owner, "user": user, @@ -75,9 +83,9 @@ func GetResources(owner, user, field, value, sortField, sortOrder string) ([]*Re "sortOrder": sortOrder, } - url := GetUrl("get-resources", queryMap) + url := c.GetUrl("get-resources", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -90,7 +98,11 @@ func GetResources(owner, user, field, value, sortField, sortOrder string) ([]*Re return resources, nil } -func GetPaginationResources(owner, user, field, value string, pageSize, page int, sortField, sortOrder string) ([]*Resource, error) { +func GetResources(owner, user, field, value, sortField, sortOrder string) ([]*Resource, error) { + return globalClient.GetResources(owner, user, field, value, sortField, sortOrder) +} + +func (c *Client) GetPaginationResources(owner, user, field, value string, pageSize, page int, sortField, sortOrder string) ([]*Resource, error) { queryMap := map[string]string{ "owner": owner, "user": user, @@ -102,9 +114,9 @@ func GetPaginationResources(owner, user, field, value string, pageSize, page int "sortOrder": sortOrder, } - url := GetUrl("get-resources", queryMap) + url := c.GetUrl("get-resources", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -117,17 +129,21 @@ func GetPaginationResources(owner, user, field, value string, pageSize, page int return resources, nil } -func UploadResource(user string, tag string, parent string, fullFilePath string, fileBytes []byte) (string, string, error) { +func GetPaginationResources(owner, user, field, value string, pageSize, page int, sortField, sortOrder string) ([]*Resource, error) { + return globalClient.GetPaginationResources(owner, user, field, value, pageSize, page, sortField, sortOrder) +} + +func (c *Client) UploadResource(user string, tag string, parent string, fullFilePath string, fileBytes []byte) (string, string, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "user": user, - "application": authConfig.ApplicationName, + "application": c.ApplicationName, "tag": tag, "parent": parent, "fullFilePath": fullFilePath, } - resp, err := DoPost("upload-resource", queryMap, fileBytes, true, true) + resp, err := c.DoPost("upload-resource", queryMap, fileBytes, true, true) if err != nil { return "", "", err } @@ -141,11 +157,15 @@ func UploadResource(user string, tag string, parent string, fullFilePath string, return fileUrl, name, nil } -func UploadResourceEx(user string, tag string, parent string, fullFilePath string, fileBytes []byte, createdTime string, description string) (string, string, error) { +func UploadResource(user string, tag string, parent string, fullFilePath string, fileBytes []byte) (string, string, error) { + return globalClient.UploadResource(user, tag, parent, fullFilePath, fileBytes) +} + +func (c *Client) UploadResourceEx(user string, tag string, parent string, fullFilePath string, fileBytes []byte, createdTime string, description string) (string, string, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "user": user, - "application": authConfig.ApplicationName, + "application": c.ApplicationName, "tag": tag, "parent": parent, "fullFilePath": fullFilePath, @@ -153,7 +173,7 @@ func UploadResourceEx(user string, tag string, parent string, fullFilePath strin "description": description, } - resp, err := DoPost("upload-resource", queryMap, fileBytes, true, true) + resp, err := c.DoPost("upload-resource", queryMap, fileBytes, true, true) if err != nil { return "", "", err } @@ -167,9 +187,13 @@ func UploadResourceEx(user string, tag string, parent string, fullFilePath strin return fileUrl, name, nil } -func DeleteResource(name string) (bool, error) { +func UploadResourceEx(user string, tag string, parent string, fullFilePath string, fileBytes []byte, createdTime string, description string) (string, string, error) { + return globalClient.UploadResourceEx(user, tag, parent, fullFilePath, fileBytes, createdTime, description) +} + +func (c *Client) DeleteResource(name string) (bool, error) { resource := Resource{ - Owner: authConfig.OrganizationName, + Owner: c.OrganizationName, Name: name, } postBytes, err := json.Marshal(resource) @@ -177,10 +201,14 @@ func DeleteResource(name string) (bool, error) { return false, err } - resp, err := DoPost("delete-resource", nil, postBytes, false, false) + resp, err := c.DoPost("delete-resource", nil, postBytes, false, false) if err != nil { return false, err } return resp.Data == "Affected", nil } + +func DeleteResource(name string) (bool, error) { + return globalClient.DeleteResource(name) +} diff --git a/casdoorsdk/role.go b/casdoorsdk/role.go index 3ee8217..4748948 100644 --- a/casdoorsdk/role.go +++ b/casdoorsdk/role.go @@ -33,14 +33,14 @@ type Role struct { IsEnabled bool `json:"isEnabled"` } -func GetRoles() ([]*Role, error) { +func (c *Client) GetRoles() ([]*Role, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, } - url := GetUrl("get-roles", queryMap) + url := c.GetUrl("get-roles", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -53,14 +53,18 @@ func GetRoles() ([]*Role, error) { return roles, nil } -func GetPaginationRoles(p int, pageSize int, queryMap map[string]string) ([]*Role, int, error) { - queryMap["owner"] = authConfig.OrganizationName +func GetRoles() ([]*Role, error) { + return globalClient.GetRoles() +} + +func (c *Client) GetPaginationRoles(p int, pageSize int, queryMap map[string]string) ([]*Role, int, error) { + queryMap["owner"] = c.OrganizationName queryMap["p"] = strconv.Itoa(p) queryMap["pageSize"] = strconv.Itoa(pageSize) - url := GetUrl("get-roles", queryMap) + url := c.GetUrl("get-roles", queryMap) - response, err := DoGetResponse(url) + response, err := c.DoGetResponse(url) if err != nil { return nil, 0, err } @@ -78,14 +82,18 @@ func GetPaginationRoles(p int, pageSize int, queryMap map[string]string) ([]*Rol return roles, int(response.Data2.(float64)), nil } -func GetRole(name string) (*Role, error) { +func GetPaginationRoles(p int, pageSize int, queryMap map[string]string) ([]*Role, int, error) { + return globalClient.GetPaginationRoles(p, pageSize, queryMap) +} + +func (c *Client) GetRole(name string) (*Role, error) { queryMap := map[string]string{ - "id": fmt.Sprintf("%s/%s", authConfig.OrganizationName, name), + "id": fmt.Sprintf("%s/%s", c.OrganizationName, name), } - url := GetUrl("get-role", queryMap) + url := c.GetUrl("get-role", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -98,22 +106,42 @@ func GetRole(name string) (*Role, error) { return role, nil } +func GetRole(name string) (*Role, error) { + return globalClient.GetRole(name) +} + +func (c *Client) UpdateRole(role *Role) (bool, error) { + _, affected, err := c.modifyRole("update-role", role, nil) + return affected, err +} + func UpdateRole(role *Role) (bool, error) { - _, affected, err := modifyRole("update-role", role, nil) + return globalClient.UpdateRole(role) +} + +func (c *Client) UpdateRoleForColumns(role *Role, columns []string) (bool, error) { + _, affected, err := c.modifyRole("update-role", role, columns) return affected, err } func UpdateRoleForColumns(role *Role, columns []string) (bool, error) { - _, affected, err := modifyRole("update-role", role, columns) + return globalClient.UpdateRoleForColumns(role, columns) +} + +func (c *Client) AddRole(role *Role) (bool, error) { + _, affected, err := c.modifyRole("add-role", role, nil) return affected, err } func AddRole(role *Role) (bool, error) { - _, affected, err := modifyRole("add-role", role, nil) + return globalClient.AddRole(role) +} + +func (c *Client) DeleteRole(role *Role) (bool, error) { + _, affected, err := c.modifyRole("delete-role", role, nil) return affected, err } func DeleteRole(role *Role) (bool, error) { - _, affected, err := modifyRole("delete-role", role, nil) - return affected, err + return globalClient.DeleteRole(role) } diff --git a/casdoorsdk/sms.go b/casdoorsdk/sms.go index 61839ba..9293260 100644 --- a/casdoorsdk/sms.go +++ b/casdoorsdk/sms.go @@ -24,7 +24,7 @@ type smsForm struct { Receivers []string `json:"receivers"` } -func SendSms(content string, receivers ...string) error { +func (c *Client) SendSms(content string, receivers ...string) error { form := smsForm{ Content: content, Receivers: receivers, @@ -34,7 +34,7 @@ func SendSms(content string, receivers ...string) error { return err } - resp, err := DoPost("send-sms", nil, postBytes, false, false) + resp, err := c.DoPost("send-sms", nil, postBytes, false, false) if err != nil { return err } @@ -45,3 +45,7 @@ func SendSms(content string, receivers ...string) error { return nil } + +func SendSms(content string, receivers ...string) error { + return globalClient.SendSms(content, receivers...) +} diff --git a/casdoorsdk/token.go b/casdoorsdk/token.go index 5cd58b6..a80824c 100644 --- a/casdoorsdk/token.go +++ b/casdoorsdk/token.go @@ -47,13 +47,13 @@ type Token struct { } // GetOAuthToken gets the pivotal and necessary secret to interact with the Casdoor server -func GetOAuthToken(code string, state string) (*oauth2.Token, error) { +func (c *Client) GetOAuthToken(code string, state string) (*oauth2.Token, error) { config := oauth2.Config{ - ClientID: authConfig.ClientId, - ClientSecret: authConfig.ClientSecret, + ClientID: c.ClientId, + ClientSecret: c.ClientSecret, Endpoint: oauth2.Endpoint{ - AuthURL: fmt.Sprintf("%s/api/login/oauth/authorize", authConfig.Endpoint), - TokenURL: fmt.Sprintf("%s/api/login/oauth/access_token", authConfig.Endpoint), + AuthURL: fmt.Sprintf("%s/api/login/oauth/authorize", c.Endpoint), + TokenURL: fmt.Sprintf("%s/api/login/oauth/access_token", c.Endpoint), AuthStyle: oauth2.AuthStyleInParams, }, // RedirectURL: redirectUri, @@ -72,14 +72,18 @@ func GetOAuthToken(code string, state string) (*oauth2.Token, error) { return token, err } +func GetOAuthToken(code string, state string) (*oauth2.Token, error) { + return globalClient.GetOAuthToken(code, state) +} + // RefreshOAuthToken refreshes the OAuth token -func RefreshOAuthToken(refreshToken string) (*oauth2.Token, error) { +func (c *Client) RefreshOAuthToken(refreshToken string) (*oauth2.Token, error) { config := oauth2.Config{ - ClientID: authConfig.ClientId, - ClientSecret: authConfig.ClientSecret, + ClientID: c.ClientId, + ClientSecret: c.ClientSecret, Endpoint: oauth2.Endpoint{ - AuthURL: fmt.Sprintf("%s/api/login/oauth/authorize", authConfig.Endpoint), - TokenURL: fmt.Sprintf("%s/api/login/oauth/refresh_token", authConfig.Endpoint), + AuthURL: fmt.Sprintf("%s/api/login/oauth/authorize", c.Endpoint), + TokenURL: fmt.Sprintf("%s/api/login/oauth/refresh_token", c.Endpoint), AuthStyle: oauth2.AuthStyleInParams, }, // RedirectURL: redirectUri, @@ -98,16 +102,20 @@ func RefreshOAuthToken(refreshToken string) (*oauth2.Token, error) { return token, err } -func GetTokens(p int, pageSize int) ([]*Token, int, error) { +func RefreshOAuthToken(refreshToken string) (*oauth2.Token, error) { + return globalClient.RefreshOAuthToken(refreshToken) +} + +func (c *Client) GetTokens(p int, pageSize int) ([]*Token, int, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "p": strconv.Itoa(p), "pageSize": strconv.Itoa(pageSize), } - url := GetUrl("get-tokens", queryMap) + url := c.GetUrl("get-tokens", queryMap) - response, err := DoGetResponse(url) + response, err := c.DoGetResponse(url) if err != nil { return nil, 0, err } @@ -125,7 +133,11 @@ func GetTokens(p int, pageSize int) ([]*Token, int, error) { return tokens, int(response.Data2.(float64)), nil } -func DeleteToken(name string) (bool, error) { +func GetTokens(p int, pageSize int) ([]*Token, int, error) { + return globalClient.GetTokens(p, pageSize) +} + +func (c *Client) DeleteToken(name string) (bool, error) { organization := Organization{ Owner: "admin", Name: name, @@ -135,10 +147,14 @@ func DeleteToken(name string) (bool, error) { return false, err } - resp, err := DoPost("delete-token", nil, postBytes, false, false) + resp, err := c.DoPost("delete-token", nil, postBytes, false, false) if err != nil { return false, err } return resp.Data == "Affected", nil } + +func DeleteToken(name string) (bool, error) { + return globalClient.DeleteToken(name) +} diff --git a/casdoorsdk/url.go b/casdoorsdk/url.go index ca441f9..0969379 100644 --- a/casdoorsdk/url.go +++ b/casdoorsdk/url.go @@ -20,36 +20,52 @@ import ( "strings" ) -func GetSignupUrl(enablePassword bool, redirectUri string) string { +func (c *Client) GetSignupUrl(enablePassword bool, redirectUri string) string { // redirectUri can be empty string if enablePassword == true (only password enabled signup page is required) if enablePassword { - return fmt.Sprintf("%s/signup/%s", authConfig.Endpoint, authConfig.ApplicationName) + return fmt.Sprintf("%s/signup/%s", c.Endpoint, c.ApplicationName) } else { - return strings.ReplaceAll(GetSigninUrl(redirectUri), "/login/oauth/authorize", "/signup/oauth/authorize") + return strings.ReplaceAll(c.GetSigninUrl(redirectUri), "/login/oauth/authorize", "/signup/oauth/authorize") } } -func GetSigninUrl(redirectUri string) string { +func GetSignupUrl(enablePassword bool, redirectUri string) string { + return globalClient.GetSignupUrl(enablePassword, redirectUri) +} + +func (c *Client) GetSigninUrl(redirectUri string) string { // origin := "https://door.casbin.com" // redirectUri := fmt.Sprintf("%s/callback", origin) scope := "read" - state := authConfig.ApplicationName + state := c.ApplicationName return fmt.Sprintf("%s/login/oauth/authorize?client_id=%s&response_type=code&redirect_uri=%s&scope=%s&state=%s", - authConfig.Endpoint, authConfig.ClientId, url.QueryEscape(redirectUri), scope, state) + c.Endpoint, c.ClientId, url.QueryEscape(redirectUri), scope, state) } -func GetUserProfileUrl(userName string, accessToken string) string { +func GetSigninUrl(redirectUri string) string { + return globalClient.GetSigninUrl(redirectUri) +} + +func (c *Client) GetUserProfileUrl(userName string, accessToken string) string { param := "" if accessToken != "" { param = fmt.Sprintf("?access_token=%s", accessToken) } - return fmt.Sprintf("%s/users/%s/%s%s", authConfig.Endpoint, authConfig.OrganizationName, userName, param) + return fmt.Sprintf("%s/users/%s/%s%s", c.Endpoint, c.OrganizationName, userName, param) } -func GetMyProfileUrl(accessToken string) string { +func GetUserProfileUrl(userName string, accessToken string) string { + return globalClient.GetUserProfileUrl(userName, accessToken) +} + +func (c *Client) GetMyProfileUrl(accessToken string) string { param := "" if accessToken != "" { param = fmt.Sprintf("?access_token=%s", accessToken) } - return fmt.Sprintf("%s/account%s", authConfig.Endpoint, param) + return fmt.Sprintf("%s/account%s", c.Endpoint, param) +} + +func GetMyProfileUrl(accessToken string) string { + return globalClient.GetMyProfileUrl(accessToken) } diff --git a/casdoorsdk/user.go b/casdoorsdk/user.go index 99d3526..1d01c56 100644 --- a/casdoorsdk/user.go +++ b/casdoorsdk/user.go @@ -173,14 +173,14 @@ type User struct { ManagedAccounts []ManagedAccount `xorm:"managedAccounts blob" json:"managedAccounts"` } -func GetUsers() ([]*User, error) { +func (c *Client) GetUsers() ([]*User, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, } - url := GetUrl("get-users", queryMap) + url := c.GetUrl("get-users", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -193,16 +193,20 @@ func GetUsers() ([]*User, error) { return users, nil } -func GetSortedUsers(sorter string, limit int) ([]*User, error) { +func GetUsers() ([]*User, error) { + return globalClient.GetUsers() +} + +func (c *Client) GetSortedUsers(sorter string, limit int) ([]*User, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "sorter": sorter, "limit": strconv.Itoa(limit), } - url := GetUrl("get-sorted-users", queryMap) + url := c.GetUrl("get-sorted-users", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -215,14 +219,18 @@ func GetSortedUsers(sorter string, limit int) ([]*User, error) { return users, nil } -func GetPaginationUsers(p int, pageSize int, queryMap map[string]string) ([]*User, int, error) { - queryMap["owner"] = authConfig.OrganizationName +func GetSortedUsers(sorter string, limit int) ([]*User, error) { + return globalClient.GetSortedUsers(sorter, limit) +} + +func (c *Client) GetPaginationUsers(p int, pageSize int, queryMap map[string]string) ([]*User, int, error) { + queryMap["owner"] = c.OrganizationName queryMap["p"] = strconv.Itoa(p) queryMap["pageSize"] = strconv.Itoa(pageSize) - url := GetUrl("get-users", queryMap) + url := c.GetUrl("get-users", queryMap) - response, err := DoGetResponse(url) + response, err := c.DoGetResponse(url) if err != nil { return nil, 0, err } @@ -244,15 +252,19 @@ func GetPaginationUsers(p int, pageSize int, queryMap map[string]string) ([]*Use return users, int(response.Data2.(float64)), nil } -func GetUserCount(isOnline string) (int, error) { +func GetPaginationUsers(p int, pageSize int, queryMap map[string]string) ([]*User, int, error) { + return globalClient.GetPaginationUsers(p, pageSize, queryMap) +} + +func (c *Client) GetUserCount(isOnline string) (int, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "isOnline": isOnline, } - url := GetUrl("get-user-count", queryMap) + url := c.GetUrl("get-user-count", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return -1, err } @@ -265,14 +277,18 @@ func GetUserCount(isOnline string) (int, error) { return count, nil } -func GetUser(name string) (*User, error) { +func GetUserCount(isOnline string) (int, error) { + return globalClient.GetUserCount(isOnline) +} + +func (c *Client) GetUser(name string) (*User, error) { queryMap := map[string]string{ - "id": fmt.Sprintf("%s/%s", authConfig.OrganizationName, name), + "id": fmt.Sprintf("%s/%s", c.OrganizationName, name), } - url := GetUrl("get-user", queryMap) + url := c.GetUrl("get-user", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -285,15 +301,19 @@ func GetUser(name string) (*User, error) { return user, nil } -func GetUserByEmail(email string) (*User, error) { +func GetUser(name string) (*User, error) { + return globalClient.GetUser(name) +} + +func (c *Client) GetUserByEmail(email string) (*User, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "email": email, } - url := GetUrl("get-user", queryMap) + url := c.GetUrl("get-user", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -306,15 +326,19 @@ func GetUserByEmail(email string) (*User, error) { return user, nil } -func GetUserByPhone(phone string) (*User, error) { +func GetUserByEmail(email string) (*User, error) { + return globalClient.GetUserByEmail(email) +} + +func (c *Client) GetUserByPhone(phone string) (*User, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "phone": phone, } - url := GetUrl("get-user", queryMap) + url := c.GetUrl("get-user", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -327,15 +351,19 @@ func GetUserByPhone(phone string) (*User, error) { return user, nil } -func GetUserByUserId(userId string) (*User, error) { +func GetUserByPhone(phone string) (*User, error) { + return globalClient.GetUserByPhone(phone) +} + +func (c *Client) GetUserByUserId(userId string) (*User, error) { queryMap := map[string]string{ - "owner": authConfig.OrganizationName, + "owner": c.OrganizationName, "userId": userId, } - url := GetUrl("get-user", queryMap) + url := c.GetUrl("get-user", queryMap) - bytes, err := DoGetBytes(url) + bytes, err := c.DoGetBytes(url) if err != nil { return nil, err } @@ -348,8 +376,12 @@ func GetUserByUserId(userId string) (*User, error) { return user, nil } +func GetUserByUserId(userId string) (*User, error) { + return globalClient.GetUserByUserId(userId) +} + // note: oldPassword is not required, if you don't need, just pass a empty string -func SetPassword(owner, name, oldPassword, newPassword string) (bool, error) { +func (c *Client) SetPassword(owner, name, oldPassword, newPassword string) (bool, error) { param := map[string]string{ "userOwner": owner, "userName": name, @@ -362,7 +394,7 @@ func SetPassword(owner, name, oldPassword, newPassword string) (bool, error) { return false, err } - resp, err := DoPost("set-password", nil, bytes, true, false) + resp, err := c.DoPost("set-password", nil, bytes, true, false) if err != nil { return false, err } @@ -370,36 +402,65 @@ func SetPassword(owner, name, oldPassword, newPassword string) (bool, error) { return resp.Status == "ok", nil } +// note: oldPassword is not required, if you don't need, just pass a empty string +func SetPassword(owner, name, oldPassword, newPassword string) (bool, error) { + return globalClient.SetPassword(owner, name, oldPassword, newPassword) +} + +func (c *Client) UpdateUserById(id string, user *User) (bool, error) { + _, affected, err := c.modifyUserById("update-user", id, user, nil) + return affected, err +} + func UpdateUserById(id string, user *User) (bool, error) { - _, affected, err := modifyUserById("update-user", id, user, nil) + return globalClient.UpdateUserById(id, user) +} + +func (c *Client) UpdateUser(user *User) (bool, error) { + _, affected, err := c.modifyUser("update-user", user, nil) return affected, err } func UpdateUser(user *User) (bool, error) { - _, affected, err := modifyUser("update-user", user, nil) + return globalClient.UpdateUser(user) +} + +func (c *Client) UpdateUserForColumns(user *User, columns []string) (bool, error) { + _, affected, err := c.modifyUser("update-user", user, columns) return affected, err } func UpdateUserForColumns(user *User, columns []string) (bool, error) { - _, affected, err := modifyUser("update-user", user, columns) + return globalClient.UpdateUserForColumns(user, columns) +} + +func (c *Client) AddUser(user *User) (bool, error) { + _, affected, err := c.modifyUser("add-user", user, nil) return affected, err } func AddUser(user *User) (bool, error) { - _, affected, err := modifyUser("add-user", user, nil) + return globalClient.AddUser(user) +} + +func (c *Client) DeleteUser(user *User) (bool, error) { + _, affected, err := c.modifyUser("delete-user", user, nil) return affected, err } func DeleteUser(user *User) (bool, error) { - _, affected, err := modifyUser("delete-user", user, nil) - return affected, err + return globalClient.DeleteUser(user) } -func CheckUserPassword(user *User) (bool, error) { - response, _, err := modifyUser("check-user-password", user, nil) +func (c *Client) CheckUserPassword(user *User) (bool, error) { + response, _, err := c.modifyUser("check-user-password", user, nil) return response.Status == "ok", err } +func CheckUserPassword(user *User) (bool, error) { + return globalClient.CheckUserPassword(user) +} + func (u User) GetId() string { return fmt.Sprintf("%s/%s", u.Owner, u.Name) } diff --git a/casdoorsdk/util.go b/casdoorsdk/util.go index f981c70..8243b79 100644 --- a/casdoorsdk/util.go +++ b/casdoorsdk/util.go @@ -22,19 +22,19 @@ import ( "strings" ) -func GetUrl(action string, queryMap map[string]string) string { +func (c *Client) GetUrl(action string, queryMap map[string]string) string { query := "" for k, v := range queryMap { query += fmt.Sprintf("%s=%s&", k, v) } query = strings.TrimRight(query, "&") - url := fmt.Sprintf("%s/api/%s?%s", authConfig.Endpoint, action, query) + url := fmt.Sprintf("%s/api/%s?%s", c.Endpoint, action, query) return url } -func GetId(name string) string { - return authConfig.OrganizationName + "/" + name +func (c *Client) GetId(name string) string { + return c.OrganizationName + "/" + name } func createFormFile(formData map[string][]byte) (string, io.Reader, error) {