Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support multiple SDK client instances #75

Merged
merged 1 commit into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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`.
Expand Down
16 changes: 12 additions & 4 deletions casdoorsdk/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand All @@ -85,15 +85,19 @@ 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
}

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,
Expand All @@ -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)
}
31 changes: 23 additions & 8 deletions casdoorsdk/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
56 changes: 27 additions & 29 deletions casdoorsdk/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand All @@ -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"
}
Expand All @@ -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)
Expand All @@ -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 {
Expand All @@ -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,
}
Expand All @@ -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
}
Expand All @@ -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),
}
Expand All @@ -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
}
Expand All @@ -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),
}
Expand All @@ -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
}
Expand Down
8 changes: 6 additions & 2 deletions casdoorsdk/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
}
Expand All @@ -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...)
}
22 changes: 15 additions & 7 deletions casdoorsdk/enforce.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
Loading
Loading