diff --git a/lib/authentication/authentication_client.go b/lib/authentication/authentication_client.go index 50bd083..c289858 100644 --- a/lib/authentication/authentication_client.go +++ b/lib/authentication/authentication_client.go @@ -2,6 +2,7 @@ package authentication import ( "bytes" + "crypto/sha256" "encoding/base64" "encoding/json" "errors" @@ -11,8 +12,11 @@ import ( "github.com/Authing/authing-go-sdk/lib/util" "github.com/Authing/authing-go-sdk/lib/util/cacheutil" simplejson "github.com/bitly/go-simplejson" + jsoniter "github.com/json-iterator/go" "io/ioutil" + "log" "net/http" + "regexp" "strings" "sync" "time" @@ -28,6 +32,9 @@ type Client struct { userPoolId string TokenEndPointAuthMethod constant.AuthMethodEnum + ClientToken *string + ClientUser *model.User + Log func(s string) } @@ -84,7 +91,7 @@ func (c *Client) BuildAuthorizeUrlByOidc(params model.OidcParams) (string, error } // GetAccessTokenByCode -// @desc code 换取 accessToken +// code 换取 accessToken func (c *Client) GetAccessTokenByCode(code string) (string, error) { if c.AppId == "" { return constant.StringEmpty, errors.New("请在初始化 AuthenticationClient 时传入 appId") @@ -123,7 +130,7 @@ func (c *Client) GetAccessTokenByCode(code string) (string, error) { } // GetUserInfoByAccessToken -// @desc accessToken 换取用户信息 +// accessToken 换取用户信息 func (c *Client) GetUserInfoByAccessToken(accessToken string) (string, error) { if accessToken == constant.StringEmpty { return constant.StringEmpty, errors.New("accessToken 不能为空") @@ -134,7 +141,7 @@ func (c *Client) GetUserInfoByAccessToken(accessToken string) (string, error) { } // GetNewAccessTokenByRefreshToken -// @desc 使用 Refresh token 获取新的 Access token +// 使用 Refresh token 获取新的 Access token func (c *Client) GetNewAccessTokenByRefreshToken(refreshToken string) (string, error) { if c.Protocol != constant.OIDC && c.Protocol != constant.OAUTH { return constant.StringEmpty, errors.New("初始化 AuthenticationClient 时传入的 protocol 参数必须为 ProtocolEnum.OAUTH 或 ProtocolEnum.OIDC,请检查参数") @@ -293,7 +300,7 @@ func (c *Client) LoginByUserName(request model.LoginByUsernameInput) (*model.Use if err != nil { return nil, err } - return loginGetUserInfo(b, "loginByUsername") + return c.loginGetUserInfo(b, "loginByUsername") } // LoginByEmail @@ -309,7 +316,7 @@ func (c *Client) LoginByEmail(request model.LoginByEmailInput) (*model.User, err if err != nil { return nil, err } - return loginGetUserInfo(b, "loginByEmail") + return c.loginGetUserInfo(b, "loginByEmail") } // LoginByPhonePassword @@ -325,37 +332,11 @@ func (c *Client) LoginByPhonePassword(request model.LoginByPhonePasswordInput) ( if err != nil { return nil, err } - return loginGetUserInfo(b, "loginByPhonePassword") -} - -/*func (c *Client) LoginByPhoneCode(request model.LoginByPhoneCodeInput) (*model.User,error) { - reqParam := make(map[string]interface{}) - reqParam["input"] = request - data, _ := json.Marshal(&reqParam) - variables := make(map[string]interface{}) - json.Unmarshal(data, &variables) - b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, constant.HttpMethodPost, constant.LoginByPhoneCodeDocument, variables) - if err != nil { - return nil, err - } - return loginGetUserInfo(b,"loginByPhoneCode") + return c.loginGetUserInfo(b, "loginByPhonePassword") } -func (c *Client) SendSmsCode(phone string) (*model.CommonMessage, error) { - var result *model.CommonMessage - variables := map[string]interface{}{ - "phone": phone, - } - b, err := c.SendHttpRequestManage(c.Host+"/api/v2/sms/send", constant.HttpMethodPost, constant.StringEmpty, variables) - if err != nil { - return result, err - } - log.Println(string(b)) - jsoniter.Unmarshal(b, result) - return result, nil -}*/ //TODO -func loginGetUserInfo(b []byte, userKey string) (*model.User, error) { +func (c *Client) loginGetUserInfo(b []byte, userKey string) (*model.User, error) { var result *simplejson.Json result, err := simplejson.NewJson(b) if _, r := result.CheckGet("errors"); r { @@ -374,6 +355,7 @@ func loginGetUserInfo(b []byte, userKey string) (*model.User, error) { if err != nil { return nil, err } + c.SetCurrentUser(&resultUser) return &resultUser, nil } func (c *Client) SendHttpRequest(url string, method string, header map[string]string, body map[string]string) ([]byte, error) { @@ -432,9 +414,9 @@ func (c *Client) SendHttpRequestManage(url string, method string, query string, } //增加header选项 - if !strings.HasPrefix(query, "query accessToken") { - token, _ := GetAccessToken(c) - req.Header.Add("Authorization", "Bearer "+token) + if !strings.HasPrefix(query, "query accessToken") && c.ClientToken != nil { + token := c.ClientToken + req.Header.Add("Authorization", "Bearer "+*token) } req.Header.Add("x-authing-userpool-id", ""+c.userPoolId) req.Header.Add("x-authing-request-from", constant.SdkType) @@ -499,3 +481,1463 @@ func GetAccessToken(client *Client) (string, error) { cacheutil.SetCache(constant.TokenCacheKeyPrefix+client.userPoolId, *token.AccessToken, time.Duration(expire*int64(time.Second))) return *token.AccessToken, nil } + +func (c *Client) SendHttpRestRequest(url string, method string, token *string, variables map[string]interface{}) ([]byte, error) { + var req *http.Request + if method == constant.HttpMethodGet { + req, _ = http.NewRequest(http.MethodGet, url, nil) + if variables != nil && len(variables) > 0 { + q := req.URL.Query() + for key, value := range variables { + q.Add(key, fmt.Sprintf("%v", value)) + } + req.URL.RawQuery = q.Encode() + } + } else { + var buf bytes.Buffer + var err error + if variables != nil { + err = json.NewEncoder(&buf).Encode(variables) + } + if err != nil { + return nil, err + } + req, err = http.NewRequest(method, url, &buf) + req.Header.Add("Content-Type", "application/json") + } + + if token == nil { + selfToken, _ := GetAccessToken(c) + token = &selfToken + } + req.Header.Add("Authorization", "Bearer "+*token) + + req.Header.Add("x-authing-userpool-id", ""+c.userPoolId) + req.Header.Add("x-authing-request-from", constant.SdkType) + req.Header.Add("x-authing-sdk-version", constant.SdkVersion) + req.Header.Add("x-authing-app-id", ""+constant.AppId) + res, err := c.HttpClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + body, err := ioutil.ReadAll(res.Body) + return body, nil +} + +func (c *Client) SendHttpRestRequestNotToken(url string, method string, variables map[string]interface{}) ([]byte, error) { + var req *http.Request + if method == constant.HttpMethodGet { + req, _ = http.NewRequest(http.MethodGet, url, nil) + if variables != nil && len(variables) > 0 { + q := req.URL.Query() + for key, value := range variables { + q.Add(key, fmt.Sprintf("%v", value)) + } + req.URL.RawQuery = q.Encode() + } + } else { + var buf bytes.Buffer + var err error + if variables != nil { + err = json.NewEncoder(&buf).Encode(variables) + } + if err != nil { + return nil, err + } + req, err = http.NewRequest(method, url, &buf) + req.Header.Add("Content-Type", "application/json") + } + + req.Header.Add("x-authing-userpool-id", ""+c.userPoolId) + req.Header.Add("x-authing-request-from", constant.SdkType) + req.Header.Add("x-authing-sdk-version", constant.SdkVersion) + req.Header.Add("x-authing-app-id", ""+constant.AppId) + res, err := c.HttpClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + body, err := ioutil.ReadAll(res.Body) + return body, nil +} + +// GetCurrentUser +// 获取资源列表 +func (c *Client) GetCurrentUser(token *string) (*model.User, error) { + + url := fmt.Sprintf("%s/api/v2/users/me", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, token, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.User `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +func (c *Client) getCurrentUser() (*model.User, error) { + k, e := cacheutil.GetCache(constant.UserCacheKeyPrefix + c.userPoolId) + if !e { + return nil, errors.New("未登录") + } + return k.(*model.User), nil +} + +// SetCurrentUser +// 设置当前用户 +func (c *Client) SetCurrentUser(user *model.User) (*model.User, error) { + c.ClientUser = user + c.ClientToken = user.Token + //cacheutil.SetDefaultCache(constant.UserCacheKeyPrefix+c.userPoolId, user) + //c.SetToken(*user.Token) + + return user, nil +} + +// SetToken +// 设置 Token +func (c *Client) SetToken(token string) { + c.ClientToken = &token + //cacheutil.SetDefaultCache(constant.TokenCacheKeyPrefix+c.userPoolId, token) +} + +// RegisterByEmail +// 使用邮箱注册 +func (c *Client) RegisterByEmail(request *model.RegisterByEmailInput) (*model.User, error) { + request.Password = util.RsaEncrypt(request.Password) + data, _ := jsoniter.Marshal(request) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RegisterByEmailDocument, + map[string]interface{}{"input": variables}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RegisterByEmail model.User `json:"registerByEmail"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.RegisterByEmail) + return &response.Data.RegisterByEmail, nil +} + +// RegisterByUsername +// 使用用户名注册 +func (c *Client) RegisterByUsername(request *model.RegisterByUsernameInput) (*model.User, error) { + request.Password = util.RsaEncrypt(request.Password) + data, _ := jsoniter.Marshal(request) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RegisterByUsernameDocument, + map[string]interface{}{"input": variables}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RegisterByUsername model.User `json:"registerByUsername"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.RegisterByUsername) + return &response.Data.RegisterByUsername, nil +} + +// RegisterByPhoneCode +// 使用手机号及验证码注册 +func (c *Client) RegisterByPhoneCode(request *model.RegisterByPhoneCodeInput) (*model.User, error) { + + data, _ := jsoniter.Marshal(request) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RegisterByPhoneCodeDocument, + map[string]interface{}{"input": variables}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RegisterByPhoneCode model.User `json:"registerByPhoneCode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.RegisterByPhoneCode) + return &response.Data.RegisterByPhoneCode, nil +} + +// CheckPasswordStrength +// 检查密码强度 +func (c *Client) CheckPasswordStrength(password string) (*struct { + Valid bool `json:"valid"` + Message string `json:"message"` +}, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.CheckPasswordStrengthDocument, + map[string]interface{}{"password": password}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + CheckPasswordStrength struct { + Valid bool `json:"valid"` + Message string `json:"message"` + } `json:"checkPasswordStrength"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + + return &response.Data.CheckPasswordStrength, nil +} + +// SendSmsCode +// 发送短信验证码 +func (c *Client) SendSmsCode(phone string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` +}, error) { + + url := fmt.Sprintf("%s/api/v2/sms/send", c.Host) + b, err := c.SendHttpRestRequestNotToken(url, http.MethodPost, map[string]interface{}{ + "phone": phone, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// LoginByPhoneCode +// 使用手机号验证码登录 +func (c *Client) LoginByPhoneCode(req *model.LoginByPhoneCodeInput) (*model.User, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.LoginByPhoneCodeDocument, map[string]interface{}{ + "input": vars, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + LoginByPhoneCode model.User `json:"loginByPhoneCode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + + return &response.Data.LoginByPhoneCode, nil +} + +// CheckLoginStatus +// 检测 Token 登录状态 +func (c *Client) CheckLoginStatus(token string) (*model.CheckLoginStatusResponse, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.CheckLoginStatusDocument, + map[string]interface{}{"token": token}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + CheckLoginStatus model.CheckLoginStatusResponse `json:"checkLoginStatus"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.CheckLoginStatus, nil +} + +// SendEmail +// 发送邮件 +func (c *Client) SendEmail(email string, scene model.EnumEmailScene) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.SendMailDocument, + map[string]interface{}{"email": email, "scene": scene}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SendMail model.CommonMessageAndCode `json:"sendEmail"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SendMail, nil +} + +// ResetPasswordByPhoneCode +// 通过短信验证码重置密码 +func (c *Client) ResetPasswordByPhoneCode(phone, code, newPassword string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ResetPasswordDocument, + map[string]interface{}{"phone": phone, "code": code, "newPassword": util.RsaEncrypt(newPassword)}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + ResetPassword model.CommonMessageAndCode `json:"resetPassword"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.ResetPassword, nil +} + +// ResetPasswordByEmailCode +// 通过邮件验证码重置密码 +func (c *Client) ResetPasswordByEmailCode(email, code, newPassword string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ResetPasswordDocument, + map[string]interface{}{"email": email, "code": code, "newPassword": util.RsaEncrypt(newPassword)}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + ResetPassword model.CommonMessageAndCode `json:"resetPassword"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.ResetPassword, nil +} + +// UpdateProfile +// 修改用户资料 +func (c *Client) UpdateProfile(req *model.UpdateUserInput) (*model.User, error) { + vars := make(map[string]interface{}) + currentUser, e := c.getCurrentUser() + if e != nil { + return nil, e + } + vars["id"] = currentUser.Id + vars["input"] = req + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdateProfileDocument, + vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdateUser model.User `json:"updateUser"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.UpdateUser) + return &response.Data.UpdateUser, nil +} + +// UpdatePassword +// 更新用户密码 +func (c *Client) UpdatePassword(oldPassword *string, newPassword string) (*model.User, error) { + + vars := make(map[string]interface{}) + vars["newPassword"] = util.RsaEncrypt(newPassword) + if oldPassword != nil { + vars["oldPassword"] = util.RsaEncrypt(*oldPassword) + } + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdatePasswordDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdatePassword model.User `json:"updatePassword"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.UpdatePassword) + return &response.Data.UpdatePassword, nil +} + +// UpdatePhone +// 更新用户手机号 +func (c *Client) UpdatePhone(phone, code string, oldPhone, oldPhoneCode *string) (*model.User, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdatePhoneDocument, + map[string]interface{}{ + "phone": phone, + "phoneCode": code, + "oldPhone": oldPhone, + "oldPhoneCode": oldPhoneCode, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdatePhone model.User `json:"updatePhone"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.UpdatePhone) + return &response.Data.UpdatePhone, nil +} + +// UpdateEmail +// 更新用户邮箱 +func (c *Client) UpdateEmail(email, code string, oldEmail, oldEmailCode *string) (*model.User, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdateEmailDocument, + map[string]interface{}{ + "email": email, + "emailCode": code, + "oldEmail": oldEmail, + "oldEmailCode": oldEmailCode, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdateEmail model.User `json:"updateEmail"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.UpdateEmail) + return &response.Data.UpdateEmail, nil +} + +// RefreshToken +// 刷新当前用户的 token +func (c *Client) RefreshToken(token *string) (*model.RefreshToken, error) { + + b, err := c.SendHttpRequestCustomTokenManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, token, constant.RefreshUserTokenDocument, + nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RefreshToken model.RefreshToken `json:"refreshToken"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetToken(*response.Data.RefreshToken.Token) + return &response.Data.RefreshToken, nil +} + +func (c *Client) SendHttpRequestCustomTokenManage(url string, method string, token *string, query string, variables map[string]interface{}) ([]byte, error) { + var req *http.Request + if method == constant.HttpMethodGet { + req, _ = http.NewRequest(http.MethodGet, url, nil) + if variables != nil && len(variables) > 0 { + q := req.URL.Query() + for key, value := range variables { + q.Add(key, fmt.Sprintf("%v", value)) + } + req.URL.RawQuery = q.Encode() + } + + } else { + in := struct { + Query string `json:"query"` + Variables map[string]interface{} `json:"variables,omitempty"` + }{ + Query: query, + Variables: variables, + } + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(in) + if err != nil { + return nil, err + } + req, err = http.NewRequest(method, url, &buf) + req.Header.Add("Content-Type", "application/json") + } + + //增加header选项 + if token == nil { + useToken, _ := GetAccessToken(c) + req.Header.Add("Authorization", "Bearer "+useToken) + } else { + req.Header.Add("Authorization", "Bearer "+*token) + + } + req.Header.Add("x-authing-userpool-id", ""+c.userPoolId) + req.Header.Add("x-authing-request-from", constant.SdkType) + req.Header.Add("x-authing-sdk-version", constant.SdkVersion) + req.Header.Add("x-authing-app-id", ""+constant.AppId) + + res, err := c.HttpClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + body, err := ioutil.ReadAll(res.Body) + return body, nil +} + +// LinkAccount +// 关联账号 +func (c *Client) LinkAccount(primaryUserToken, secondaryUserToken string) (*model.CommonMessageAndCode, error) { + + url := fmt.Sprintf("%s/api/v2/users/link", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, nil, map[string]interface{}{ + "primaryUserToken": primaryUserToken, + "secondaryUserToken": secondaryUserToken, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := model.CommonMessageAndCode{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp, nil +} + +// UnLinkAccount +// 主账号解绑社会化登录账号 +func (c *Client) UnLinkAccount(primaryUserToken string, provider constant.SocialProviderType) (*model.CommonMessageAndCode, error) { + + url := fmt.Sprintf("%s/api/v2/users/unlink", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, nil, map[string]interface{}{ + "primaryUserToken": primaryUserToken, + "provider": provider, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := model.CommonMessageAndCode{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp, nil +} + +// BindPhone +// 绑定手机号 +func (c *Client) BindPhone(phone, phoneCode string) (*model.User, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.BindPhoneDocument, + map[string]interface{}{"phone": phone, "phoneCode": phoneCode}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + BindPhone model.User `json:"bindPhone"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.BindPhone) + return &response.Data.BindPhone, nil +} + +// UnBindPhone +// 绑定手机号 +func (c *Client) UnBindPhone() (*model.User, error) { + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UnBindPhoneDocument, + nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UnbindPhone model.User `json:"unbindPhone"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.UnbindPhone) + return &response.Data.UnbindPhone, nil +} + +// BindEmail +// 绑定邮箱号 +func (c *Client) BindEmail(email, emailCode string) (*model.User, error) { + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.BindEmailDocument, + map[string]interface{}{ + "email": email, + "emailCode": emailCode, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + BindEmail model.User `json:"bindEmail"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.BindEmail) + return &response.Data.BindEmail, nil +} + +// UnBindEmail +// 解绑邮箱号 +func (c *Client) UnBindEmail() (*model.User, error) { + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UnBindEmailDocument, + nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UnbindEmail model.User `json:"unbindEmail"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.UnbindEmail) + return &response.Data.UnbindEmail, nil +} + +// Logout +// 退出登录 +func (c *Client) Logout() (*model.CommonMessageAndCode, error) { + cacheToken, _ := cacheutil.GetCache(constant.TokenCacheKeyPrefix + c.userPoolId) + if cacheToken == nil { + return nil, errors.New("Please login first") + } + token := cacheToken.(string) + + url := fmt.Sprintf("%s/api/v2/logout?app_id=%s", c.Host, c.AppId) + b, err := c.SendHttpRestRequest(url, http.MethodGet, &token, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := model.CommonMessageAndCode{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + c.ClearUser() + return &resp, nil +} + +func (c *Client) ClearUser() { + c.ClientUser = nil + c.ClientToken = nil + //cacheutil.DeleteCache(constant.TokenCacheKeyPrefix + c.userPoolId) + //cacheutil.DeleteCache(constant.UserCacheKeyPrefix + c.userPoolId) +} + +func (c *Client) getCacheUser() (*model.User, error) { + //cache, _ := cacheutil.GetCache(constant.UserCacheKeyPrefix + c.userPoolId) + //if cache == nil { + // return nil, errors.New("Please login first") + //} + //cacheUser := cache.(*model.User) + if c.ClientUser == nil { + return nil, errors.New("Please login first") + } + return c.ClientUser, nil +} + +// ListUdv +// 获取当前用户的自定义数据列表 +func (c *Client) ListUdv() (*[]model.UserDefinedData, error) { + cacheUser, e := c.getCacheUser() + if e != nil { + return nil, e + } + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UdvDocument, map[string]interface{}{ + "targetType": model.EnumUDFTargetTypeUSER, + "targetId": cacheUser.Id, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Udv []model.UserDefinedData `json:"udv"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Udv, nil +} + +// SetUdv +// 添加自定义数据 +func (c *Client) SetUdv(udvList []model.KeyValuePair) (*[]model.UserDefinedData, error) { + cacheUser, e := c.getCacheUser() + if e != nil { + return nil, e + } + variables := make(map[string]interface{}) + + variables["targetType"] = model.EnumUDFTargetTypeUSER + variables["targetId"] = cacheUser.Id + variables["udvList"] = udvList + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.SetRoleUdfValueDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SetUdvBatch []model.UserDefinedData `json:"setUdvBatch"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SetUdvBatch, nil +} + +// RemoveUdv +// 删除自定义数据 +func (c *Client) RemoveUdv(key string) (*[]model.UserDefinedData, error) { + cacheUser, e := c.getCacheUser() + if e != nil { + return nil, e + } + variables := make(map[string]interface{}) + variables["targetType"] = constant.USER + variables["targetId"] = cacheUser.Id + variables["key"] = key + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemoveUdfValueDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RemoveUdv []model.UserDefinedData `json:"removeUdv"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.RemoveUdv, nil +} + +// ListOrg +// 获取用户所在组织机构 +func (c *Client) ListOrg() (*struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data []model.UserOrgs `json:"data"` +}, error) { + + if c.ClientToken == nil { + return nil, errors.New("Please login first") + } + token := c.ClientToken + + url := fmt.Sprintf("%s/api/v2/users/me/orgs", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, token, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data []model.UserOrgs `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// LoginByLdap +// 使用 LDAP 用户名登录 +func (c *Client) LoginByLdap(username, password string) (*struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data model.User `json:"data"` +}, error) { + + url := fmt.Sprintf("%s/api/v2/ldap/verify-user", c.Host) + b, err := c.SendHttpRestRequestNotToken(url, http.MethodPost, map[string]interface{}{ + "username": username, + "password": password, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data model.User `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// LoginByAd +// 使用 AD 用户名登录 +func (c *Client) LoginByAd(username, password string) (*struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data model.User `json:"data"` +}, error) { + + com, _ := regexp.Compile("(?:http.*://)?(?P[^:/ ]+).?(?P[0-9]*).*") + domain := com.FindString(c.Host) + + lis := strings.Split(domain, ".") + var wsHost string + if len(lis) > 2 { + wsHost = strings.Join(lis[1:], ".") + } else { + wsHost = domain + } + url := fmt.Sprintf("https://ws.%s/api/v2/ad/verify-user", wsHost) + b, err := c.SendHttpRestRequestNotToken(url, http.MethodPost, map[string]interface{}{ + "username": username, + "password": password, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data model.User `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// GetSecurityLevel +// 用户安全等级 +func (c *Client) GetSecurityLevel() (*struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data model.GetSecurityLevelResponse `json:"data"` +}, error) { + //cacheToken, _ := cacheutil.GetCache(constant.TokenCacheKeyPrefix + c.userPoolId) + //if cacheToken == nil { + // return nil, errors.New("Please login first") + //} + //token := cacheToken.(string) + if c.ClientToken == nil { + return nil, errors.New("Please login first") + } + token := c.ClientToken + url := fmt.Sprintf("%s/api/v2/users/me/security-level", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, token, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data model.GetSecurityLevelResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// ListAuthorizedResources +// 获取用户被授权的所有资源 +func (c *Client) ListAuthorizedResources(namespace string, resourceType model.EnumResourceType) (*model.AuthorizedResources, error) { + cacheUser, e := c.getCacheUser() + if e != nil { + return nil, e + } + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListUserAuthorizedResourcesDocument, + map[string]interface{}{ + "id": cacheUser.Id, + "namespace": namespace, + "resourceType": resourceType, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + User struct { + AuthorizedResources model.AuthorizedResources `json:"authorizedResources"` + } `json:"user"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.User.AuthorizedResources, nil +} + +func (c *Client) BuildAuthorizeUrlByOauth(scope, redirectUri, state, responseType string) (string, error) { + + if c.AppId == "" { + return constant.StringEmpty, errors.New("请在初始化 AuthenticationClient 时传入 appId") + } + if c.Protocol != constant.OAUTH { + return constant.StringEmpty, errors.New("初始化 AuthenticationClient 传入的 protocol 应为 ProtocolEnum.OAUTH") + } + if redirectUri == "" { + return constant.StringEmpty, errors.New("redirectUri 不能为空") + } + + if strings.Contains(scope, "offline_access") { + scope = "consent" + } + dataMap := map[string]string{ + "client_id": util.GetValidValue(c.AppId), + "scope": util.GetValidValue(scope, "openid profile email phone address"), + "state": util.GetValidValue(state, util.RandomString(12)), + "response_type": util.GetValidValue(responseType), + "redirect_uri": util.GetValidValue(redirectUri), + } + return c.Host + "/oauth/auth?" + util.GetQueryString(dataMap), nil +} + +func (c *Client) BuildAuthorizeUrlBySaml() string { + return fmt.Sprintf("%s/api/v2/saml-idp/%s", c.Host, c.AppId) +} + +func (c *Client) BuildAuthorizeUrlByCas(service *string) string { + if service != nil { + return fmt.Sprintf("%s/cas-idp/%s?service=%s", c.Host, c.AppId, *service) + } else { + return fmt.Sprintf("%s/cas-idp/%s?service", c.Host, c.AppId) + } +} + +// ValidateTicketV1 +// 检验 CAS 1.0 Ticket 合法性 +func (c *Client) ValidateTicketV1(ticket, service string) (*struct { + Valid bool `json:"code"` + Message string `json:"message"` + Username string `json:"username"` +}, error) { + + url := fmt.Sprintf("%s/cas-idp/%s/validate?service=%s&ticket=%s", c.Host, c.AppId, service, ticket) + b, err := c.SendHttpRestRequestNotToken(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + sps := strings.Split(string(b), "\n") + var username, message string + + valid := (sps[0] == "yes") + username = sps[1] + if !valid { + message = "ticket is not valid" + } + resp := &struct { + Valid bool `json:"code"` + Message string `json:"message"` + Username string `json:"username"` + }{ + Valid: valid, + Username: username, + Message: message, + } + + return resp, nil +} + +//BuildLogoutUrl +//拼接登出 URL +func (c *Client) BuildLogoutUrl(expert, redirectUri, idToken *string) string { + var url string + if c.Protocol == constant.OIDC { + if expert == nil { + if redirectUri != nil { + url = fmt.Sprintf("%s/login/profile/logout?redirect_uri=%s", c.Host, *redirectUri) + } else { + url = fmt.Sprintf("%s/login/profile/logout", c.Host) + } + + } else { + if redirectUri != nil { + url = fmt.Sprintf("%s/oidc/session/end?id_token_hint=%s&post_logout_redirect_uri=%s", c.Host, *idToken, *redirectUri) + } else { + url = fmt.Sprintf("%s/oidc/session/end", c.Host) + } + + } + } + if c.Protocol == constant.CAS { + if redirectUri != nil { + url = fmt.Sprintf("%s/cas-idp/logout?url=%s", c.Host, *redirectUri) + } else { + url = fmt.Sprintf("%s/cas-idp/logout", c.Host) + } + } + return url +} + +// ListRole +// 获取用户拥有的角色列表 +func (c *Client) ListRole(namespace string) (*struct { + TotalCount int `json:"totalCount"` + List []model.RoleModel `json:"list"` +}, error) { + cacheUser, e := c.getCacheUser() + if e != nil { + return nil, e + } + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.GetUserRolesDocument, + map[string]interface{}{ + "id": cacheUser.Id, + "namespace": namespace, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + User model.GetUserRolesResponse `json:"user"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.User.Roles, nil +} + +// HasRole +// 判断当前用户是否有某个角色 +func (c *Client) HasRole(code, namespace string) (*bool, error) { + r, e := c.ListRole(namespace) + if e != nil { + return nil, e + } + hasRole := true + notHas := false + if r.TotalCount == 0 { + return ¬Has, nil + } + for _, d := range r.List { + if d.Code == code { + return &hasRole, nil + } + } + return ¬Has, nil +} + +// ListApplications +// 获取当前用户能够访问的应用 +func (c *Client) ListApplications(page, limit int) (*struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data struct { + TotalCount int64 `json:"totalCount"` + List []model.Application `json:"list"` + } `json:"data"` +}, error) { + if c.ClientToken == nil { + return nil, errors.New("Please login first") + } + token := c.ClientToken + url := fmt.Sprintf("%s/api/v2/users/me/applications/allowed?page=%v&limit=%v", c.Host, page, limit) + b, err := c.SendHttpRestRequest(url, http.MethodGet, token, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data struct { + TotalCount int64 `json:"totalCount"` + List []model.Application `json:"list"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// GenerateCodeChallenge +// 生成一个 PKCE 校验码,长度必须大于等于 43。 +func (c *Client) GenerateCodeChallenge(size int) (string, error) { + if size < 43 { + return constant.StringEmpty, errors.New("code_challenge must be a string length grater than 43") + } + return util.RandomString(size), nil + +} + +// GetCodeChallengeDigest +// 生成一个 PKCE 校验码摘要值 +func (c *Client) GetCodeChallengeDigest(codeChallenge string, method constant.GenerateCodeChallengeMethod) (string, error) { + if len(codeChallenge) < 43 { + return constant.StringEmpty, errors.New("code_challenge must be a string length grater than 43") + } + if method == constant.PLAIN { + return codeChallenge, nil + } else { + hasher := sha256.New() + hasher.Write([]byte(codeChallenge)) + base64Str := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) + return strings.Replace(base64Str, "=", "", -1), nil + } + +} + +// LoginBySubAccount +// 登录子账号 +func (c *Client) LoginBySubAccount(req *model.LoginBySubAccountRequest) (*model.User, error) { + req.Password = util.RsaEncrypt(req.Password) + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.LoginBySubAccountDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + LoginBySubAccount model.User `json:"loginBySubAccount"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + c.SetCurrentUser(&response.Data.LoginBySubAccount) + return &response.Data.LoginBySubAccount, nil +} + +// ResetPasswordByFirstLoginToken +// 通过首次登录的 Token 重置密码 +func (c *Client) ResetPasswordByFirstLoginToken(token, password string) (*model.CommonMessageAndCode, error) { + password = util.RsaEncrypt(password) + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ResetPasswordByTokenDocument, + map[string]interface{}{ + "token": token, + "password": password, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + ResetPasswordByFirstLoginToken model.CommonMessageAndCode `json:"resetPasswordByFirstLoginToken"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + + return &response.Data.ResetPasswordByFirstLoginToken, nil +} + +// ResetPasswordByForceResetToken +// 通过密码强制更新临时 Token 修改密码 +func (c *Client) ResetPasswordByForceResetToken(token, password, newPassword string) (*model.CommonMessageAndCode, error) { + password = util.RsaEncrypt(password) + newPassword = util.RsaEncrypt(newPassword) + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ResetPasswordByForceResetTokenDocument, + map[string]interface{}{ + "token": token, + "oldPassword": password, + "newPassword": newPassword, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + ResetPasswordByForceResetToken model.CommonMessageAndCode `json:"resetPasswordByForceResetToken"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + + return &response.Data.ResetPasswordByForceResetToken, nil +} + +// ListDepartments +// 获取用户所有部门 +func (c *Client) ListDepartments() (*model.PaginatedDepartments, error) { + cacheUser, e := c.getCacheUser() + if e != nil { + return nil, e + } + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, constant.HttpMethodPost, constant.GetUserDepartmentsDocument, + map[string]interface{}{"id": cacheUser.Id}) + if err != nil { + return nil, err + } + log.Println(string(b)) + + var response = &struct { + Data model.UserDepartmentsData `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return response.Data.User.Departments, nil + +} + +// IsUserExists +// 判断用户是否存在 +func (c *Client) IsUserExists(req *model.IsUserExistsRequest) (*bool, error) { + + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequestManage(c.Host+constant.CoreAuthingGraphqlPath, constant.HttpMethodPost, constant.IsUserExistsDocument, + vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + + var response = &struct { + Data struct { + IsUserExists *bool `json:"isUserExists"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return response.Data.IsUserExists, nil + +} + +// ValidateTicketV2 +// 通过远端服务验证票据合法性 +func (c *Client) ValidateTicketV2(ticket, service string, format constant.TicketFormat) (*struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data interface{} `json:"data"` +}, error) { + + url := fmt.Sprintf("%s/cas-idp/%s/serviceValidate", c.Host, c.AppId) + b, err := c.SendHttpRestRequestNotToken(url, http.MethodGet, map[string]interface{}{ + "service": service, + "ticket": ticket, + "format": format, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// TrackSession +// sso 检测登录态 +func (c *Client) TrackSession(code string, country, lang, state *string) (*struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data interface{} `json:"data"` +}, error) { + + url := fmt.Sprintf("%s/connection/social/wechat:mobile/%s/callback?code=%s", c.Host, c.AppId, code) + if country != nil { + url = url + "&country=" + *country + } + if lang != nil { + url = url + "&lang=" + *lang + } + if state != nil { + url = url + "&state=" + *state + } + b, err := c.SendHttpRestRequestNotToken(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} diff --git a/lib/authentication/authentication_client_test.go b/lib/authentication/authentication_client_test.go index 7ac924e..947bb31 100644 --- a/lib/authentication/authentication_client_test.go +++ b/lib/authentication/authentication_client_test.go @@ -4,13 +4,18 @@ import ( "fmt" "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" "log" "testing" ) const ( - AppId = "60a6f980dd9a9a7642da768a" - Secret = "5cd4ea7b3603b792aea9a00da9e18f44" + //UserPool="60c17b3d72b925097a738d86" + //Secret="6a350fe221596e96125e9375452da606" + //AppId ="60c17b536f0f06def12dfec4" + AppId = "6168f95e81d5e20f9cb72f22" + Secret = "ff053c05e4fb664a560556ea7c2cb715" + UserPool = "61384d3e302f1f75e69ce95a" ) func TestClient_BuildAuthorizeUrlByOidc(t *testing.T) { @@ -202,3 +207,512 @@ func TestClient_SendSmsCode(t *testing.T) { resp,err := authenticationClient.SendSmsCode("15566416161") log.Println(resp,err) }*/ + +func TestClient_GetCurrentUser(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + req := &model.LoginByPhoneCodeInput{ + Code: "3289", + Phone: "189xxxx1835", + } + authenticationClient.LoginByPhoneCode(req) + resp, err := authenticationClient.GetCurrentUser(nil) + log.Println(resp, err) +} + +func TestClient_RegisterByEmail(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + data, e := jsoniter.Marshal([]model.KeyValuePair{{Key: "custom", Value: "qq"}}) + log.Println(data, e) + p := string(data) + userName := "username" + req := &model.RegisterByEmailInput{ + Email: "5304950622@qq.com", + Password: "123456", + Profile: &model.RegisterProfile{ + Username: &userName, + }, + Params: &p, + } + resp, err := authenticationClient.RegisterByEmail(req) + log.Println(resp, err) +} + +func TestClient_RegisterByUsername(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + data, e := jsoniter.Marshal([]model.KeyValuePair{{Key: "custom", Value: "qq"}}) + log.Println(data, e) + p := string(data) + req := &model.RegisterByUsernameInput{ + Username: "gosdk", + Password: "123456", + Params: &p, + } + resp, err := authenticationClient.RegisterByUsername(req) + log.Println(resp, err) +} + +func TestClient_RegisterByPhoneCode(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + data, e := jsoniter.Marshal([]model.KeyValuePair{{Key: "custom", Value: "qq"}}) + log.Println(data, e) + p := string(data) + company := "company" + nickName := "nickName" + req := &model.RegisterByPhoneCodeInput{ + Phone: "15865561492", + Code: "123456", + Profile: &model.RegisterProfile{ + Nickname: &nickName, + Company: &company, + }, + Params: &p, + } + resp, err := authenticationClient.RegisterByPhoneCode(req) + log.Println(resp, err) +} + +func TestClient_CheckPasswordStrength(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + data, e := jsoniter.Marshal([]model.KeyValuePair{{Key: "custom", Value: "qq"}}) + log.Println(data, e) + + resp, err := authenticationClient.CheckPasswordStrength("12345678") + log.Println(resp, err) +} + +func TestClient_SendSmsCode(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + resp, err := authenticationClient.SendSmsCode("18910471835") + log.Println(resp, err) +} + +func TestClient_LoginByPhoneCode(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByPhoneCodeInput{ + Code: "3289", + Phone: "18910471835", + } + resp, err := authenticationClient.LoginByPhoneCode(req) + log.Println(resp, err) +} + +func TestClient_CheckLoginStatus(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + reginter := &model.RegisterByUsernameInput{ + Username: "testGoSDK", + Password: "123456789", + } + ru, re := authenticationClient.RegisterByUsername(reginter) + log.Println(ru, re) + req := &model.LoginByUsernameInput{ + Username: "testGoSDK", + Password: "123456789", + } + u, e := authenticationClient.LoginByUserName(*req) + log.Println(u, e) + resp, err := authenticationClient.CheckLoginStatus(*u.Token) + log.Println(resp, err) +} + +func TestClient_SendEmail(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + resp, err := authenticationClient.SendEmail(" mail@qq.com", model.EnumEmailSceneChangeEmail) + log.Println(resp, err) +} + +func TestClient_UpdateProfile(t *testing.T) { + authenticationClient := NewClient("6139c4d24e78a4d706b7545b", Secret) + authenticationClient.userPoolId = UserPool + + req := &model.LoginByUsernameInput{ + Username: "updateProfile", + Password: "123456", + } + resp, err := authenticationClient.LoginByUserName(*req) + log.Println(resp) + username := "goSdkTestUpdateProfile" + updateReq := &model.UpdateUserInput{ + Username: &username, + } + resp1, err := authenticationClient.UpdateProfile(updateReq) + log.Println(resp1, err) +} + +func TestClient_UpdatePassword(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "goSdkTestUpdateProfile", + Password: "654321", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.UpdatePassword(nil, "654321") + + log.Println(resp, err) + loginResp, loginErr := authenticationClient.LoginByUserName(model.LoginByUsernameInput{ + Username: "goSdkTestUpdateProfile", + Password: "654321", + }) + log.Println(loginResp, loginErr) +} + +func TestClient_UpdatePhone(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "goSdkTestUpdateProfile", + Password: "654321", + } + //authenticationClient.SendSmsCode("18515006338") + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.UpdatePhone("18515006338", "7757", nil, nil) + + log.Println(resp, err) + +} + +func TestClient_UpdateEmail(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "goSdkTestUpdateProfile", + Password: "654321", + } + //authenticationClient.SendSmsCode("18515006338") + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.UpdateEmail("530495062@qq.com", "7757", nil, nil) + + log.Println(resp, err) + +} + +func TestClient_RefreshToken(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "goSdkTestUpdateProfile", + Password: "654321", + } + //authenticationClient.SendSmsCode("18515006338") + user, _ := authenticationClient.LoginByUserName(*req) + oldToken := user.Token + log.Println(oldToken) + resp, err := authenticationClient.RefreshToken(user.Token) + log.Println(resp.Token) + + log.Println(resp, err) + +} + +func TestClient_LinkAccount(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "goSdkTestUpdateProfile", + Password: "654321", + } + + user, _ := authenticationClient.LoginByUserName(*req) + + resp, err := authenticationClient.LinkAccount(*user.Token, "qqwe") + + log.Println(resp, err) + +} + +func TestClient_UnLinkAccount(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "goSdkTestUpdateProfile", + Password: "654321", + } + + user, _ := authenticationClient.LoginByUserName(*req) + + resp, err := authenticationClient.UnLinkAccount(*user.Token, constant.WECHATPC) + + log.Println(resp, err) + +} + +func TestClient_BindPhone(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.BindPhone("18515006338", "1453") + log.Println(resp, err) + +} +func TestClient_SendSmsCode2(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + d, e := authenticationClient.SendSmsCode("18515006338") + log.Println(d, e) +} + +func TestClient_UnBindPhone(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.UnBindPhone() + log.Println(resp, err) + +} + +func TestClient_BindEmail(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.BindEmail("email", "code") + log.Println(resp, err) + +} + +func TestClient_UnBindEmail(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.UnBindEmail() + log.Println(resp, err) + +} + +func TestClient_Logout(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.Logout() + log.Println(resp, err) + +} + +func TestClient_ListUdv(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.ListUdv() + log.Println(resp, err) + +} + +func TestClient_SetUdv(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.SetUdv([]model.KeyValuePair{ + {Key: "age", Value: "18"}, + }) + log.Println(resp, err) + +} + +func TestClient_RemoveUdv(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.RemoveUdv("school") + log.Println(resp, err) + +} + +func TestClient_ListOrg(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.ListOrg() + log.Println(resp, err) + +} + +func TestClient_LoginByLdap(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + resp, err := authenticationClient.LoginByLdap("18515006338", "123456") + log.Println(resp, err) +} + +func TestClient_LoginByAd(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + resp, err := authenticationClient.LoginByAd("18515006338", "123456") + log.Println(resp, err) +} + +func TestClient_GetSecurityLevel(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.GetSecurityLevel() + log.Println(resp, err) +} + +func TestClient_ListAuthorizedResources(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.ListAuthorizedResources("default", model.EnumResourceTypeDATA) + log.Println(resp, err) +} + +func TestClient_BuildAuthorizeUrlByOauth(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + authenticationClient.Protocol = constant.OAUTH + resp, ee := authenticationClient.BuildAuthorizeUrlByOauth("email", "qq", "ww", "cc") + log.Println(resp, ee) +} + +func TestClient_ValidateTicketV1(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + authenticationClient.Protocol = constant.OAUTH + resp, ee := authenticationClient.ValidateTicketV1("email", "qq") + log.Println(resp, ee) +} + +func TestClient_ListRole(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.ListRole("default") + log.Println(resp, err) +} +func TestClient_HasRole(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.HasRole("NewCode", "default") + log.Println(resp, err) +} +func TestClient_ListApplications(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.ListApplications(1, 10) + log.Println(resp, err) +} + +func TestClient_GetCodeChallengeDigest(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + resp, err := authenticationClient.GetCodeChallengeDigest("wpaiscposrovkquicztfmftripjocybgmphyqtucmoz", constant.S256) + + log.Println(resp, err) +} + +func TestClient_LoginBySubAccount(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginBySubAccountRequest{ + Account: "123456789", + Password: "8558781", + } + resp, err := authenticationClient.LoginBySubAccount(req) + + log.Println(resp, err) +} + +func TestClient_ListDepartments(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.ListDepartments() + log.Println(resp, err) +} + +func TestClient_IsUserExists(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + req := &model.LoginByUsernameInput{ + Username: "18515006338", + Password: "123456", + } + userName := "18515006338" + authenticationClient.LoginByUserName(*req) + resp, err := authenticationClient.IsUserExists(&model.IsUserExistsRequest{ + Username: &userName, + }) + log.Println(resp, err) +} + +func TestClient_ValidateTicketV2(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + resp, err := authenticationClient.ValidateTicketV2("ss", "ss", constant.XML) + log.Println(resp, err) +} diff --git a/lib/authentication/mfa_client.go b/lib/authentication/mfa_client.go new file mode 100644 index 0000000..433cc34 --- /dev/null +++ b/lib/authentication/mfa_client.go @@ -0,0 +1,355 @@ +package authentication + +import ( + "errors" + "fmt" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// GetMfaAuthenticators +// 获取 MFA 认证器 +func (c *Client) GetMfaAuthenticators(req *model.MfaInput) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data []model.GetMfaAuthenticatorsResponse `json:"data"` +}, error) { + + vars := make(map[string]interface{}) + if req.MfaType == nil { + vars["type"] = "totp" + } else { + vars["type"] = req.MfaType + } + if req.MfaSource == nil { + vars["source"] = constant.Self + } else { + vars["source"] = req.MfaSource + } + url := fmt.Sprintf("%s/api/v2/mfa/authenticator", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, req.MfaToken, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data []model.GetMfaAuthenticatorsResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// AssociateMfaAuthenticator +// 请求 MFA 二维码和密钥信息 +func (c *Client) AssociateMfaAuthenticator(req *model.MfaInput) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.AssociateMfaAuthenticatorResponse `json:"data"` +}, error) { + + vars := make(map[string]interface{}) + if req.MfaType == nil { + vars["authenticatorType"] = "totp" + } else { + vars["authenticatorType"] = req.MfaType + } + if req.MfaSource == nil { + vars["source"] = constant.Self + } else { + vars["source"] = req.MfaSource + } + url := fmt.Sprintf("%s/api/v2/mfa/totp/associate", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, req.MfaToken, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.AssociateMfaAuthenticatorResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// DeleteMfaAuthenticator +// 解绑 MFA +func (c *Client) DeleteMfaAuthenticator() (*model.CommonMessageAndCode, error) { + + url := fmt.Sprintf("%s/api/v2/mfa/totp/associate", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodDelete, nil, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + var resp model.CommonMessageAndCode + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp, nil +} + +// ConfirmAssociateMfaAuthenticator +// 确认绑定 MFA +func (c *Client) ConfirmAssociateMfaAuthenticator(req *model.ConfirmAssociateMfaAuthenticatorRequest) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := make(map[string]interface{}) + if req.AuthenticatorType == nil { + vars["authenticatorType"] = "totp" + } else { + vars["authenticatorType"] = req.AuthenticatorType + } + if req.MfaSource == nil { + vars["source"] = constant.Self + } else { + vars["source"] = req.MfaSource + } + vars["totp"] = req.Totp + url := fmt.Sprintf("%s/api/v2/mfa/totp/associate/confirm", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, req.MfaToken, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// VerifyTotpMfa +// 检验二次验证 MFA 口令 +func (c *Client) VerifyTotpMfa(totp, token string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := make(map[string]interface{}) + + vars["totp"] = totp + url := fmt.Sprintf("%s/api/v2/mfa/totp/verify", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, &token, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// VerifyAppSmsMfa +// 检验二次验证 MFA 短信验证码 +func (c *Client) VerifyAppSmsMfa(phone, code, token string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := map[string]interface{}{ + "code": code, + "phone": phone, + } + + url := fmt.Sprintf("%s/api/v2/applications/mfa/sms/verify", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, &token, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// VerifyAppEmailMfa +// 检验二次验证 MFA 邮箱验证码 +func (c *Client) VerifyAppEmailMfa(email, code, token string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := map[string]interface{}{ + "code": code, + "email": email, + } + + url := fmt.Sprintf("%s/api/v2/applications/mfa/email/verify", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, &token, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// PhoneOrEmailBindable +// 检测手机号或邮箱是否已被绑定 +func (c *Client) PhoneOrEmailBindable(email, phone *string, token string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := make(map[string]interface{}) + if email != nil { + vars["email"] = email + } + if phone != nil { + vars["phone"] = phone + } + + url := fmt.Sprintf("%s/api/v2/applications/mfa/check", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, &token, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// VerifyTotpRecoveryCode +// 检验二次验证 MFA 恢复代码 +func (c *Client) VerifyTotpRecoveryCode(code, token string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := make(map[string]interface{}) + + vars["recoveryCode"] = code + url := fmt.Sprintf("%s/api/v2/mfa/totp/recovery", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, &token, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// AssociateFaceByUrl +// 通过图片 URL 绑定人脸 +func (c *Client) AssociateFaceByUrl(baseFaceUrl, CompareFaceUrl, token string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := map[string]interface{}{ + "photoA": baseFaceUrl, + "photoB": CompareFaceUrl, + "isExternal": true, + } + url := fmt.Sprintf("%s/api/v2/mfa/face/associate", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, &token, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// VerifyFaceMfa +// 人脸二次认证 +func (c *Client) VerifyFaceMfa(faceUrl, token string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + vars := map[string]interface{}{ + "photo": faceUrl, + } + url := fmt.Sprintf("%s/api/v2/mfa/face/associate", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, &token, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} diff --git a/lib/authentication/mfa_client_test.go b/lib/authentication/mfa_client_test.go new file mode 100644 index 0000000..7f80cc3 --- /dev/null +++ b/lib/authentication/mfa_client_test.go @@ -0,0 +1,183 @@ +package authentication + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_GetMfaAuthenticators(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + loginReq := model.LoginByEmailInput{ + Email: "fptvmzqyxn@authing.cn", + Password: "12345678", + } + u, e := authenticationClient.LoginByEmail(loginReq) + //log.Println(u) + log.Println(e) + resp, err := authenticationClient.GetMfaAuthenticators(&model.MfaInput{ + MfaToken: u.Token, + }) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_AssociateMfaAuthenticator(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + loginReq := model.LoginByEmailInput{ + Email: "fptvmzqyxn@authing.cn", + Password: "12345678", + } + u, e := authenticationClient.LoginByEmail(loginReq) + log.Println(e) + resp, err := authenticationClient.AssociateMfaAuthenticator(&model.MfaInput{ + MfaToken: u.Token, + }) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_DeleteMfaAuthenticator(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + resp, err := authenticationClient.DeleteMfaAuthenticator() + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_ConfirmAssociateMfaAuthenticator(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + //loginReq:= model.LoginByEmailInput{ + // Email: "fptvmzqyxn@authing.cn", + // Password: "12345678", + //} + //u,e:=authenticationClient.LoginByEmail(loginReq) + //log.Println(e) + resp, err := authenticationClient.ConfirmAssociateMfaAuthenticator(&model.ConfirmAssociateMfaAuthenticatorRequest{ + Totp: "D5LH4GQQGEEWEHKX", + //Totp: "c833-cbb6-9180-7240-a048-ebe6", + //MfaToken: u.Token, + }) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_VerifyTotpMfa(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + mfaToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXJQb29sSWQiOiI2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODYiLCJ1c2VySWQiOiI2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJhcm4iOiJhcm46Y246YXV0aGluZzo2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODY6dXNlcjo2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJzdGFnZSI6MX0sImlhdCI6MTYzNTE0OTQ2MiwiZXhwIjoxNjM1MTQ5ODIyfQ.2DbmVf1-JQeiRMpZBk-3y-uPIN15FL-ranE4UlMKMoM" + + resp, err := authenticationClient.VerifyTotpMfa("q", mfaToken) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_VerifyAppSmsMfa(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + loginReq := model.LoginByEmailInput{ + Email: "gosdk@mail.com", + Password: "123456789", + } + u, e := authenticationClient.LoginByEmail(loginReq) + log.Println(e) + resp, err := authenticationClient.VerifyAppSmsMfa("777777", "q", *u.Token) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_VerifyAppEmailMfa(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + loginReq := model.LoginByEmailInput{ + Email: "gosdk@mail.com", + Password: "123456789", + } + u, e := authenticationClient.LoginByEmail(loginReq) + log.Println(u, e) + mfaToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXJQb29sSWQiOiI2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODYiLCJ1c2VySWQiOiI2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJhcm4iOiJhcm46Y246YXV0aGluZzo2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODY6dXNlcjo2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJzdGFnZSI6MX0sImlhdCI6MTYzNTE0OTQ2MiwiZXhwIjoxNjM1MTQ5ODIyfQ.2DbmVf1-JQeiRMpZBk-3y-uPIN15FL-ranE4UlMKMoM" + + resp, err := authenticationClient.VerifyAppEmailMfa("gosdk@mail.com", "q", mfaToken) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_PhoneOrEmailBindable(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + mfaToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXJQb29sSWQiOiI2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODYiLCJ1c2VySWQiOiI2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJhcm4iOiJhcm46Y246YXV0aGluZzo2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODY6dXNlcjo2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJzdGFnZSI6MX0sImlhdCI6MTYzNTE0OTQ2MiwiZXhwIjoxNjM1MTQ5ODIyfQ.2DbmVf1-JQeiRMpZBk-3y-uPIN15FL-ranE4UlMKMoM" + email := "gosdk@mail.com" + resp, err := authenticationClient.PhoneOrEmailBindable(&email, nil, mfaToken) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_VerifyFaceMfa(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + mfaToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXJQb29sSWQiOiI2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODYiLCJ1c2VySWQiOiI2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJhcm4iOiJhcm46Y246YXV0aGluZzo2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODY6dXNlcjo2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJzdGFnZSI6MX0sImlhdCI6MTYzNTE0OTQ2MiwiZXhwIjoxNjM1MTQ5ODIyfQ.2DbmVf1-JQeiRMpZBk-3y-uPIN15FL-ranE4UlMKMoM" + + resp, err := authenticationClient.VerifyFaceMfa("http://face", mfaToken) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_AssociateFaceByUrl(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + mfaToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXJQb29sSWQiOiI2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODYiLCJ1c2VySWQiOiI2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJhcm4iOiJhcm46Y246YXV0aGluZzo2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODY6dXNlcjo2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJzdGFnZSI6MX0sImlhdCI6MTYzNTE0OTQ2MiwiZXhwIjoxNjM1MTQ5ODIyfQ.2DbmVf1-JQeiRMpZBk-3y-uPIN15FL-ranE4UlMKMoM" + + resp, err := authenticationClient.AssociateFaceByUrl("http://tp", "http://zp", mfaToken) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} + +func TestClient_VerifyTotpRecoveryCode(t *testing.T) { + authenticationClient := NewClient(AppId, Secret) + authenticationClient.userPoolId = UserPool + + mfaToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXJQb29sSWQiOiI2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODYiLCJ1c2VySWQiOiI2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJhcm4iOiJhcm46Y246YXV0aGluZzo2MGMxN2IzZDcyYjkyNTA5N2E3MzhkODY6dXNlcjo2MTc2NWYxMDI5MThhOGZjNjUyNDU2NDAiLCJzdGFnZSI6MX0sImlhdCI6MTYzNTE0OTQ2MiwiZXhwIjoxNjM1MTQ5ODIyfQ.2DbmVf1-JQeiRMpZBk-3y-uPIN15FL-ranE4UlMKMoM" + + resp, err := authenticationClient.VerifyTotpMfa("eedc-58ed-931b-8967-a092-46ae", mfaToken) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(resp) + } +} diff --git a/lib/constant/enums.go b/lib/constant/enums.go index b897e71..bccc64c 100644 --- a/lib/constant/enums.go +++ b/lib/constant/enums.go @@ -40,6 +40,7 @@ const ( // TokenCacheKeyPrefix token缓存key前缀 TokenCacheKeyPrefix = "token_" + UserCacheKeyPrefix = "user_" ) type ProtocolEnum string @@ -59,12 +60,86 @@ const ( None = "none" ) -type ResourceTypeEnum string +type ResourceTargetTypeEnum string const ( - DATA ResourceTypeEnum = "DATA" - API ResourceTypeEnum = "API" - MENU ResourceTypeEnum = "MENU" - UI ResourceTypeEnum = "UI" - BUTTON ResourceTypeEnum = "BUTTON" + USER ResourceTargetTypeEnum = "USER" + ROLE ResourceTargetTypeEnum = "ROLE" + GROUP ResourceTargetTypeEnum = "GROUP" + ORG ResourceTargetTypeEnum = "ORG" +) + +type ApplicationDefaultAccessPolicies string + +const ( + AllowAll ApplicationDefaultAccessPolicies = "ALLOW_ALL" + DenyAll ApplicationDefaultAccessPolicies = "DENY_ALL" +) + +type GetAuthorizedTargetsOpt string + +const ( + AND GetAuthorizedTargetsOpt = "AND" + OR GetAuthorizedTargetsOpt = "OR" +) + +type ProviderTypeEnum string + +const ( + DingTalk ProviderTypeEnum = "dingtalk" + WechatWork ProviderTypeEnum = "wechatwork" + AD ProviderTypeEnum = "ad" +) + +type PrincipalAuthenticateType string + +const ( + P PrincipalAuthenticateType = "P" + E PrincipalAuthenticateType = "E" +) + +type MfaSource string + +const ( + Self MfaSource = "SELF" + Application MfaSource = "APPLICATION" +) + +type SocialProviderType string + +const ( + WECHATPC SocialProviderType = "wechat:pc" + GITHUB SocialProviderType = "github" + GOOGLE SocialProviderType = "google" + QQ SocialProviderType = "qq" + APPLE SocialProviderType = "apple" + BAIDU SocialProviderType = "baidu" + ALIPAY SocialProviderType = "alipay" + LARK_APP_STORE SocialProviderType = "lark:app-store" + LARK_CUSTOM_APP SocialProviderType = "lark:custom-app" + WEIBO SocialProviderType = "weibo" + DINGTALK SocialProviderType = "dingtalk" + WECHAT_WEB SocialProviderType = "wechat:webpage-authorization" + ALIPAY_MOBILE SocialProviderType = "alipay" + WECHAT_MQ_DEFAULT SocialProviderType = "wechat:miniprogram:default" + WECHAT_MOBILE SocialProviderType = "wechat:mobile" + WECHATWORK_SP_AUTHZ SocialProviderType = "wechatwork:service-provider:authorization" + WECHATWORK_SP_QR SocialProviderType = "wechatwork:service-provider:qrconnect" + WECHATWORK_CORP_QR SocialProviderType = "wechatwork:corp:qrconnect" + WECHAT_MP_AL SocialProviderType = "wechat:miniprogram:app-launch" + WECHAT_MP_QR SocialProviderType = "wechat:miniprogram:qrconnect" +) + +type GenerateCodeChallengeMethod string + +const ( + PLAIN GenerateCodeChallengeMethod = "plain" + S256 GenerateCodeChallengeMethod = "S256" +) + +type TicketFormat string + +const ( + XML TicketFormat = "XML" + JSON TicketFormat = "JSON" ) diff --git a/lib/constant/gql.go b/lib/constant/gql.go index 0350a38..609d844 100644 --- a/lib/constant/gql.go +++ b/lib/constant/gql.go @@ -601,18 +601,200 @@ const AuthorizeResourceDocument = ` } ` -const GroupsDocument = ` - query groups($userId: String, $page: Int, $limit: Int, $sortBy: SortByEnum) { - groups(userId: $userId, page: $page, limit: $limit, sortBy: $sortBy) { - totalCount - list { +const UpdateUserPoolDocument = ` +mutation updateUserpool($input: UpdateUserpoolInput!) { + updateUserpool(input: $input) { + id + name + domain + description + secret + jwtSecret + userpoolTypes { code name description - createdAt - updatedAt + image + sdks + } + logo + createdAt + updatedAt + emailVerifiedDefault + sendWelcomeEmail + registerDisabled + appSsoEnabled + showWxQRCodeWhenRegisterDisabled + allowedOrigins + tokenExpiresAfter + isDeleted + frequentRegisterCheck { + timeInterval + limit + enabled + } + loginFailCheck { + timeInterval + limit + enabled + } + loginFailStrategy + loginPasswordFailCheck { + timeInterval + limit + enabled + } + changePhoneStrategy { + verifyOldPhone + } + changeEmailStrategy { + verifyOldEmail + } + qrcodeLoginStrategy { + qrcodeExpiresAfter + returnFullUserInfo + allowExchangeUserInfoFromBrowser + ticketExpiresAfter + } + app2WxappLoginStrategy { + ticketExpriresAfter + ticketExchangeUserInfoNeedSecret + } + whitelist { + phoneEnabled + emailEnabled + usernameEnabled + } + customSMSProvider { + enabled + provider + config } + packageType + useCustomUserStore + loginRequireEmailVerified + verifyCodeLength } } - ` +` +const WhileListDocument = ` +query whitelist($type: WhitelistType!) { + whitelist(type: $type) { + createdAt + updatedAt + value + } +} +` +const AddWhileListDocument = ` +mutation addWhitelist($type: WhitelistType!, $list: [String!]!) { + addWhitelist(type: $type, list: $list) { + createdAt + updatedAt + value + } +} +` + +const RemoveWhileListDocument = ` +mutation removeWhitelist($type: WhitelistType!, $list: [String!]!) { + removeWhitelist(type: $type, list: $list) { + createdAt + updatedAt + value + } +} +` + +const ListAuthorizedResourcesDocument = ` +query authorizedResources($targetType: PolicyAssignmentTargetType, $targetIdentifier: String, $namespace: String, $resourceType: String) { + authorizedResources(targetType: $targetType, targetIdentifier: $targetIdentifier, namespace: $namespace, resourceType: $resourceType) { + totalCount + list { + code + type + actions + } + } +} +` +const GetAuthorizedTargetsDocument = ` +query authorizedTargets($namespace: String!, $resourceType: ResourceType!, $resource: String!, $targetType: PolicyAssignmentTargetType, $actions: AuthorizedTargetsActionsInput) { + authorizedTargets(namespace: $namespace, resource: $resource, resourceType: $resourceType, targetType: $targetType, actions: $actions) { + totalCount + list { + targetType + targetIdentifier + actions + } + } +} +` +const SendMailDocument = ` +mutation sendEmail($email: String!, $scene: EmailScene!) { + sendEmail(email: $email, scene: $scene) { + message + code + } +} +` + +const CheckLoginStatusDocument = ` +query checkLoginStatus($token: String) { + checkLoginStatus(token: $token) { + code + message + status + exp + iat + data { + id + userPoolId + arn + } + } +} +` + +const ListUdfDocument = ` +query udf($targetType: UDFTargetType!) { + udf(targetType: $targetType) { + targetType + dataType + key + label + options + } +}` + +const SetUdfDocument = ` +mutation setUdf($targetType: UDFTargetType!, $key: String!, $dataType: UDFDataType!, $label: String!, $options: String) { + setUdf(targetType: $targetType, key: $key, dataType: $dataType, label: $label, options: $options) { + targetType + dataType + key + label + options + } +} +` +const RemoveUdfDocument = ` +mutation removeUdf($targetType: UDFTargetType!, $key: String!) { + removeUdf(targetType: $targetType, key: $key) { + message + code + } +} +` + +const UdvDocument = ` +query udv($targetType: UDFTargetType!, $targetId: String!) { + udv(targetType: $targetType, targetId: $targetId) { + key + dataType + value + label + } +} +` diff --git a/lib/constant/gql_authentication.go b/lib/constant/gql_authentication.go new file mode 100644 index 0000000..bae0e36 --- /dev/null +++ b/lib/constant/gql_authentication.go @@ -0,0 +1,664 @@ +package constant + +const RegisterByEmailDocument = ` +mutation registerByEmail($input: RegisterByEmailInput!) { + registerByEmail(input: $input) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + externalId + } +} + +` + +const RegisterByUsernameDocument = ` +mutation registerByUsername($input: RegisterByUsernameInput!) { + registerByUsername(input: $input) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + externalId + } +} + +` + +const RegisterByPhoneCodeDocument = ` +mutation registerByPhoneCode($input: RegisterByPhoneCodeInput!) { + registerByPhoneCode(input: $input) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + externalId + } +} + +` + +const CheckPasswordStrengthDocument = ` +query checkPasswordStrength($password: String!) { + checkPasswordStrength(password: $password) { + valid + message + } +} +` + +const ResetPasswordDocument = ` +mutation resetPassword($phone: String, $email: String, $code: String!, $newPassword: String!) { + resetPassword(phone: $phone, email: $email, code: $code, newPassword: $newPassword) { + message + code + } +} +` + +const UpdateProfileDocument = ` +mutation updateUser($id: String, $input: UpdateUserInput!) { + updateUser(id: $id, input: $input) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + externalId + } +} +` + +const UpdatePasswordDocument = ` +mutation updatePassword($newPassword: String!, $oldPassword: String) { + updatePassword(newPassword: $newPassword, oldPassword: $oldPassword) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } +} + +` +const UpdatePhoneDocument = ` +mutation updatePhone($phone: String!, $phoneCode: String!, $oldPhone: String, $oldPhoneCode: String) { + updatePhone(phone: $phone, phoneCode: $phoneCode, oldPhone: $oldPhone, oldPhoneCode: $oldPhoneCode) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } +} +` + +const UpdateEmailDocument = ` +mutation updateEmail($email: String!, $emailCode: String!, $oldEmail: String, $oldEmailCode: String) { + updateEmail(email: $email, emailCode: $emailCode, oldEmail: $oldEmail, oldEmailCode: $oldEmailCode) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } +} + +` +const BindPhoneDocument = ` +mutation bindPhone($phone: String!, $phoneCode: String!) { + bindPhone(phone: $phone, phoneCode: $phoneCode) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } +} + +` + +const UnBindPhoneDocument = ` +mutation unbindPhone { + unbindPhone { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } +} + +` + +const BindEmailDocument = ` +mutation bindEmail($email: String!, $emailCode: String!) { + bindEmail(email: $email, emailCode: $emailCode) { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } +}` + +const UnBindEmailDocument = ` +mutation unbindEmail { + unbindEmail { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } +} +` +const ResetPasswordByTokenDocument = ` +mutation resetPasswordByFirstLoginToken($token: String!, $password: String!) { + resetPasswordByFirstLoginToken(token: $token, password: $password) { + message + code + } +} +` +const ResetPasswordByForceResetTokenDocument = ` +mutation resetPasswordByForceResetToken($token: String!, $oldPassword: String!, $newPassword: String!) { + resetPasswordByForceResetToken(token: $token, oldPassword: $oldPassword, newPassword: $newPassword) { + message + code + } +} +` +const IsUserExistsDocument = ` +query isUserExists($email: String, $phone: String, $username: String, $externalId: String) { + isUserExists(email: $email, phone: $phone, username: $username, externalId: $externalId) +} +` diff --git a/lib/constant/gql_manage_groups.go b/lib/constant/gql_manage_groups.go new file mode 100644 index 0000000..1be9946 --- /dev/null +++ b/lib/constant/gql_manage_groups.go @@ -0,0 +1,223 @@ +package constant + +const CreateGroupsDocument = ` +mutation createGroup($code: String!, $name: String!, $description: String) { + createGroup(code: $code, name: $name, description: $description) { + code + name + description + createdAt + updatedAt + } +} +` + +const UpdateGroupsDocument = ` +mutation updateGroup($code: String!, $name: String, $description: String, $newCode: String) { + updateGroup(code: $code, name: $name, description: $description, newCode: $newCode) { + code + name + description + createdAt + updatedAt + } +} +` + +const GroupsDocument = ` + query groups($userId: String, $page: Int, $limit: Int, $sortBy: SortByEnum) { + groups(userId: $userId, page: $page, limit: $limit, sortBy: $sortBy) { + totalCount + list { + code + name + description + createdAt + updatedAt + } + } +} +` + +const DetailGroupsDocument = ` +query group($code: String!) { + group(code: $code) { + code + name + description + createdAt + updatedAt + } +} +` + +const DeleteGroupsDocument = ` +mutation deleteGroups($codeList: [String!]!) { + deleteGroups(codeList: $codeList) { + message + code + } +} +` + +const ListGroupsDocument = ` +query groups($userId: String, $page: Int, $limit: Int, $sortBy: SortByEnum) { + groups(userId: $userId, page: $page, limit: $limit, sortBy: $sortBy) { + totalCount + list { + code + name + description + createdAt + updatedAt + } + } +} +` + +const ListGroupUserDocument = ` +query groupWithUsers($code: String!, $page: Int, $limit: Int) { + group(code: $code) { + users(page: $page, limit: $limit) { + totalCount + list { + id + arn + status + userPoolId + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + externalId + } + } + } +} + +` + +const ListGroupUserWithCustomDocument = ` +query groupWithUsersWithCustomData($code: String!, $page: Int, $limit: Int) { + group(code: $code) { + users(page: $page, limit: $limit) { + totalCount + list { + id + arn + status + userPoolId + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + externalId + customData { + key + value + dataType + label + } + } + } + } +} + +` + +const ListGroupAuthorizedResourcesDocument = ` +query listGroupAuthorizedResources($code: String!, $namespace: String, $resourceType: String) { + group(code: $code) { + authorizedResources(namespace: $namespace, resourceType: $resourceType) { + totalCount + list { + code + type + actions + } + } + } +} +` diff --git a/lib/constant/gql_manage_org.go b/lib/constant/gql_manage_org.go new file mode 100644 index 0000000..2ce9038 --- /dev/null +++ b/lib/constant/gql_manage_org.go @@ -0,0 +1,480 @@ +package constant + +const CreateOrgDocument = ` +mutation createOrg($name: String!, $code: String, $description: String) { + createOrg(name: $name, code: $code, description: $description) { + id + rootNode { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + } + nodes { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + } + } +} +` + +const DeleteOrgDocument = ` +mutation deleteOrg($id: String!) { + deleteOrg(id: $id) { + message + code + } +} +` + +const ListOrgDocument = ` +query orgs($page: Int, $limit: Int, $sortBy: SortByEnum) { + orgs(page: $page, limit: $limit, sortBy: $sortBy) { + totalCount + list { + id + rootNode { + id + name + nameI18n + path + description + descriptionI18n + order + code + root + depth + createdAt + updatedAt + children + } + nodes { + id + name + path + nameI18n + description + descriptionI18n + order + code + root + depth + createdAt + updatedAt + children + } + } + } +} + +` + +const AddOrgNodeDocument = ` +mutation addNode($orgId: String!, $parentNodeId: String, $name: String!, $nameI18n: String, $description: String, $descriptionI18n: String, $order: Int, $code: String) { + addNode(orgId: $orgId, parentNodeId: $parentNodeId, name: $name, nameI18n: $nameI18n, description: $description, descriptionI18n: $descriptionI18n, order: $order, code: $code) { + id + rootNode { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + } + nodes { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + } + } +} +` + +const GetOrgNodeDocument = ` +query nodeById($id: String!) { + nodeById(id: $id) { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + } +} + +` + +const UpdateOrgNodeDocument = ` +mutation updateNode($page: Int, $limit: Int, $sortBy: SortByEnum, $includeChildrenNodes: Boolean, $id: String!, $name: String, $code: String, $description: String) { + updateNode(id: $id, name: $name, code: $code, description: $description) { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + users(page: $page, limit: $limit, sortBy: $sortBy, includeChildrenNodes: $includeChildrenNodes) { + totalCount + } + } +} +` + +const DeleteOrgNodeDocument = ` +mutation deleteNode($orgId: String!, $nodeId: String!) { + deleteNode(orgId: $orgId, nodeId: $nodeId) { + message + code + } +} +` + +const IsRootNodeDocument = ` +query isRootNode($nodeId: String!, $orgId: String!) { + isRootNode(nodeId: $nodeId, orgId: $orgId) +} +` + +const MoveNodeDocument = ` + +mutation moveNode($orgId: String!, $nodeId: String!, $targetParentId: String!) { + moveNode(orgId: $orgId, nodeId: $nodeId, targetParentId: $targetParentId) { + id + rootNode { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + } + nodes { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + } + } +}` + +const GetRootNodeDocument = ` +query rootNode($orgId: String!) { + rootNode(orgId: $orgId) { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + codePath + namePath + createdAt + updatedAt + children + } +} + +` + +const AddMembersDocument = ` +mutation addMember($page: Int, $limit: Int, $sortBy: SortByEnum, $includeChildrenNodes: Boolean, $nodeId: String, $orgId: String, $nodeCode: String, $userIds: [String!]!, $isLeader: Boolean) { + addMember(nodeId: $nodeId, orgId: $orgId, nodeCode: $nodeCode, userIds: $userIds, isLeader: $isLeader) { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + createdAt + updatedAt + children + users(page: $page, limit: $limit, sortBy: $sortBy, includeChildrenNodes: $includeChildrenNodes) { + totalCount + list { + id + arn + userPoolId + username + status + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + externalId + } + } + } +} + +` + +const MoveNodeMembersDocument = ` +mutation moveMembers($userIds: [String!]!, $sourceNodeId: String!, $targetNodeId: String!) { + moveMembers(userIds: $userIds, sourceNodeId: $sourceNodeId, targetNodeId: $targetNodeId) { + code + message + } +} + +` + +const RemoveNodeMembersDocument = ` +mutation removeMember($page: Int, $limit: Int, $sortBy: SortByEnum, $includeChildrenNodes: Boolean, $nodeId: String, $orgId: String, $nodeCode: String, $userIds: [String!]!) { + removeMember(nodeId: $nodeId, orgId: $orgId, nodeCode: $nodeCode, userIds: $userIds) { + id + name + nameI18n + description + descriptionI18n + order + code + root + depth + createdAt + updatedAt + children + users(page: $page, limit: $limit, sortBy: $sortBy, includeChildrenNodes: $includeChildrenNodes) { + totalCount + list { + id + arn + userPoolId + status + username + email + emailVerified + phone + phoneVerified + unionid + openid + nickname + registerSource + photo + password + oauth + token + tokenExpiredAt + loginsCount + lastLogin + lastIP + signedUp + blocked + isDeleted + device + browser + company + name + givenName + familyName + middleName + profile + preferredUsername + website + gender + birthdate + zoneinfo + locale + address + formatted + streetAddress + locality + region + postalCode + city + province + country + createdAt + updatedAt + } + } + } +} +` + +const SetUserMainDepartmentDocument = ` +mutation setMainDepartment($userId: String!, $departmentId: String) { + setMainDepartment(userId: $userId, departmentId: $departmentId) { + message + code + } +} +` + +const ListNodeByIdAuthorizedResourcesDocument = ` +query listNodeByIdAuthorizedResources($id: String!, $namespace: String, $resourceType: String) { + nodeById(id: $id) { + authorizedResources(namespace: $namespace, resourceType: $resourceType) { + totalCount + list { + code + type + actions + } + } + } +} + +` + +const ListNodeByCodeAuthorizedResourcesDocument = ` +query listNodeByCodeAuthorizedResources($orgId: String!, $code: String!, $namespace: String, $resourceType: String) { + nodeByCode(orgId: $orgId, code: $code) { + authorizedResources(namespace: $namespace, resourceType: $resourceType) { + totalCount + list { + code + type + actions + } + } + } +} +` + +const SearchNodesDocument = ` +query searchNodes($keyword: String!) { + searchNodes(keyword: $keyword) { + id + orgId + name + nameI18n + description + descriptionI18n + order + code + root + depth + path + codePath + namePath + createdAt + updatedAt + children + } +} +` diff --git a/lib/constant/gql_manage_policy.go b/lib/constant/gql_manage_policy.go new file mode 100644 index 0000000..0cc620e --- /dev/null +++ b/lib/constant/gql_manage_policy.go @@ -0,0 +1,162 @@ +package constant + +const CreatePolicyDocument = ` +mutation createPolicy($namespace: String, $code: String!, $description: String, $statements: [PolicyStatementInput!]!) { + createPolicy(namespace: $namespace, code: $code, description: $description, statements: $statements) { + namespace + code + isDefault + description + statements { + resource + actions + effect + condition { + param + operator + value + } + } + createdAt + updatedAt + assignmentsCount + } +} + +` + +const ListPolicyDocument = ` +query policies($page: Int, $limit: Int, $namespace: String) { + policies(page: $page, limit: $limit, namespace: $namespace) { + totalCount + list { + namespace + code + description + createdAt + updatedAt + statements { + resource + actions + effect + condition { + param + operator + value + } + } + } + } +} +` + +const DetailPolicyDocument = ` +query policy($namespace: String, $code: String!) { + policy(code: $code, namespace: $namespace) { + namespace + code + isDefault + description + statements { + resource + actions + effect + condition { + param + operator + value + } + } + createdAt + updatedAt + } +} + +` + +const UpdatePolicyDocument = ` +mutation updatePolicy($namespace: String, $code: String!, $description: String, $statements: [PolicyStatementInput!], $newCode: String) { + updatePolicy(namespace: $namespace, code: $code, description: $description, statements: $statements, newCode: $newCode) { + namespace + code + description + statements { + resource + actions + effect + condition { + param + operator + value + } + } + createdAt + updatedAt + } +} + +` + +const DeletePolicyDocument = ` +mutation deletePolicy($code: String!, $namespace: String) { + deletePolicy(code: $code, namespace: $namespace) { + message + code + } +} +` + +const BatchDeletePolicyDocument = ` +mutation deletePolicies($codeList: [String!]!, $namespace: String) { + deletePolicies(codeList: $codeList, namespace: $namespace) { + message + code + } +} +` +const PolicyAssignmentsDocument = ` +query policyAssignments($namespace: String, $code: String, $targetType: PolicyAssignmentTargetType, $targetIdentifier: String, $page: Int, $limit: Int) { + policyAssignments(namespace: $namespace, code: $code, targetType: $targetType, targetIdentifier: $targetIdentifier, page: $page, limit: $limit) { + totalCount + list { + code + targetType + targetIdentifier + } + } +} +` +const AddAssignmentsDocument = ` +mutation addPolicyAssignments($policies: [String!]!, $targetType: PolicyAssignmentTargetType!, $targetIdentifiers: [String!], $inheritByChildren: Boolean, $namespace: String) { + addPolicyAssignments(policies: $policies, targetType: $targetType, targetIdentifiers: $targetIdentifiers, inheritByChildren: $inheritByChildren, namespace: $namespace) { + message + code + } +} +` +const RemoveAssignmentsDocument = ` +mutation removePolicyAssignments($policies: [String!]!, $targetType: PolicyAssignmentTargetType!, $targetIdentifiers: [String!], $namespace: String) { + removePolicyAssignments(policies: $policies, targetType: $targetType, targetIdentifiers: $targetIdentifiers, namespace: $namespace) { + message + code + } +} +` + +const EnablePolicyAssignmentDocument = ` +mutation enablePolicyAssignment($policy: String!, $targetType: PolicyAssignmentTargetType!, $targetIdentifier: String!, $namespace: String) { + enablePolicyAssignment(policy: $policy, targetType: $targetType, targetIdentifier: $targetIdentifier, namespace: $namespace) { + message + code + } +} +` +const DisablePolicyAssignmentDocument = ` +mutation disbalePolicyAssignment($policy: String!, $targetType: PolicyAssignmentTargetType!, $targetIdentifier: String!, $namespace: String) { + disbalePolicyAssignment(policy: $policy, targetType: $targetType, targetIdentifier: $targetIdentifier, namespace: $namespace) { + message + code + } +} + +` diff --git a/lib/constant/gql_manage_user.go b/lib/constant/gql_manage_user.go index 0a8b3bc..db8811c 100644 --- a/lib/constant/gql_manage_user.go +++ b/lib/constant/gql_manage_user.go @@ -753,3 +753,11 @@ mutation setUdv($targetType: UDFTargetType!, $targetId: String!, $key: String!, } } ` +const SendFirstLoginVerifyEmailDocument = ` +mutation sendFirstLoginVerifyEmail($userId: String!, $appId: String!) { + sendFirstLoginVerifyEmail(userId: $userId, appId: $appId) { + message + code + } +} +` diff --git a/lib/management/acl_management_client.go b/lib/management/acl_management_client.go index 0689b93..9379f8b 100644 --- a/lib/management/acl_management_client.go +++ b/lib/management/acl_management_client.go @@ -2,12 +2,19 @@ package management import ( "encoding/json" + "errors" + "fmt" "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/model" + "github.com/Authing/authing-go-sdk/lib/util" "github.com/bitly/go-simplejson" + jsoniter "github.com/json-iterator/go" "log" + "net/http" ) +//IsAllowed +//判断某个用户是否对某个资源有某个操作权限 func (c *Client) IsAllowed(request model.IsAllowedRequest) (bool, error) { data, _ := json.Marshal(&request) variables := make(map[string]interface{}) @@ -25,6 +32,8 @@ func (c *Client) IsAllowed(request model.IsAllowedRequest) (bool, error) { return result, nil } +//Allow +//允许某个用户对某个资源进行某个操作 func (c *Client) Allow(request model.AllowRequest) (bool, error) { data, _ := json.Marshal(&request) variables := make(map[string]interface{}) @@ -43,6 +52,8 @@ func (c *Client) Allow(request model.AllowRequest) (bool, error) { } +//AuthorizeResource +//将一个(类)资源授权给用户、角色、分组、组织机构,且可以分别指定不同的操作权限。 func (c *Client) AuthorizeResource(request model.AuthorizeResourceRequest) (bool, error) { data, _ := json.Marshal(&request) variables := make(map[string]interface{}) @@ -60,6 +71,8 @@ func (c *Client) AuthorizeResource(request model.AuthorizeResourceRequest) (bool return result == 200, nil } +//RevokeResource +//批量撤销资源的授权 func (c *Client) RevokeResource(request model.RevokeResourceRequest) (bool, error) { data, _ := json.Marshal(&request) variables := make(map[string]interface{}) @@ -74,6 +87,545 @@ func (c *Client) RevokeResource(request model.RevokeResourceRequest) (bool, erro return result == 200, nil } +// ListAuthorizedResourcesForCustom +// 获取某个主体(用户、角色、分组、组织机构节点)被授权的所有资源。 +func (c *Client) ListAuthorizedResourcesForCustom(request model.ListAuthorizedResourcesRequest) (*struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` +}, error) { + + data, _ := json.Marshal(&request) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListAuthorizedResourcesDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + AuthorizedResources struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` + } `json:"authorizedResources"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.AuthorizedResources, nil +} + +// ProgrammaticAccessAccountList +// 编程访问账号列表 +func (c *Client) ProgrammaticAccessAccountList(appId string, page, limit int) (*struct { + TotalCount int64 `json:"totalCount"` + List []model.ProgrammaticAccessAccount `json:"list"` +}, error) { + + url := fmt.Sprintf("%s/api/v2/applications/%s/programmatic-access-accounts?limit=%v&page=%v", c.Host, appId, limit, page) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + TotalCount int64 `json:"totalCount"` + List []model.ProgrammaticAccessAccount `json:"list"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// CreateProgrammaticAccessAccount +// 添加编程访问账号 +func (c *Client) CreateProgrammaticAccessAccount(appId string, remark *string, tokenLifetime *int) (*model.ProgrammaticAccessAccount, error) { + + vars := make(map[string]interface{}) + if tokenLifetime == nil { + vars["tokenLifetime"] = 600 + } else { + vars["tokenLifetime"] = tokenLifetime + } + if remark != nil { + vars["remark"] = remark + } + url := fmt.Sprintf("%s/api/v2/applications/%s/programmatic-access-accounts", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ProgrammaticAccessAccount `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// DisableProgrammaticAccessAccount +// 禁用编程访问账号 +func (c *Client) DisableProgrammaticAccessAccount(programmaticAccessAccountId string) (*model.ProgrammaticAccessAccount, error) { + + url := fmt.Sprintf("%s/api/v2/applications/programmatic-access-accounts", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPatch, map[string]interface{}{ + "id": programmaticAccessAccountId, + "enabled": false, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ProgrammaticAccessAccount `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// EnableProgrammaticAccessAccount +// 启用编程访问账号 +func (c *Client) EnableProgrammaticAccessAccount(programmaticAccessAccountId string) (*model.ProgrammaticAccessAccount, error) { + + url := fmt.Sprintf("%s/api/v2/applications/programmatic-access-accounts", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPatch, map[string]interface{}{ + "id": programmaticAccessAccountId, + "enabled": true, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ProgrammaticAccessAccount `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// RefreshProgrammaticAccessAccountSecret +// 刷新编程访问账号密钥 +func (c *Client) RefreshProgrammaticAccessAccountSecret(programmaticAccessAccountId string, secret *string) (*model.ProgrammaticAccessAccount, error) { + + vars := map[string]interface{}{ + "id": programmaticAccessAccountId, + } + if secret == nil { + vars["secret"] = util.RandomString(32) + } else { + vars["secret"] = secret + } + url := fmt.Sprintf("%s/api/v2/applications/programmatic-access-accounts", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPatch, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ProgrammaticAccessAccount `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// DeleteProgrammaticAccessAccount +// 删除编程访问账号 +func (c *Client) DeleteProgrammaticAccessAccount(programmaticAccessAccountId string) (*string, error) { + + url := fmt.Sprintf("%s/api/v2/applications/programmatic-access-accounts?id=%s", c.Host, programmaticAccessAccountId) + b, err := c.SendHttpRestRequest(url, http.MethodDelete, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// ListNamespaceResources +// 获取资源列表 +func (c *Client) ListNamespaceResources(req model.ListResourceRequest) (*model.ListNamespaceResourceResponse, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + + url := fmt.Sprintf("%s/api/v2/resources", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ListNamespaceResourceResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// GetResourceById +// 根据 ID 获取单个资源 +func (c *Client) GetResourceById(id string) (*model.ResourceResponse, error) { + url := fmt.Sprintf("%s/api/v2/resources/detail", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, map[string]interface{}{"id": id}) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ResourceResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// GetResourceByCode +// 根据 Code 获取单个资源 +func (c *Client) GetResourceByCode(code, namespace string) (*model.ResourceResponse, error) { + url := fmt.Sprintf("%s/api/v2/resources/detail", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, map[string]interface{}{ + "code": code, + "namespace": namespace, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ResourceResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// CreateResource +// 创建资源 +func (c *Client) CreateResource(req *model.CreateResourceRequest) (*model.ResourceResponse, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + + url := fmt.Sprintf("%s/api/v2/resources", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ResourceResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// UpdateResource +// 更新资源 +func (c *Client) UpdateResource(code string, req *model.UpdateResourceRequest) (*model.ResourceResponse, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + url := fmt.Sprintf("%s/api/v2/resources/%s", c.Host, code) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ResourceResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// DeleteResource +// 删除资源 +func (c *Client) DeleteResource(code, namespace string) (*string, error) { + + url := fmt.Sprintf("%s/api/v2/resources/%s", c.Host, code) + b, err := c.SendHttpRestRequest(url, http.MethodDelete, map[string]interface{}{"namespace": namespace}) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// GetApplicationAccessPolicies +// 获取应用访问控制策略列表 +func (c *Client) GetApplicationAccessPolicies(appId string, page, limit int) (*model.GetApplicationAccessPoliciesResponse, error) { + + url := fmt.Sprintf("%s/api/v2/applications/%s/authorization/records", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodGet, map[string]interface{}{ + "page": page, + "limit": limit, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.GetApplicationAccessPoliciesResponse `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// EnableApplicationAccessPolicies +// 启用应用访问控制策略 +func (c *Client) EnableApplicationAccessPolicies(appId string, req *model.ApplicationAccessPoliciesRequest) (*string, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + url := fmt.Sprintf("%s/api/v2/applications/%s/authorization/enable-effect", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// DisableApplicationAccessPolicies +// 停用应用访问控制策略 +func (c *Client) DisableApplicationAccessPolicies(appId string, req *model.ApplicationAccessPoliciesRequest) (*string, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + url := fmt.Sprintf("%s/api/v2/applications/%s/authorization/disable-effect", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// DeleteApplicationAccessPolicies +// 删除应用访问控制策略 +func (c *Client) DeleteApplicationAccessPolicies(appId string, req *model.ApplicationAccessPoliciesRequest) (*string, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + url := fmt.Sprintf("%s/api/v2/applications/%s/authorization/revoke", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// AllowApplicationAccessPolicies +// 配置「允许主体(用户、角色、分组、组织机构节点)访问应用」的控制策略 +func (c *Client) AllowApplicationAccessPolicies(appId string, req *model.ApplicationAccessPoliciesRequest) (*string, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + url := fmt.Sprintf("%s/api/v2/applications/%s/authorization/allow", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// DenyApplicationAccessPolicies +// 配置「拒绝主体(用户、角色、分组、组织机构节点)访问应用」的控制策略 +func (c *Client) DenyApplicationAccessPolicies(appId string, req *model.ApplicationAccessPoliciesRequest) (*string, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + url := fmt.Sprintf("%s/api/v2/applications/%s/authorization/deny", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// UpdateDefaultApplicationAccessPolicy +// 更改默认应用访问策略(默认拒绝所有用户访问应用、默认允许所有用户访问应用) +func (c *Client) UpdateDefaultApplicationAccessPolicy(appId string, strategy constant.ApplicationDefaultAccessPolicies) (*model.Application, error) { + + url := fmt.Sprintf("%s/api/v2/applications/%s", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, map[string]interface{}{ + "permissionStrategy": map[string]interface{}{ + "defaultStrategy": strategy, + }, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.Application `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// GetAuthorizedTargets +// 获取具备某些资源操作权限的主体 +func (c *Client) GetAuthorizedTargets(req *model.GetAuthorizedTargetsRequest) (*struct { + TotalCount int64 `json:"totalCount"` + List []struct { + Actions string `json:"actions"` + TargetType string `json:"targetType"` + TargetIdentifier string `json:"targetIdentifier"` + } `json:"list"` +}, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.GetAuthorizedTargetsDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + AuthorizedTargets struct { + TotalCount int64 `json:"totalCount"` + List []struct { + Actions string `json:"actions"` + TargetType string `json:"targetType"` + TargetIdentifier string `json:"targetIdentifier"` + } `json:"list"` + } `json:"authorizedTargets"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.AuthorizedTargets, nil +} + /*func (c *Client) CheckResourcePermissionBatch(request model.CheckResourcePermissionBatchRequest) (bool, error) { data, _ := json.Marshal(&request) variables := make(map[string]interface{}) diff --git a/lib/management/acl_management_client_test.go b/lib/management/acl_management_client_test.go index 5b347b7..5dd4ab6 100644 --- a/lib/management/acl_management_client_test.go +++ b/lib/management/acl_management_client_test.go @@ -1,6 +1,7 @@ package management import ( + "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/model" "log" "testing" @@ -39,7 +40,7 @@ func TestClient_AuthorizeResource(t *testing.T) { var actions []string actions = append(actions, "*") opt := model.AuthorizeResourceOpt{ - TargetType: model.EnumPolicyAssignmentTargetTypeUSER, + TargetType: model.EnumPolicyAssignmentTargetTypeUser, TargetIdentifier: "611b2ff477d701441c25e29e", Actions: actions, } @@ -61,7 +62,7 @@ func TestClient_RevokeResource(t *testing.T) { var actions []string actions = append(actions, "*") opt := model.AuthorizeResourceOpt{ - TargetType: model.EnumPolicyAssignmentTargetTypeUSER, + TargetType: model.EnumPolicyAssignmentTargetTypeUser, TargetIdentifier: "61090ca34e01a3968d3e3b76", Actions: actions, } @@ -77,6 +78,218 @@ func TestClient_RevokeResource(t *testing.T) { log.Printf("%+v\n", resp) } +func TestClient_ListAuthorizedResourcesForCustom(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========将一个(类)资源取消授权给用户、角色、分组、组织机构==========") + rt := model.EnumResourceTypeAPI + req := model.ListAuthorizedResourcesRequest{ + Namespace: "default", + ResourceType: &rt, + TargetIdentifier: "616d41b7410a33da0cb70e65", + TargetType: constant.USER, + } + resp, _ := client.ListAuthorizedResourcesForCustom(req) + log.Printf("%+v\n", resp) +} + +func TestClient_ProgrammaticAccessAccountList(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========编程账号列表==========") + + resp, _ := client.ProgrammaticAccessAccountList("6168f95e81d5e20f9cb72f22", 1, 10) + log.Printf("%+v\n", resp) +} + +func TestClient_CreateProgrammaticAccessAccount(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========编程账号列表==========") + + resp, _ := client.CreateProgrammaticAccessAccount("6168f95e81d5e20f9cb72f22", nil, nil) + log.Printf("%+v\n", resp) +} + +func TestClient_DisableProgrammaticAccessAccount(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========禁用编程账号==========") + + resp, _ := client.DisableProgrammaticAccessAccount("617109c03d185a5092395cab") + log.Printf("%+v\n", resp) +} + +func TestClient_EnableProgrammaticAccessAccount(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========启用编程账号==========") + + resp, _ := client.EnableProgrammaticAccessAccount("617109c03d185a5092395cab") + log.Printf("%+v\n", resp) +} + +func TestClient_RefreshProgrammaticAccessAccountSecret(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========刷新编程账号访问秘钥==========") + + resp, _ := client.RefreshProgrammaticAccessAccountSecret("617109c03d185a5092395cab", nil) + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteProgrammaticAccessAccount(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========刷新编程账号访问秘钥==========") + + resp, _ := client.DeleteProgrammaticAccessAccount("617109c03d185a5092395cab") + log.Printf("%+v\n", resp) +} + +func TestClient_ListNamespaceResources(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取Namespace下资源列表==========") + + req := model.ListResourceRequest{ + ResourceType: model.EnumResourceTypeAPI, + Namespace: "default", + Page: 1, + Limit: 10, + } + resp, _ := client.ListNamespaceResources(req) + log.Printf("%+v\n", resp) +} + +func TestClient_GetResourceById(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========根据ID获取资源==========") + + resp, _ := client.GetResourceById("616cdf9d1642b20d8c2ec555") + log.Printf("%+v\n", resp) +} + +func TestClient_GetResourceByCode(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========根据 Code 获取资源==========") + + resp, _ := client.GetResourceByCode("ddddd", "default") + log.Printf("%+v\n", resp) +} + +func TestClient_CreateResource(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建资源==========") + req := &model.CreateResourceRequest{ + Code: "nmw", + Namespace: "default", + Actions: []model.ActionsModel{{ + Name: "qqw", + Description: "qwe", + }}, + } + resp, _ := client.CreateResource(req) + log.Printf("%+v\n", resp) +} + +func TestClient_UpdateResource(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========修改资源==========") + req := &model.UpdateResourceRequest{ + + Namespace: "default", + Actions: []model.ActionsModel{{ + Name: "qqwcc", + Description: "qwe", + }}, + } + resp, _ := client.UpdateResource("nmw", req) + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteResource(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除资源==========") + + resp, _ := client.DeleteResource("nmw", "default") + log.Printf("%+v\n", resp) +} + +func TestClient_GetApplicationAccessPolicies(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取应用访问策略==========") + + resp, _ := client.GetApplicationAccessPolicies("6168f95e81d5e20f9cb72f22", 1, 10) + log.Printf("%+v\n", resp) +} + +func TestClient_EnableApplicationAccessPolicies(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========启用应用访问策略==========") + req := &model.ApplicationAccessPoliciesRequest{ + TargetType: constant.USER, + InheritByChildren: true, + TargetIdentifiers: []string{"616e905ebc18f0f106973a29"}, + Namespace: "default", + } + resp, _ := client.EnableApplicationAccessPolicies("6168f95e81d5e20f9cb72f22", req) + log.Printf("%+v\n", resp) +} + +func TestClient_DisableApplicationAccessPolicies(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========禁用应用访问策略==========") + req := &model.ApplicationAccessPoliciesRequest{ + TargetType: constant.USER, + InheritByChildren: true, + TargetIdentifiers: []string{"616e905ebc18f0f106973a29"}, + Namespace: "default", + } + resp, _ := client.DisableApplicationAccessPolicies("6168f95e81d5e20f9cb72f22", req) + log.Printf("%+v\n", resp) +} + +func TestClient_AllowApplicationAccessPolicies(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========允许应用访问策略==========") + req := &model.ApplicationAccessPoliciesRequest{ + TargetType: constant.USER, + InheritByChildren: true, + TargetIdentifiers: []string{"616e905ebc18f0f106973a29"}, + Namespace: "default", + } + resp, _ := client.AllowApplicationAccessPolicies("6168f95e81d5e20f9cb72f22", req) + log.Printf("%+v\n", resp) +} + +func TestClient_DenyApplicationAccessPolicies(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========拒绝应用访问策略==========") + req := &model.ApplicationAccessPoliciesRequest{ + TargetType: constant.USER, + InheritByChildren: true, + TargetIdentifiers: []string{"616e905ebc18f0f106973a29"}, + Namespace: "default", + } + resp, _ := client.DenyApplicationAccessPolicies("6168f95e81d5e20f9cb72f22", req) + log.Printf("%+v\n", resp) +} + +func TestClient_UpdateDefaultApplicationAccessPolicy(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========修改应用默认访问策略==========") + + resp, _ := client.UpdateDefaultApplicationAccessPolicy("6168f95e81d5e20f9cb72f22", constant.AllowAll) + log.Printf("%+v\n", resp) +} + +func TestClient_GetAuthorizedTargets(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取拥有资源的对象列表==========") + + req := &model.GetAuthorizedTargetsRequest{ + TargetType: constant.ROLE, + Resource: "cccccc", + Namespace: "default", + ResourceType: model.EnumResourceTypeAPI, + } + resp, _ := client.GetAuthorizedTargets(req) + log.Printf("%+v\n", resp) +} + /*func TestClient_CheckResourcePermissionBatch(t *testing.T) { client := NewClient(userPoolId, appSecret) log.Println("==========获取用户对某些资源的权限==========") diff --git a/lib/management/application_management_client.go b/lib/management/application_management_client.go new file mode 100644 index 0000000..ef444e0 --- /dev/null +++ b/lib/management/application_management_client.go @@ -0,0 +1,291 @@ +package management + +import ( + "errors" + "fmt" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// ListApplication +// 获取应用列表 +func (c *Client) ListApplication(req *model.CommonPageRequest) (*struct { + List []model.Application `json:"list"` +}, error) { + + url := fmt.Sprintf("%v/api/v2/applications?page=%v&limit=%v", c.Host, req.Page, req.Limit) + b, err := c.SendHttpRequest(url, constant.HttpMethodGet, "", nil) + if err != nil { + return nil, err + } + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + List []model.Application `json:"list"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// CreateApplication +// 创建应用 +func (c *Client) CreateApplication(name, identifier, redirectUris string, logo *string) (*model.Application, error) { + vars := make(map[string]interface{}) + vars["name"] = name + vars["identifier"] = identifier + vars["redirectUris"] = redirectUris + if logo != nil { + vars["logo"] = logo + } + url := fmt.Sprintf("%v/api/v2/applications", c.Host) + b, err := c.SendHttpRequest(url, constant.HttpMethodPost, "", vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.Application `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// DeleteApplication +// 删除应用 +func (c *Client) DeleteApplication(appId string) (*string, error) { + url := fmt.Sprintf("%v/api/v2/applications/%v", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodDelete, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// RefreshApplicationSecret +// 刷新应用密钥 +func (c *Client) RefreshApplicationSecret(appId string) (*model.Application, error) { + url := fmt.Sprintf("%s/api/v2/application/%s/refresh-secret", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPatch, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.Application `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// ListApplicationActiveUsers +// 查看应用下已登录用户 +func (c *Client) ListApplicationActiveUsers(appId string, page, limit int) (*struct { + List []model.ApplicationActiveUsers `json:"list"` + TotalCount int64 `json:"totalCount"` +}, error) { + url := fmt.Sprintf("%s/api/v2/applications/%s/active-users?page=%v&%v", c.Host, appId, page, limit) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + List []model.ApplicationActiveUsers `json:"list"` + TotalCount int64 `json:"totalCount"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// FindApplicationById +// 通过应用 id 查找应用详情 +func (c *Client) FindApplicationById(appId string) (*model.Application, error) { + url := fmt.Sprintf("%s/api/v2/applications/%s", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.Application `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// CreateApplicationAgreement +// 创建应用协议 +func (c *Client) CreateApplicationAgreement(appId, title string, lang *string, required *bool) (*model.ApplicationAgreement, error) { + if lang == nil { + var def = "zh-CN" + lang = &def + } + if required == nil { + var def = true + required = &def + } + vars := map[string]interface{}{ + "title": title, + "lang": lang, + "required": required, + } + url := fmt.Sprintf("%s/api/v2/applications/%s/agreements", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ApplicationAgreement `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// ListApplicationAgreement +// 应用协议列表 +func (c *Client) ListApplicationAgreement(appId string) (*struct { + List []model.ApplicationAgreement `json:"list"` + TotalCount int64 `json:"totalCount"` +}, error) { + + url := fmt.Sprintf("%s/api/v2/applications/%s/agreements", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + List []model.ApplicationAgreement `json:"list"` + TotalCount int64 `json:"totalCount"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// ModifyApplicationAgreement +// 修改应用协议 +func (c *Client) ModifyApplicationAgreement(appId, agreementId, title string, lang *string, required *bool) (*model.ApplicationAgreement, error) { + if lang == nil { + var def = "zh-CN" + lang = &def + } + if required == nil { + var def = true + required = &def + } + vars := map[string]interface{}{ + "title": title, + "lang": lang, + "required": required, + } + url := fmt.Sprintf("%s/api/v2/applications/%s/agreements/%v", c.Host, appId, agreementId) + b, err := c.SendHttpRestRequest(url, http.MethodPut, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.ApplicationAgreement `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// DeleteApplicationAgreement +// 删除应用协议 +func (c *Client) DeleteApplicationAgreement(appId, agreementId string) (*string, error) { + + url := fmt.Sprintf("%s/api/v2/applications/%s/agreements/%v", c.Host, appId, agreementId) + b, err := c.SendHttpRestRequest(url, http.MethodDelete, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// SortApplicationAgreement +// 排序应用协议 +func (c *Client) SortApplicationAgreement(appId string, ids []string) (*string, error) { + + url := fmt.Sprintf("%s/api/v2/applications/%s/agreements/sort", c.Host, appId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, map[string]interface{}{"ids": ids}) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} diff --git a/lib/management/application_management_client_test.go b/lib/management/application_management_client_test.go new file mode 100644 index 0000000..88904ea --- /dev/null +++ b/lib/management/application_management_client_test.go @@ -0,0 +1,125 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_ListApplication(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========查询应用列表==========") + + req := &model.CommonPageRequest{ + Page: 1, + Limit: 10, + } + resp, err := client.ListApplication(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_CreateApplication(t *testing.T) { + log.Println(userPoolId) + client := NewClient(userPoolId, appSecret) + log.Println("==========创建应用==========") + resp, err := client.CreateApplication("sqq12", "noww22", "http://locaqql", nil) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteApplication(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除应用==========") + resp, err := client.DeleteApplication("616fbde39a4c5ce0518d87fc") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_RefreshApplicationSecret(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========刷新应用秘钥==========") + resp, err := client.RefreshApplicationSecret("614bf4af279893d5ab645e58") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListApplicationActiveUsers(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取应用下登录用户==========") + resp, err := client.ListApplicationActiveUsers("614bf4af279893d5ab645e58", 1, 10) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) + log.Println(resp.TotalCount) +} + +func TestClient_FindApplicationById(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========根据ID获取应用==========") + resp, err := client.FindApplicationById("614bf4af279893d5ab645e58") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_CreateApplicationAgreement(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建应用策略==========") + resp, err := client.CreateApplicationAgreement("614bf4af279893d5ab645e58", "cccqq", nil, nil) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListApplicationAgreement(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========遍历应用策略==========") + resp, err := client.ListApplicationAgreement("614bf4af279893d5ab645e58") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ModifyApplicationAgreement(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========修改应用策略==========") + resp, err := client.ModifyApplicationAgreement("614bf4af279893d5ab645e58", "249", "cccqq2", nil, nil) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteApplicationAgreement(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除应用策略==========") + resp, err := client.DeleteApplicationAgreement("614bf4af279893d5ab645e58", "249") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_SortApplicationAgreement(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除应用策略==========") + resp, err := client.SortApplicationAgreement("614bf4af279893d5ab645e58", []string{"238"}) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/management/audit_log_management_client.go b/lib/management/audit_log_management_client.go new file mode 100644 index 0000000..9019f6f --- /dev/null +++ b/lib/management/audit_log_management_client.go @@ -0,0 +1,86 @@ +package management + +import ( + "errors" + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// ListAuditLogs +// 审计日志列表查询 +func (c *Client) ListAuditLogs(req *model.ListAuditLogsRequest) (*struct { + List []interface{} `json:"list"` + TotalCount int64 `json:"totalCount"` +}, error) { + + if req.UserIds != nil { + + var formatUserIds = make([]string, 0) + for _, d := range *req.UserIds { + formatUserId := "arn:cn:authing:user:" + d + formatUserIds = append(formatUserIds, formatUserId) + } + req.UserIds = &formatUserIds + } + vars := make(map[string]interface{}) + url := fmt.Sprintf("%s/api/v2/analysis/audit", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + List []interface{} `json:"list"` + TotalCount int64 `json:"totalCount"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// ListUserAction +// 查看用户操作日志 +func (c *Client) ListUserAction(req *model.ListUserActionRequest) (*struct { + List []interface{} `json:"list"` + TotalCount int64 `json:"totalCount"` +}, error) { + + if req.UserIds != nil { + + var formatUserIds = make([]string, 0) + for _, d := range *req.UserIds { + formatUserId := "arn:cn:authing:user:" + d + formatUserIds = append(formatUserIds, formatUserId) + } + req.UserIds = &formatUserIds + } + vars := make(map[string]interface{}) + url := fmt.Sprintf("%s/api/v2/analysis/user-action", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + List []interface{} `json:"list"` + TotalCount int64 `json:"totalCount"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} diff --git a/lib/management/audit_log_management_client_test.go b/lib/management/audit_log_management_client_test.go new file mode 100644 index 0000000..f69192a --- /dev/null +++ b/lib/management/audit_log_management_client_test.go @@ -0,0 +1,44 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_ListAuditLogs(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========审计日志列表==========") + var userIds = []string{"xx", "xxq"} + page := 1 + limit := 10 + req := &model.ListAuditLogsRequest{ + Page: &page, + Limit: &limit, + UserIds: &userIds, + } + resp, err := client.ListAuditLogs(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListUserActionLogs(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========用户操作日志列表==========") + var userIds = []string{"xx", "xxq"} + page := 1 + limit := 10 + req := &model.ListUserActionRequest{ + Page: &page, + Limit: &limit, + UserIds: &userIds, + } + resp, err := client.ListUserAction(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/management/groups_management_client.go b/lib/management/groups_management_client.go new file mode 100644 index 0000000..c702c1e --- /dev/null +++ b/lib/management/groups_management_client.go @@ -0,0 +1,268 @@ +package management + +import ( + "errors" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// CreateGroups +// 创建分组 +func (c *Client) CreateGroups(req *model.CreateGroupsRequest) (*model.GroupModel, error) { + data, _ := jsoniter.Marshal(req) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.CreateGroupsDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + CreateGroup model.GroupModel `json:"createGroup"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.CreateGroup, nil +} + +// UpdateGroups +// 修改分组 +func (c *Client) UpdateGroups(req *model.UpdateGroupsRequest) (*model.GroupModel, error) { + data, _ := jsoniter.Marshal(req) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdateGroupsDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdateGroup model.GroupModel `json:"updateGroup"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.UpdateGroup, nil +} + +// DetailGroups +// 获取分组详情 +func (c *Client) DetailGroups(code string) (*model.GroupModel, error) { + + variables := map[string]interface{}{"code": code} + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.DetailGroupsDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Group model.GroupModel `json:"group"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Group, nil +} + +// DeleteGroups +// 删除分组 +func (c *Client) DeleteGroups(code string) (*model.CommonMessageAndCode, error) { + r, e := c.BatchDeleteGroups([]string{code}) + return r, e +} + +// ListGroups +// 获取分组列表 +func (c *Client) ListGroups(page, limit int) (*struct { + TotalCount int64 `json:"totalCount"` + List []model.GroupModel `json:"list"` +}, error) { + + variables := map[string]interface{}{"page": page, "limit": limit} + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListGroupsDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Groups struct { + TotalCount int64 `json:"totalCount"` + List []model.GroupModel `json:"list"` + } `json:"groups"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Groups, nil +} + +// BatchDeleteGroups +// 批量删除分组 +func (c *Client) BatchDeleteGroups(codes []string) (*model.CommonMessageAndCode, error) { + variables := map[string]interface{}{"codeList": codes} + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.DeleteGroupsDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + DeleteGroups model.CommonMessageAndCode `json:"deleteGroups"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.DeleteGroups, nil +} + +// ListGroupsUser +// 获取分组用户列表 +func (c *Client) ListGroupsUser(code string, page, limit int, withCustomData bool) (*struct { + TotalCount int `json:"totalCount"` + List []model.User `json:"list"` +}, error) { + variables := map[string]interface{}{ + "code": code, + "page": page, + "limit": limit, + } + query := constant.ListGroupUserDocument + if withCustomData { + query = constant.ListGroupUserWithCustomDocument + } + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, query, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Group model.GetGroupUserResponse `json:"group"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Group.Users, nil +} + +// AddUserToGroups +// 添加用户 +func (c *Client) AddUserToGroups(code string, userIds []string) (*model.CommonMessageAndCode, error) { + variables := map[string]interface{}{ + "code": code, + "userIds": userIds, + } + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.AddUserToGroupDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + AddUserToGroup model.CommonMessageAndCode `json:"addUserToGroup"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.AddUserToGroup, nil +} + +//RemoveGroupUsers +//移除用户 +func (c *Client) RemoveGroupUsers(code string, userIds []string) (*model.CommonMessageAndCode, error) { + + variables := map[string]interface{}{ + "code": code, + "userIds": userIds, + } + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemoveUserInGroupDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RemoveUserFromGroup model.CommonMessageAndCode `json:"removeUserFromGroup"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.RemoveUserFromGroup, nil +} + +//ListGroupsAuthorizedResources +//获取分组被授权的所有资源 +func (c *Client) ListGroupsAuthorizedResources(req *model.ListGroupsAuthorizedResourcesRequest) (*struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` +}, error) { + data, _ := jsoniter.Marshal(req) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListGroupAuthorizedResourcesDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Group struct { + AuthorizedResources struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` + } `json:"authorizedResources"` + } `json:"group"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Group.AuthorizedResources, nil +} diff --git a/lib/management/groups_management_client_test.go b/lib/management/groups_management_client_test.go new file mode 100644 index 0000000..2da66ba --- /dev/null +++ b/lib/management/groups_management_client_test.go @@ -0,0 +1,99 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_CreateGroups(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建分组==========") + req := &model.CreateGroupsRequest{ + Code: "goSDK", + Name: "goSDK", + } + resp, err := client.CreateGroups(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_UpdateGroups(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========更新分组==========") + newCode := "newGoSdk" + req := &model.UpdateGroupsRequest{ + Code: "goSDK", + NewCode: &newCode, + } + resp, err := client.UpdateGroups(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DetailGroups(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========分组详情==========") + + resp, err := client.DetailGroups("newGoSdk") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteGroups(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除分组==========") + + resp, err := client.DeleteGroups("newGoSdk") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListGroups(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========分组列表==========") + + resp, err := client.ListGroups(1, 10) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListGroupsUser(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========分组下的用户列表==========") + + resp, err := client.ListGroupsUser("jjwjl", 1, 10, false) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListGroupsAuthorizedResources(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取分组授权资源==========") + cc := model.EnumResourceTypeAPI + nm := "default" + req := &model.ListGroupsAuthorizedResourcesRequest{ + Code: "kcerb", + //Code: "kmvnk", + ResourceType: &cc, + Namespace: &nm, + } + resp, err := client.ListGroupsAuthorizedResources(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/management/management_client.go b/lib/management/management_client.go index 28dc963..ed582c6 100644 --- a/lib/management/management_client.go +++ b/lib/management/management_client.go @@ -4,10 +4,12 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/model" "github.com/Authing/authing-go-sdk/lib/util/cacheutil" + jsoniter "github.com/json-iterator/go" "github.com/valyala/fasthttp" "golang.org/x/oauth2" "io/ioutil" @@ -167,7 +169,49 @@ func (c *Client) SendHttpRequest(url string, method string, query string, variab req.Header.Add("x-authing-request-from", constant.SdkType) req.Header.Add("x-authing-sdk-version", constant.SdkVersion) req.Header.Add("x-authing-app-id", ""+constant.AppId) + res, err := c.HttpClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + body, err := ioutil.ReadAll(res.Body) + return body, nil +} + +func (c *Client) SendHttpRestRequest(url string, method string, variables map[string]interface{}) ([]byte, error) { + var req *http.Request + if method == constant.HttpMethodGet { + req, _ = http.NewRequest(http.MethodGet, url, nil) + if variables != nil && len(variables) > 0 { + q := req.URL.Query() + for key, value := range variables { + q.Add(key, fmt.Sprintf("%v", value)) + } + req.URL.RawQuery = q.Encode() + } + + } else { + + var buf bytes.Buffer + var err error + if variables != nil { + err = json.NewEncoder(&buf).Encode(variables) + + } + if err != nil { + return nil, err + } + req, err = http.NewRequest(method, url, &buf) + req.Header.Add("Content-Type", "application/json") + } + token, _ := GetAccessToken(c) + req.Header.Add("Authorization", "Bearer "+token) + + req.Header.Add("x-authing-userpool-id", ""+c.userPoolId) + req.Header.Add("x-authing-request-from", constant.SdkType) + req.Header.Add("x-authing-sdk-version", constant.SdkVersion) + req.Header.Add("x-authing-app-id", ""+constant.AppId) res, err := c.HttpClient.Do(req) if err != nil { return nil, err @@ -290,3 +334,79 @@ func CreateRequestParam(param struct{}) map[string]interface{} { json.Unmarshal(data, &variables) return variables } + +// SendEmail +// 发送邮件 +func (c *Client) SendEmail(email string, scene model.EnumEmailScene) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.SendMailDocument, + map[string]interface{}{"email": email, "scene": scene}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SendMail model.CommonMessageAndCode `json:"sendEmail"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SendMail, nil +} + +// CheckLoginStatusByToken +// 检测登录状态 +func (c *Client) CheckLoginStatusByToken(token string) (*model.CheckLoginStatusResponse, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.CheckLoginStatusDocument, + map[string]interface{}{"token": token}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + CheckLoginStatus model.CheckLoginStatusResponse `json:"checkLoginStatus"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.CheckLoginStatus, nil +} + +// IsPasswordValid +// 检测密码是否合法 +func (c *Client) IsPasswordValid(password string) (*struct { + Valid bool `json:"valid"` + Message string `json:"message"` +}, error) { + + url := fmt.Sprintf("%s/api/v2/password/check", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, map[string]interface{}{"password": password}) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + Valid bool `json:"valid"` + Message string `json:"message"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} diff --git a/lib/management/namespace_management_client.go b/lib/management/namespace_management_client.go new file mode 100644 index 0000000..7f9ff0b --- /dev/null +++ b/lib/management/namespace_management_client.go @@ -0,0 +1,110 @@ +package management + +import ( + "encoding/json" + "errors" + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// CreateNamespace +// 创建权限分组 +func (c *Client) CreateNamespace(request *model.EditNamespaceRequest) (*model.Namespace, error) { + data, _ := json.Marshal(&request) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + url := fmt.Sprintf("%s/api/v2/resource-namespace/%s", c.Host, c.userPoolId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.Namespace `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// UpdateNamespace +// 修改权限分组 +func (c *Client) UpdateNamespace(id string, request *model.EditNamespaceRequest) (*model.Namespace, error) { + + data, _ := json.Marshal(&request) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + + url := fmt.Sprintf("%s/api/v2/resource-namespace/%s/%s", c.Host, c.userPoolId, id) + b, err := c.SendHttpRestRequest(url, http.MethodPut, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.Namespace `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// DeleteNamespace +// 删除权限分组 +func (c *Client) DeleteNamespace(id string) (*string, error) { + + url := fmt.Sprintf("%s/api/v2/resource-namespace/%s/%s", c.Host, c.userPoolId, id) + b, err := c.SendHttpRestRequest(url, http.MethodDelete, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// ListNamespace +// 权限分组列表 +func (c *Client) ListNamespace(page, limit int) (*struct { + List []model.Namespace `json:"list"` + Total int64 `json:"total"` +}, error) { + + url := fmt.Sprintf("%s/api/v2/resource-namespace/%s?page=%v&limit=%v", c.Host, c.userPoolId, page, limit) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data struct { + List []model.Namespace `json:"list"` + Total int64 `json:"total"` + } `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} diff --git a/lib/management/namespace_management_client_test.go b/lib/management/namespace_management_client_test.go new file mode 100644 index 0000000..c980f0d --- /dev/null +++ b/lib/management/namespace_management_client_test.go @@ -0,0 +1,62 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_CreateNamespace(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建权限分组==========") + code := "qCode" + name := "qName" + req := &model.EditNamespaceRequest{ + Code: &code, + Name: &name, + } + resp, err := client.CreateNamespace(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_UpdateNamespace(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========修改权限分组==========") + code := "qCodeww" + name := "qNameww" + req := &model.EditNamespaceRequest{ + Code: &code, + Name: &name, + } + resp, err := client.UpdateNamespace("54156", req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListNamespace(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========权限分组列表==========") + + resp, err := client.ListNamespace(1, 10) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteNamespace(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========权限分组列表==========") + + resp, err := client.DeleteNamespace("54156") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/management/organization_management_client.go b/lib/management/organization_management_client.go index 1a86563..e192e61 100644 --- a/lib/management/organization_management_client.go +++ b/lib/management/organization_management_client.go @@ -2,11 +2,14 @@ package management import ( "encoding/json" + "errors" + "fmt" "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/enum" "github.com/Authing/authing-go-sdk/lib/model" jsoniter "github.com/json-iterator/go" "log" + "net/http" ) // ExportAll @@ -103,3 +106,530 @@ func (c *Client) GetOrganizationChildren(nodeId string, depth int) (*[]model.Nod jsoniter.Unmarshal(b, &response) return &response.Data, nil } + +// CreateOrg +// 创建组织机构 +func (c *Client) CreateOrg(req *model.CreateOrgRequest) (*model.OrgResponse, error) { + data, _ := jsoniter.Marshal(req) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.CreateOrgDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + CreateOrg model.OrgResponse `json:"createOrg"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.CreateOrg, nil +} + +// DeleteOrgById +// 删除组织机构 +func (c *Client) DeleteOrgById(id string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.DeleteOrgDocument, map[string]interface{}{ + "id": id, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + DeleteOrg model.CommonMessageAndCode `json:"deleteOrg"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.DeleteOrg, nil +} + +// ListOrg +// 获取用户池组织机构列表 +func (c *Client) ListOrg(page, limit int) (*model.PaginatedOrgs, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListOrgDocument, map[string]interface{}{ + "page": page, + "limit": limit, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Orgs model.PaginatedOrgs `json:"orgs"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Orgs, nil +} + +// AddOrgNode +// 在组织机构中添加一个节点 +func (c *Client) AddOrgNode(req *model.AddOrgNodeRequest) (*model.AddNodeOrg, error) { + data, _ := jsoniter.Marshal(req) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.AddOrgNodeDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + AddNode model.AddNodeOrg `json:"addNode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.AddNode, nil +} + +// GetOrgNodeById +// 获取某个节点详情 +func (c *Client) GetOrgNodeById(id string) (*model.OrgNodeChildStr, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.GetOrgNodeDocument, map[string]interface{}{ + "id": id, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + NodeById model.OrgNodeChildStr `json:"nodeById"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.NodeById, nil +} + +// UpdateOrgNode +// 修改节点 +func (c *Client) UpdateOrgNode(req *model.UpdateOrgNodeRequest) (*model.Node, error) { + data, _ := jsoniter.Marshal(req) + variables := make(map[string]interface{}) + jsoniter.Unmarshal(data, &variables) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdateOrgNodeDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdateNode model.Node `json:"updateNode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.UpdateNode, nil +} + +// DeleteOrgNode +// 删除节点 +func (c *Client) DeleteOrgNode(orgId, nodeId string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.DeleteOrgNodeDocument, map[string]interface{}{ + "orgId": orgId, + "nodeId": nodeId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + DeleteNode model.CommonMessageAndCode `json:"deleteNode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.DeleteNode, nil +} + +// IsRootNode +// 判断是否为根节点 +func (c *Client) IsRootNode(orgId, nodeId string) (*bool, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.IsRootNodeDocument, map[string]interface{}{ + "orgId": orgId, + "nodeId": nodeId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + IsRootNode bool `json:"isRootNode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.IsRootNode, nil +} + +// MoveOrgNode +// 移动节点 +func (c *Client) MoveOrgNode(orgId, nodeId, targetParentId string) (*model.AddNodeOrg, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.MoveNodeDocument, map[string]interface{}{ + "orgId": orgId, + "nodeId": nodeId, + "targetParentId": targetParentId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + MoveNode model.AddNodeOrg `json:"moveNode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.MoveNode, nil +} + +// GetRootNode +// 获取根节点 +func (c *Client) GetRootNode(orgId string) (*model.OrgNodeChildStr, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.GetRootNodeDocument, map[string]interface{}{ + "orgId": orgId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RootNode model.OrgNodeChildStr `json:"rootNode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.RootNode, nil +} + +// ImportNodeByJSON +// 通过 JSON 导入 +func (c *Client) ImportNodeByJSON(jsonStr string) (*string, error) { + + url := fmt.Sprintf("%s/api/v2/orgs/import", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, map[string]interface{}{ + "filetype": "json", + "file": jsonStr, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Message, nil +} + +// AddMembers +// 节点添加成员 +func (c *Client) AddMembers(nodeId string, userIds []string) (*model.Node, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.AddMembersDocument, map[string]interface{}{ + "nodeId": nodeId, + "userIds": userIds, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + AddMember model.Node `json:"addMember"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.AddMember, nil +} + +// MoveNodeMembers +// 移动节点成员 +func (c *Client) MoveNodeMembers(nodeId, targetNodeId string, userIds []string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.MoveNodeMembersDocument, map[string]interface{}{ + "userIds": userIds, + "targetNodeId": targetNodeId, + "sourceNodeId": nodeId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + MoveMembers model.CommonMessageAndCode `json:"moveMembers"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.MoveMembers, nil +} + +// DeleteNodeMembers +// 删除节点成员 +func (c *Client) DeleteNodeMembers(nodeId string, userIds []string) (*model.Node, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemoveNodeMembersDocument, map[string]interface{}{ + "userIds": userIds, + "nodeId": nodeId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RemoveMembers model.Node `json:"removeMember"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.RemoveMembers, nil +} + +// SetMainDepartment +// 设置用户主部门 +func (c *Client) SetMainDepartment(departmentId, userId string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.SetUserMainDepartmentDocument, map[string]interface{}{ + "userId": userId, + "departmentId": departmentId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SetMainDepartment model.CommonMessageAndCode `json:"setMainDepartment"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SetMainDepartment, nil +} + +// ExportByOrgId +// 导出某个组织机构 +func (c *Client) ExportByOrgId(orgId string) (*model.OrgNode, error) { + + url := fmt.Sprintf("%s/api/v2/orgs/export?org_id=%s", c.Host, orgId) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.OrgNode `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// ListAuthorizedResourcesByNodeId +// 获取组织机构节点被授权的所有资源 +func (c *Client) ListAuthorizedResourcesByNodeId(req *model.ListAuthorizedResourcesByIdRequest) (*struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` +}, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListNodeByIdAuthorizedResourcesDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + NodeByCode struct { + AuthorizedResources struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` + } `json:"authorizedResources"` + } `json:"nodeByCode"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.NodeByCode.AuthorizedResources, nil +} + +// ListAuthorizedResourcesByNodeCode +// 获取组织机构节点被授权的所有资源 +func (c *Client) ListAuthorizedResourcesByNodeCode(req *model.ListAuthorizedResourcesByNodeCodeRequest) (*struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` +}, error) { + data, _ := json.Marshal(&req) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListNodeByIdAuthorizedResourcesDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + NodeById struct { + AuthorizedResources struct { + TotalCount int64 `json:"totalCount"` + List []model.AuthorizedResource `json:"list"` + } `json:"authorizedResources"` + } `json:"nodeById"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.NodeById.AuthorizedResources, nil +} + +// SearchNodes +// 搜索组织机构节点 +func (c *Client) SearchNodes(keywords string) (*[]model.OrgNodeChildStr, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, + constant.SearchNodesDocument, map[string]interface{}{"keyword": keywords}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SearchNodes []model.OrgNodeChildStr `json:"searchNodes"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SearchNodes, nil +} + +// +//// StartSync +//// 组织机构同步 +//func (c *Client) StartSync(providerType constant.ProviderTypeEnum, connectionId *string) (*interface{}, error) { +// +// url:=fmt.Sprintf("%s/connections/enterprise/%s/start-sync",c.Host,providerType) +// vars:=make(map[string]interface{}) +// if providerType == constant.AD { +// url = fmt.Sprintf("%s/api/v2/ad/sync",c.Host) +// vars["connectionId"]=connectionId +// } +// b, err := c.SendHttpRestRequest(url, http.MethodPost, vars) +// if err != nil { +// return nil, err +// } +// log.Println(string(b)) +// resp :=&struct { +// Message string `json:"message"` +// Code int64 `json:"code"` +// Data interface{} `json:"data"` +// }{} +// jsoniter.Unmarshal(b, &resp) +// if resp.Code != 200 { +// return nil, errors.New(resp.Message) +// } +// return &resp.Data, nil +//} diff --git a/lib/management/organization_management_client_test.go b/lib/management/organization_management_client_test.go index bf14753..e5b210b 100644 --- a/lib/management/organization_management_client_test.go +++ b/lib/management/organization_management_client_test.go @@ -1,6 +1,7 @@ package management import ( + "fmt" "github.com/Authing/authing-go-sdk/lib/enum" "github.com/Authing/authing-go-sdk/lib/model" "log" @@ -9,17 +10,11 @@ import ( const ( // prod - userPoolId = "60e043f8cd91b87d712b6365" - appSecret = "158c7679333bc196b524d78d745813e5" - // dev - userPoolIdDev = "61090ca2ae21b81053abbd07" - appSecretDev = "db3e0a32cd5629fe12c9d29911abb9b7" - //userPoolId = "60e043f8cd91b87d712b6365" - //appSecret = "158c7679333bc196b524d78d745813e5" - //userPoolId = "6114ea3b25851f2e44db357f" - //appSecret = "4f673a16f53cbbf54633212b1a882a2a" - //userPoolId = "61384d3e302f1f75e69ce95a" - //appSecret = "ff053c05e4fb664a560556ea7c2cb715" + + userPoolId = "61384d3e302f1f75e69ce95a" + appSecret = "ff053c05e4fb664a560556ea7c2cb715" + //userPoolId = "616fcf8a9447f3ad59ebc1af" + //appSecret = "7e3f194a2c7d1a0dab17fe4c434ca6b0" ) func TestClient_ExportAll(t *testing.T) { @@ -75,3 +70,163 @@ func TestClient_GetOrganizationChildren(t *testing.T) { resp, _ := client.GetOrganizationChildren("60cd9d3a4b96cfff16e7e5f4", 1) log.Printf("%+v\n", resp) } + +func TestClient_CreateOrg(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建组织机构==========") + req := &model.CreateOrgRequest{ + Name: "GoSDKOrg2", + } + resp, _ := client.CreateOrg(req) + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteOrgById(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除组织机构==========") + resp, _ := client.DeleteOrgById("617224b00869fe94de9357de") + log.Printf("%+v\n", resp) +} + +func TestClient_ListOrg(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========遍历组织机构==========") + resp, _ := client.ListOrg(1, 10) + log.Printf("%+v\n", resp) +} + +func TestClient_GetOrgNodeById(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========根据ID获取节点==========") + resp, _ := client.GetOrgNodeById("61725b9f3ad07a44b85302b1") + log.Printf("%+v\n", resp) +} + +func TestClient_UpdateOrgNode(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========修改节点==========") + updateName := "updateName" + req := &model.UpdateOrgNodeRequest{ + Name: &updateName, + Id: "617230eba040848abb3689b7", + } + resp, _ := client.UpdateOrgNode(req) + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteOrgNode(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除节点==========") + resp, _ := client.DeleteOrgNode("617230eba040848abb3689b7", "6172315f5371116d5ad5ead9") + log.Printf("%+v\n", resp) +} + +func TestClient_IsRootNode(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========判断是否根节点==========") + resp, _ := client.IsRootNode("6142c2c41c6e6c6cc3edfd88", "6142e08f64d5a8873598e9fb") + log.Printf("%+v\n", resp) +} + +func TestClient_MoveOrgNode(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========移动节点==========") + resp, _ := client.MoveOrgNode("6142c2c41c6e6c6cc3edfd88", "6142e08f64d5a8873598e9fb", "6142e03436f09aa7e66c1935") + log.Printf("%+v\n", resp) +} + +func TestClient_GetRootNode(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取根节点==========") + resp, _ := client.GetRootNode("6142c2c41c6e6c6cc3edfd88") + log.Printf("%+v\n", resp) +} + +func TestClient_ImportNodeByJSON(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========通过JSON导入==========") + json := ` + { + "name": "北京非凡科技有限公司", + "code": "feifan", + "children": [] + }` + resp, _ := client.ImportNodeByJSON(json) + log.Printf("%+v\n", resp) +} + +func TestClient_AddMembers(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========新增节点成员==========") + resp, _ := client.AddMembers("61722ece541df9301478b17d", []string{"6141876341abedef979c3740"}) + log.Printf("%+v\n", resp) +} + +func TestClient_MoveNodeMembers(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========移动节点成员==========") + resp, _ := client.MoveNodeMembers("61722ece541df9301478b17d", "617230eba040848abb3689b7", []string{"6141876341abedef979c3740"}) + log.Printf("%+v\n", resp) +} + +func TestClient_DeleteNodeMembers(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除节点成员==========") + resp, _ := client.DeleteNodeMembers("617230eba040848abb3689b7", []string{"6141876341abedef979c3740"}) + log.Printf("%+v\n", resp) +} + +func TestClient_SetMainDepartment(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========设置用户主部门==========") + resp, _ := client.SetMainDepartment("6142e0483f54818690c99600", "6141876341abedef979c3740") + log.Printf("%+v\n", resp) +} + +func TestClient_ExportByOrgId(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========设置用户主部门==========") + resp, _ := client.ExportByOrgId("6142c2c41c6e6c6cc3edfd88") + log.Printf("%+v\n", resp) +} + +func TestClient_ListAuthorizedResourcesByNodeId(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取机构授权资源==========") + req := &model.ListAuthorizedResourcesByIdRequest{Id: "61725b9f321fcc1ca9e36ddc"} + resp, _ := client.ListAuthorizedResourcesByNodeId(req) + log.Printf("%+v\n", resp) +} + +func TestClient_SearchNodes(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取机构授权资源==========") + + resp, _ := client.SearchNodes("qq") + log.Printf("%+v\n", resp) +} + +func TestClient_AddOrgNode(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========权限分组列表==========") + + req := &model.AddOrgNodeRequest{ + Name: "qqqw", + ParentNodeId: "617230eba040848abb3689b7", + OrgId: "61722ececf7cd66d1ec27075", + } + resp, err := client.AddOrgNode(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +// +//func TestClient_StartSync(t *testing.T) { +// client := NewClient(userPoolId, appSecret) +// log.Println("==========获取机构授权资源==========") +// +// resp, _ := client.StartSync( constant.WechatWork,nil) +// log.Printf("%+v\n", resp) +//} diff --git a/lib/management/policies_management_client.go b/lib/management/policies_management_client.go new file mode 100644 index 0000000..790112e --- /dev/null +++ b/lib/management/policies_management_client.go @@ -0,0 +1,286 @@ +package management + +import ( + "errors" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// CreatePolicy +// 添加策略 +func (c *Client) CreatePolicy(req *model.PolicyRequest) (*model.CreatePolicyResponse, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.CreatePolicyDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + CreatePolicy model.CreatePolicyResponse `json:"createPolicy"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.CreatePolicy, nil +} + +// ListPolicy +// 获取策略列表 +func (c *Client) ListPolicy(page, limit int) (*model.PaginatedPolicies, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListPolicyDocument, + map[string]interface{}{"page": page, "limit": limit}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Policies model.PaginatedPolicies `json:"policies"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Policies, nil +} + +// DetailPolicy +// 获取策略详情 +func (c *Client) DetailPolicy(code string) (*model.Policy, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, + constant.DetailPolicyDocument, map[string]interface{}{"code": code}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Policy model.Policy `json:"policy"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Policy, nil +} + +// UpdatePolicy +// 修改策略 +func (c *Client) UpdatePolicy(req *model.PolicyRequest) (*model.UpdatePolicyResponse, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdatePolicyDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdatePolicy model.UpdatePolicyResponse `json:"updatePolicy"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.UpdatePolicy, nil +} + +// DeletePolicy +// 删除策略 +func (c *Client) DeletePolicy(code string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, + constant.DeletePolicyDocument, map[string]interface{}{"code": code}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + DeletePolicy model.CommonMessageAndCode `json:"deletePolicy"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.DeletePolicy, nil +} + +// BatchDeletePolicy +// 删除策略 +func (c *Client) BatchDeletePolicy(codeList []string) (*model.CommonMessageAndCode, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, + constant.BatchDeletePolicyDocument, map[string]interface{}{"codeList": codeList}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + DeletePolicies model.CommonMessageAndCode `json:"deletePolicies"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.DeletePolicies, nil +} + +// ListAssignments +// 获取策略授权记录 +func (c *Client) ListAssignments(code string, page, limit int) (*model.PaginatedPolicyAssignments, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.PolicyAssignmentsDocument, + map[string]interface{}{"code": code, "page": page, "limit": limit}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + PolicyAssignments model.PaginatedPolicyAssignments `json:"policyAssignments"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.PolicyAssignments, nil +} + +// AddAssignments +// 添加策略授权 +func (c *Client) AddAssignments(req *model.PolicyAssignmentsRequest) (*model.CommonMessageAndCode, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.AddAssignmentsDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + AddPolicyAssignments model.CommonMessageAndCode `json:"addPolicyAssignments"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.AddPolicyAssignments, nil +} + +// RemoveAssignments +// 撤销策略授权 +func (c *Client) RemoveAssignments(req *model.PolicyAssignmentsRequest) (*model.CommonMessageAndCode, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemoveAssignmentsDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RemovePolicyAssignments model.CommonMessageAndCode `json:"removePolicyAssignments"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.RemovePolicyAssignments, nil +} + +// EnableAssignments +// 设置策略授权状态为开启 +func (c *Client) EnableAssignments(req *model.SwitchPolicyAssignmentsRequest) (*model.CommonMessageAndCode, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.EnablePolicyAssignmentDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + EnablePolicyAssignment model.CommonMessageAndCode `json:"enablePolicyAssignment"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.EnablePolicyAssignment, nil +} + +// DisableAssignments +// 设置策略授权状态为关闭 +func (c *Client) DisableAssignments(req *model.SwitchPolicyAssignmentsRequest) (*model.CommonMessageAndCode, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.DisablePolicyAssignmentDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + DisablePolicyAssignment model.CommonMessageAndCode `json:"disbalePolicyAssignment"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.DisablePolicyAssignment, nil +} diff --git a/lib/management/policies_management_client_test.go b/lib/management/policies_management_client_test.go new file mode 100644 index 0000000..8183f93 --- /dev/null +++ b/lib/management/policies_management_client_test.go @@ -0,0 +1,152 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_CreatePolicy(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建策略==========") + ef := model.EnumPolicyEffectAllow + stateMents := &model.PolicyStatement{ + Resource: "book:222c", + Effect: &ef, + Actions: []string{"'booksc:read'"}, + } + req := &model.PolicyRequest{ + Code: "qqx", + Statements: []model.PolicyStatement{*stateMents}, + } + resp, err := client.CreatePolicy(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListPolicy(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建策略==========") + + resp, err := client.ListPolicy(1, 10) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DetailPolicy(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========策略详情==========") + + resp, err := client.DetailPolicy("qqx") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", *resp.Statements[0].Effect) +} + +func TestClient_UpdatePolicy(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========修改策略==========") + ef := model.EnumPolicyEffectAllow + stateMents := &model.PolicyStatement{ + Resource: "book:222cw", + Effect: &ef, + Actions: []string{"'booksc:read'"}, + } + req := &model.PolicyRequest{ + Code: "qqx", + Statements: []model.PolicyStatement{*stateMents}, + } + resp, err := client.UpdatePolicy(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DeletePolicy(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除策略==========") + + resp, err := client.DeletePolicy("qqx") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListAssignments(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========删除策略==========") + + resp, err := client.ListAssignments("tliewdutrn", 1, 10) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_AddAssignments(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========授权策略==========") + req := &model.PolicyAssignmentsRequest{ + Policies: []string{"tliewdutrn"}, + TargetType: model.EnumPolicyAssignmentTargetTypeUser, + TargetIdentifiers: []string{"616e905ebc18f0f106973a29"}, + } + resp, err := client.AddAssignments(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_RemoveAssignments(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========撤销策略==========") + req := &model.PolicyAssignmentsRequest{ + Policies: []string{"tliewdutrn"}, + TargetType: model.EnumPolicyAssignmentTargetTypeUser, + TargetIdentifiers: []string{"616e905ebc18f0f106973a29"}, + } + resp, err := client.RemoveAssignments(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_EnableAssignments(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========撤销策略==========") + req := &model.SwitchPolicyAssignmentsRequest{ + Policy: "tliewdutrn", + TargetType: model.EnumPolicyAssignmentTargetTypeUser, + TargetIdentifier: "616e905ebc18f0f106973a29", + } + resp, err := client.EnableAssignments(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_DisableAssignments(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========撤销策略==========") + req := &model.SwitchPolicyAssignmentsRequest{ + Policy: "tliewdutrn", + TargetType: model.EnumPolicyAssignmentTargetTypeUser, + TargetIdentifier: "616e905ebc18f0f106973a29", + } + resp, err := client.DisableAssignments(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/management/principal_authentication_management_client.go b/lib/management/principal_authentication_management_client.go new file mode 100644 index 0000000..e5c659a --- /dev/null +++ b/lib/management/principal_authentication_management_client.go @@ -0,0 +1,64 @@ +package management + +import ( + "errors" + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// PrincipalAuthDetail +// 获取主体认证详情 +func (c *Client) PrincipalAuthDetail(userId string) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + + url := fmt.Sprintf("%s/api/v2/users/%s/management/principal_authentication", c.Host, userId) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} + +// PrincipalAuthenticate +// 进行主体认证 +func (c *Client) PrincipalAuthenticate(userId string, req *model.PrincipalAuthenticateRequest) (*struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` +}, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + url := fmt.Sprintf("%s/api/v2/users/%s/management/principal_authentication", c.Host, userId) + b, err := c.SendHttpRestRequest(url, http.MethodPost, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data interface{} `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return resp, nil +} diff --git a/lib/management/principal_authentication_management_client_test.go b/lib/management/principal_authentication_management_client_test.go new file mode 100644 index 0000000..db00c34 --- /dev/null +++ b/lib/management/principal_authentication_management_client_test.go @@ -0,0 +1,34 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_PrincipalAuthDetail(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========主体认证详情==========") + + resp, err := client.PrincipalAuthDetail("6139c4d24e78a4d706b7545b") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} +func TestClient_PrincipalAuthenticate(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========主体认证详情==========") + req := &model.PrincipalAuthenticateRequest{ + Name: "xx", + Type: constant.P, + IdCard: "123123", + } + resp, err := client.PrincipalAuthenticate("6139c4d24e78a4d706b7545b", req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/management/role_management_client.go b/lib/management/role_management_client.go index e67eea3..c71620f 100644 --- a/lib/management/role_management_client.go +++ b/lib/management/role_management_client.go @@ -28,7 +28,10 @@ func (c *Client) GetRoleList(request model.GetRoleListRequest) (*model.Paginated // GetRoleUserList // 获取角色用户列表 -func (c *Client) GetRoleUserList(request model.GetRoleUserListRequest) (*model.PaginatedRoles, error) { +func (c *Client) GetRoleUserList(request model.GetRoleUserListRequest) (*struct { + TotalCount int64 `json:"totalCount"` + List []model.User `json:"list"` +}, error) { data, _ := json.Marshal(&request) variables := make(map[string]interface{}) json.Unmarshal(data, &variables) @@ -37,9 +40,20 @@ func (c *Client) GetRoleUserList(request model.GetRoleUserListRequest) (*model.P return nil, err } log.Println(string(b)) - var response model.GetRoleListResponse + var response = &struct { + Data struct { + Role struct { + Users struct { + TotalCount int64 `json:"totalCount"` + List []model.User `json:"list"` + } `json:"users"` + } `json:"role"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) - return &response.Data.Roles, nil + return &response.Data.Role.Users, nil } // CreateRole 创建角色 @@ -229,7 +243,7 @@ func (c *Client) ListRolePolicies(request model.ListPoliciesRequest) (*model.Lis variables := make(map[string]interface{}) json.Unmarshal(data, &variables) - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListPoliciesDocument, variables) if err != nil { return nil, err @@ -257,7 +271,7 @@ func (c *Client) AddRolePolicies(code string, policiesCode []string) (*model.Com variables := make(map[string]interface{}) variables["policies"] = policiesCode - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE variables["targetIdentifiers"] = []string{code} b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.AddPoliciesDocument, variables) @@ -287,7 +301,7 @@ func (c *Client) RemoveRolePolicies(code string, policiesCode []string) (*model. variables := make(map[string]interface{}) variables["policies"] = policiesCode - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE variables["targetIdentifiers"] = []string{code} b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemovePoliciesDocument, variables) @@ -312,7 +326,7 @@ func (c *Client) RemoveRolePolicies(code string, policiesCode []string) (*model. // ListRoleAuthorizedResources // 获取角色被授权的所有资源 -func (c *Client) ListRoleAuthorizedResources(code, namespace string, resourceType constant.ResourceTypeEnum) (*model.AuthorizedResources, error) { +func (c *Client) ListRoleAuthorizedResources(code, namespace string, resourceType model.EnumResourceType) (*model.AuthorizedResources, error) { variables := make(map[string]interface{}) @@ -348,7 +362,7 @@ func (c *Client) GetRoleUdfValue(id string) (*[]model.UserDefinedData, error) { variables := make(map[string]interface{}) - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE variables["targetId"] = id b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.GetRoleUdfValueDocument, variables) @@ -383,7 +397,7 @@ func (c *Client) BatchGetRoleUdfValue(ids []string) (map[string][]model.UserDefi variables := make(map[string]interface{}) - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE variables["targetIds"] = ids b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.BatchGetRoleUdfValueDocument, variables) @@ -415,7 +429,7 @@ func (c *Client) SetRoleUdfValue(id string, udv *model.KeyValuePair) (*[]model.U variables := make(map[string]interface{}) - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE variables["targetId"] = id variables["udvList"] = []model.KeyValuePair{*udv} @@ -443,7 +457,7 @@ func (c *Client) SetRoleUdfValue(id string, udv *model.KeyValuePair) (*[]model.U func (c *Client) BatchSetRoleUdfValue(request *[]model.SetUdfValueBatchInput) (*model.CommonMessageAndCode, error) { variables := make(map[string]interface{}) - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE variables["input"] = request b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.BatchSetUdfValueDocument, variables) if err != nil { @@ -469,7 +483,7 @@ func (c *Client) BatchSetRoleUdfValue(request *[]model.SetUdfValueBatchInput) (* func (c *Client) RemoveRoleUdfValue(id, key string) (*[]model.UserDefinedData, error) { variables := make(map[string]interface{}) - variables["targetType"] = "ROLE" + variables["targetType"] = constant.ROLE variables["targetId"] = id variables["key"] = key diff --git a/lib/management/role_management_client_test.go b/lib/management/role_management_client_test.go index 3eb716f..3bd82d6 100644 --- a/lib/management/role_management_client_test.go +++ b/lib/management/role_management_client_test.go @@ -2,7 +2,6 @@ package management import ( "fmt" - "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/enum" "github.com/Authing/authing-go-sdk/lib/model" "log" @@ -24,11 +23,12 @@ func TestClient_GetRoleList(t *testing.T) { func TestClient_GetRoleUserList(t *testing.T) { client := NewClient(userPoolId, appSecret) log.Println("==========获取角色列表==========") + defaultNamespace := "default" req := model.GetRoleUserListRequest{ Page: 1, Limit: 10, Code: "develop", - Namespace: "default", + Namespace: &defaultNamespace, } resp, _ := client.GetRoleUserList(req) log.Printf("%+v\n", resp) @@ -38,9 +38,7 @@ func TestClient_CreateRole(t *testing.T) { client := NewClient(userPoolId, appSecret) log.Println("==========创建角色==========") req := model.CreateRoleRequest{ - Code: "develop123456", - Namespace: "default", - ParentCode: "develop12345", + Code: "develop123456", } resp, err := client.CreateRole(req) @@ -51,8 +49,7 @@ func TestClient_DeleteRole(t *testing.T) { client := NewClient(userPoolId, appSecret) log.Println("==========删除角色==========") req := model.DeleteRoleRequest{ - Code: "develop123456", - Namespace: "default", + Code: "develop123456", } resp, err := client.DeleteRole(req) if err != nil { @@ -66,8 +63,7 @@ func TestClient_DeleteRoles(t *testing.T) { log.Println("==========批量删除角色==========") req := model.BatchDeleteRoleRequest{ - CodeList: []string{"develop123456", "develop1234562"}, - Namespace: "default", + CodeList: []string{"develop123456", "develop1234562"}, } resp, err := client.BatchDeleteRole(req) if err != nil { @@ -81,8 +77,7 @@ func TestClient_UpdateRole(t *testing.T) { log.Println("==========更新角色==========") req := model.CreateRoleRequest{ - Code: "ttCode", - Namespace: "default", + Code: "ttCode", } resp, err := client.CreateRole(req) if err != nil { @@ -91,8 +86,7 @@ func TestClient_UpdateRole(t *testing.T) { log.Printf("%+v\n", resp) updateRequest := model.UpdateRoleRequest{ - Code: "ttCode", - NewCode: "NewCode", + Code: "ttCode", } resp, err = client.UpdateRole(updateRequest) log.Printf("%+v\n", resp) @@ -103,8 +97,7 @@ func TestClient_RoleDetail(t *testing.T) { log.Println("==========角色详情==========") req := model.RoleDetailRequest{ - Code: "NewCode", - Namespace: "default", + Code: "NewCode", } resp, err := client.RoleDetail(req) if err != nil { @@ -120,7 +113,6 @@ func TestClient_AssignRole(t *testing.T) { req := model.AssignAndRevokeRoleRequest{ RoleCodes: []string{"NewCode"}, UserIds: []string{"615551a3dcdd486139a917b1"}, - Namespace: "default", } resp, err := client.AssignRole(req) if err != nil { @@ -136,7 +128,6 @@ func TestClient_RevokeRole(t *testing.T) { req := model.AssignAndRevokeRoleRequest{ RoleCodes: []string{"NewCode"}, UserIds: []string{"615551a3dcdd486139a917b1"}, - Namespace: "default", } resp, err := client.RevokeRole(req) if err != nil { @@ -184,7 +175,7 @@ func TestClient_RemoveRolePolicies(t *testing.T) { func TestClient_ListRoleAuthorizedResources(t *testing.T) { client := NewClient(userPoolId, appSecret) log.Println("==========查询角色被授权资源==========") - resp, err := client.ListRoleAuthorizedResources("NewCode", "default", constant.API) + resp, err := client.ListRoleAuthorizedResources("NewCode", "default", model.EnumResourceTypeAPI) if err != nil { fmt.Println(err) } diff --git a/lib/management/udf_management_client.go b/lib/management/udf_management_client.go new file mode 100644 index 0000000..bc21cd4 --- /dev/null +++ b/lib/management/udf_management_client.go @@ -0,0 +1,138 @@ +package management + +import ( + "errors" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// ListUdf +// 获取自定义字段定义 +func (c *Client) ListUdf(targetType model.EnumUDFTargetType) (*[]model.UserDefinedField, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListUdfDocument, + map[string]interface{}{"targetType": targetType}) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Udf []model.UserDefinedField `json:"udf"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Udf, nil +} + +// SetUdf +// 设置自定义字段元数据 +func (c *Client) SetUdf(req *model.SetUdfInput) (*model.UserDefinedField, error) { + data, _ := jsoniter.Marshal(req) + vars := make(map[string]interface{}) + jsoniter.Unmarshal(data, &vars) + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.SetUdfDocument, vars) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SetUdf model.UserDefinedField `json:"setUdf"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SetUdf, nil +} + +// RemoveUdf +// 删除自定义字段 +func (c *Client) RemoveUdf(targetType model.EnumUDFTargetType, key string) (*model.CommonMessageAndCode, error) { + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemoveUdfDocument, map[string]interface{}{ + "targetType": targetType, + "key": key, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + RemoveUdf model.CommonMessageAndCode `json:"removeUdf"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.RemoveUdf, nil +} + +// ListUdfValue +// 获取某一实体的自定义字段数据列表 +func (c *Client) ListUdfValue(targetType model.EnumUDFTargetType, targetId string) (*[]model.UserDefinedData, error) { + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UdvDocument, map[string]interface{}{ + "targetType": targetType, + "targetId": targetId, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + Udv []model.UserDefinedData `json:"udv"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.Udv, nil +} + +// SetUdvBatch +// 批量添加自定义数据 +func (c *Client) SetUdvBatch(id string, targetType model.EnumUDFTargetType, udv *[]model.KeyValuePair) (*[]model.UserDefinedData, error) { + variables := make(map[string]interface{}) + + variables["targetType"] = targetType + variables["targetId"] = id + variables["udvList"] = udv + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.SetRoleUdfValueDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SetUdvBatch []model.UserDefinedData `json:"setUdvBatch"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SetUdvBatch, nil +} diff --git a/lib/management/udf_management_client_test.go b/lib/management/udf_management_client_test.go new file mode 100644 index 0000000..b695fd7 --- /dev/null +++ b/lib/management/udf_management_client_test.go @@ -0,0 +1,69 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_ListUdf(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========自定义字段列表==========") + resp, err := client.ListUdf(model.EnumUDFTargetTypeUSER) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_SetUdf(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========自定义字段列表==========") + req := &model.SetUdfInput{ + TargetType: model.EnumUDFTargetTypeUSER, + DataType: model.EnumUDFDataTypeSTRING, + Key: "goSDK", + Label: "goSDK", + } + resp, err := client.SetUdf(req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_RemoveUdf(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========自定义字段列表==========") + + resp, err := client.RemoveUdf(model.EnumUDFTargetTypeUSER, "goSDK") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_ListUdfValue(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========某对象自定义字段列表==========") + + resp, err := client.ListUdfValue(model.EnumUDFTargetTypeUSER, "616d41b7410a33da0cb70e65") + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_SetUdvBatch(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========某对象自定义字段列表==========") + + resp, err := client.SetUdvBatch("616d41b7410a33da0cb70e65", model.EnumUDFTargetTypeUSER, &[]model.KeyValuePair{ + {Key: "goSDK", Value: "goSDK"}, + }) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/management/user_management_client.go b/lib/management/user_management_client.go index 4701003..71547a2 100644 --- a/lib/management/user_management_client.go +++ b/lib/management/user_management_client.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/model" + "github.com/Authing/authing-go-sdk/lib/util" "github.com/bitly/go-simplejson" jsoniter "github.com/json-iterator/go" "log" @@ -82,68 +83,66 @@ func (c *Client) CheckUserExists(request model.CheckUserExistsRequest) (bool, er // CreateUser // 创建用户 -//func (c *Client) CreateUser(request model.CreateUserRequest) (*model.User, error) { -// if request.UserInfo.Password != nil { -// pwd := util.RsaEncrypt(*request.UserInfo.Password) -// request.UserInfo.Password = &pwd -// } -// fillDefaultVal(&request.UserInfo) -// data, _ := json.Marshal(&request) -// variables := make(map[string]interface{}) -// json.Unmarshal(data, &variables) -// -// query := constant.CreateUserDocument -// if request.CustomData != nil { -// query = constant.CreateUserWithCustomDataDocument -// customData,_ := json.Marshal(&request.CustomData) -// variables["params"] = customData -// } -// b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, query , variables) -// if err != nil { -// return nil, err -// } -// log.Println(string(b)) -// var response = &struct { -// Data struct{ -// CreateUser model.User `json:"createUser"` -// } `json:"data"` -// Errors []model.GqlCommonErrors `json:"errors"` -// }{} -// jsoniter.Unmarshal(b, &response) -// if len(response.Errors) >0 { -// return nil, errors.New(response.Errors[0].Message.Message) -// } -// return &response.Data.CreateUser,nil -//} +func (c *Client) CreateUser(request model.CreateUserRequest) (*model.User, error) { + if request.UserInfo.Password != nil { + pwd := util.RsaEncrypt(*request.UserInfo.Password) + request.UserInfo.Password = &pwd + } + data, _ := json.Marshal(&request) + variables := make(map[string]interface{}) + json.Unmarshal(data, &variables) + + query := constant.CreateUserDocument + if request.CustomData != nil { + query = constant.CreateUserWithCustomDataDocument + customData, _ := json.Marshal(&request.CustomData) + variables["params"] = customData + } + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, query, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + CreateUser model.User `json:"createUser"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.CreateUser, nil +} //UpdateUser //修改用户资料 -//func (c *Client) UpdateUser(id string ,updateInfo model.UpdateUserInput) (*model.User, error) { -// if updateInfo.Password != nil { -// pwd:=util.RsaEncrypt(*updateInfo.Password) -// updateInfo.Password = &pwd -// } -// fillUpdateDefaultVal(&updateInfo) -// variables := make(map[string]interface{}) -// variables["id"] = id -// variables["input"] = updateInfo -// b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdateUserDocument, variables) -// if err != nil { -// return nil, err -// } -// log.Println(string(b)) -// var response = &struct { -// Data struct{ -// UpdateUser model.User `json:"updateUser"` -// } `json:"data"` -// Errors []model.GqlCommonErrors `json:"errors"` -// }{} -// jsoniter.Unmarshal(b, &response) -// if len(response.Errors) >0 { -// return nil, errors.New(response.Errors[0].Message.Message) -// } -// return &response.Data.UpdateUser,nil -//} +func (c *Client) UpdateUser(id string, updateInfo model.UpdateUserInput) (*model.User, error) { + if updateInfo.Password != nil { + pwd := util.RsaEncrypt(*updateInfo.Password) + updateInfo.Password = &pwd + } + variables := make(map[string]interface{}) + variables["id"] = id + variables["input"] = updateInfo + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdateUserDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdateUser model.User `json:"updateUser"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.UpdateUser, nil +} //DeleteUser //删除用户 @@ -519,7 +518,7 @@ func (c *Client) ListUserOrg(userId string) (*[][]model.OrgModel, error) { func (c *Client) GetUserUdfValue(userId string) (*[]model.UserDefinedData, error) { variables := make(map[string]interface{}) - variables["targetType"] = "USER" + variables["targetType"] = constant.USER variables["targetId"] = userId b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.GetRoleUdfValueDocument, variables) @@ -578,7 +577,7 @@ func (c *Client) BatchGetUserUdfValue(ids []string) (map[string][]model.UserDefi variables := make(map[string]interface{}) - variables["targetType"] = "USER" + variables["targetType"] = constant.USER variables["targetIds"] = ids b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.BatchGetRoleUdfValueDocument, variables) @@ -610,7 +609,7 @@ func (c *Client) SetUserUdfValue(id string, udv *model.KeyValuePair) (*[]model.U variables := make(map[string]interface{}) - variables["targetType"] = "USER" + variables["targetType"] = constant.USER variables["targetId"] = id variables["key"] = udv.Key variables["value"] = udv.Value @@ -639,7 +638,7 @@ func (c *Client) SetUserUdfValue(id string, udv *model.KeyValuePair) (*[]model.U func (c *Client) BatchSetUserUdfValue(request *[]model.SetUdfValueBatchInput) (*model.CommonMessageAndCode, error) { variables := make(map[string]interface{}) - variables["targetType"] = "USER" + variables["targetType"] = constant.USER variables["input"] = request b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.BatchSetUdfValueDocument, variables) if err != nil { @@ -665,7 +664,7 @@ func (c *Client) BatchSetUserUdfValue(request *[]model.SetUdfValueBatchInput) (* func (c *Client) RemoveUserUdfValue(id, key string) (*[]model.UserDefinedData, error) { variables := make(map[string]interface{}) - variables["targetType"] = "USER" + variables["targetType"] = constant.USER variables["targetId"] = id variables["key"] = key @@ -703,7 +702,7 @@ func (c *Client) ListUserPolicies(request model.ListPoliciesOnIdRequest) (*model variables := make(map[string]interface{}) json.Unmarshal(data, &variables) - variables["targetType"] = "USER" + variables["targetType"] = constant.USER b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.ListPoliciesDocument, variables) if err != nil { return nil, err @@ -731,7 +730,7 @@ func (c *Client) AddUserPolicies(userId string, policiesCode []string) (*model.C variables := make(map[string]interface{}) variables["policies"] = policiesCode - variables["targetType"] = "USER" + variables["targetType"] = constant.USER variables["targetIdentifiers"] = []string{userId} b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.AddPoliciesDocument, variables) @@ -761,7 +760,7 @@ func (c *Client) RemoveUserPolicies(userId string, policiesCode []string) (*mode variables := make(map[string]interface{}) variables["policies"] = policiesCode - variables["targetType"] = "USER" + variables["targetType"] = constant.USER variables["targetIdentifiers"] = []string{userId} b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemovePoliciesDocument, variables) @@ -808,67 +807,24 @@ func (c *Client) UserHasRole(userId, roleCode, namespace string) (bool, error) { return hasRole, nil } -// KickUser -// 强制一批用户下线 -//func (c *Client) KickUser(userIds []string) (*model.CommonMessageAndCode, error) { -// -// url := fmt.Sprintf("%v/api/v2/users/kick",c.Host) -// json := make(map[string]interface{}) -// json["userIds"] = userIds -// b, err := c.SendHttpRequest(url, http.MethodPost, "", json) -// if err != nil { -// return nil, err -// } -// log.Println(string(b)) -// var response model.CommonMessageAndCode -// jsoniter.Unmarshal(b,&response) -// return &response,nil -//} +//KickUser +//强制一批用户下线 +func (c *Client) KickUser(userIds []string) (*model.CommonMessageAndCode, error) { -func fillUpdateDefaultVal(info *model.UpdateUserInput) { - defaultGender := "U" - isVerified := false - var zero int64 = 0 - if info.Gender == nil { - info.Gender = &defaultGender - } - if info.EmailVerified == nil { - info.EmailVerified = &isVerified - } - if info.PhoneVerified == nil { - info.PhoneVerified = &isVerified - } - if info.Blocked == nil { - info.Blocked = &isVerified - } - if info.LoginsCount == nil { - info.LoginsCount = &zero - } -} - -func fillDefaultVal(info *model.CreateUserInput) { - defaultGender := "U" - isVerified := false - var zero int64 = 0 - if info.Gender == nil { - info.Gender = &defaultGender - } - if info.EmailVerified == nil { - info.EmailVerified = &isVerified - } - if info.PhoneVerified == nil { - info.PhoneVerified = &isVerified - } - if info.Blocked == nil { - info.Blocked = &isVerified - } - if info.LoginsCount == nil { - info.LoginsCount = &zero + url := fmt.Sprintf("%v/api/v2/users/kick", c.Host) + json := make(map[string]interface{}) + json["userIds"] = userIds + b, err := c.SendHttpRequest(url, http.MethodPost, "", json) + if err != nil { + return nil, err } - + log.Println(string(b)) + var response model.CommonMessageAndCode + jsoniter.Unmarshal(b, &response) + return &response, nil } -func (c *Client) ListAuthorizedResources(request model.ListUserAuthorizedResourcesRequest) (*model.User, error) { +func (c *Client) ListAuthorizedResources(request model.ListAuthorizedResourcesByIdRequest) (*model.User, error) { data, _ := json.Marshal(&request) variables := make(map[string]interface{}) json.Unmarshal(data, &variables) @@ -921,3 +877,77 @@ func (c *Client) GetUserGroupList(userId string) (*model.PaginatedGroups, error) } return &result, nil } + +//CheckLoginStatus +//检查用户登录状态 +func (c *Client) CheckLoginStatus(userId string, appId, deviceId *string) (*model.CommonMessageAndCode, error) { + variables := make(map[string]interface{}, 0) + if appId != nil { + variables["appId"] = appId + } + if deviceId != nil { + variables["deviceId"] = deviceId + } + variables["userId"] = userId + + url := fmt.Sprintf("%v/api/v2/users/login-status", c.Host) + b, err := c.SendHttpRequest(url, constant.HttpMethodGet, constant.StringEmpty, variables) + log.Println(string(b)) + result := model.CommonMessageAndCode{} + + err = json.Unmarshal(b, &result) + if err != nil { + return nil, err + } + return &result, err +} + +//LogOut +//用户退出 +func (c *Client) LogOut(userId string, appId *string) (*model.CommonMessageAndCode, error) { + variables := make(map[string]interface{}, 0) + if appId != nil { + variables["appId"] = appId + } + + variables["userId"] = userId + + url := fmt.Sprintf("%v/logout", c.Host) + b, err := c.SendHttpRequest(url, http.MethodGet, constant.StringEmpty, variables) + log.Println(string(b)) + result := model.CommonMessageAndCode{} + + err = json.Unmarshal(b, &result) + if err != nil { + return nil, err + } + return &result, err +} + +// SendFirstLoginVerifyEmail +// 发送首次登录验证邮件 +func (c *Client) SendFirstLoginVerifyEmail(userId, appId string) (*model.CommonMessageAndCode, error) { + + variables := make(map[string]interface{}) + variables["appId"] = appId + variables["userId"] = userId + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.SendFirstLoginVerifyEmailDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + SendFirstLoginVerifyEmail model.CommonMessageAndCode `json:"sendFirstLoginVerifyEmail"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.SendFirstLoginVerifyEmail, nil +} diff --git a/lib/management/user_management_client_test.go b/lib/management/user_management_client_test.go index 1d700c5..0941a37 100644 --- a/lib/management/user_management_client_test.go +++ b/lib/management/user_management_client_test.go @@ -1,7 +1,6 @@ package management import ( - "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/enum" "github.com/Authing/authing-go-sdk/lib/model" "log" @@ -50,69 +49,69 @@ func TestClient_CheckUserExists(t *testing.T) { log.Println(resp) } -//func TestClient_CreateUser(t *testing.T) { -// client := NewClient(userPoolId, appSecret) -// log.Println("==========创建用户==========") -// //email := "t041gyqw0b@gmail.com" -// phone := "15761403457222" -// username := "xx" -// pwd:="123456789" -// var userInfo = &model.CreateUserInput{ -// Username: &username, -// Phone: &phone, -// Password: &pwd, -// } -// req := model.CreateUserRequest{ -// UserInfo: *userInfo, -// } -// resp, err := client.CreateUser(req) -// log.Println(resp) -// log.Println(err) -//} - -//func TestClient_CreateUserWithCustom(t *testing.T) { -// client := NewClient(userPoolId, appSecret) -// log.Println("==========创建用户包含自定义数据==========") -// //email := "t041gyqw0b@gmail.com" -// phone := "15761403457222122" -// username := "xxqq12" -// pwd:="123456789" -// var userInfo = &model.CreateUserInput{ -// Username: &username, -// Phone: &phone, -// Password: &pwd, -// } -// req := model.CreateUserRequest{ -// UserInfo: *userInfo, -// CustomData: []model.KeyValuePair{ -// model.KeyValuePair{ -// Key: "objhvfwdbi", -// Value: "qq", -// }, -// }, -// } -// resp, err := client.CreateUser(req) -// log.Println(resp) -// log.Println(err) -//} - -//func TestClient_UpdateUser(t *testing.T) { -// client := NewClient(userPoolId, appSecret) -// log.Println("==========更新用户==========") -// //email := "t041gyqw0b@gmail.com" -// phone := "15761403457222122" -// username := "xxqq123" -// //pwd:="123456789" -// var userInfo = &model.UpdateUserInput{ -// Username: &username, -// Phone: &phone, -// //Password: &pwd, -// } -// -// resp, err := client.UpdateUser("616d4333b809f9f4768db847",*userInfo) -// log.Println(resp) -// log.Println(err) -//} +func TestClient_CreateUser(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建用户==========") + //email := "t041gyqw0b@gmail.com" + phone := "15761403457222" + username := "xx" + pwd := "123456789" + var userInfo = &model.CreateUserInput{ + Username: &username, + Phone: &phone, + Password: &pwd, + } + req := model.CreateUserRequest{ + UserInfo: *userInfo, + } + resp, err := client.CreateUser(req) + log.Println(resp) + log.Println(err) +} + +func TestClient_CreateUserWithCustom(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========创建用户包含自定义数据==========") + //email := "t041gyqw0b@gmail.com" + phone := "15761403457222122" + username := "xxqq12" + pwd := "123456789" + var userInfo = &model.CreateUserInput{ + Username: &username, + Phone: &phone, + Password: &pwd, + } + req := model.CreateUserRequest{ + UserInfo: *userInfo, + CustomData: []model.KeyValuePair{ + model.KeyValuePair{ + Key: "objhvfwdbi", + Value: "qq", + }, + }, + } + resp, err := client.CreateUser(req) + log.Println(resp) + log.Println(err) +} + +func TestClient_UpdateUser(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========更新用户==========") + //email := "t041gyqw0b@gmail.com" + phone := "15761403457222122" + username := "xxqq123" + //pwd:="123456789" + var userInfo = &model.UpdateUserInput{ + Username: &username, + Phone: &phone, + //Password: &pwd, + } + + resp, err := client.UpdateUser("616d4333b809f9f4768db847", *userInfo) + log.Println(resp) + log.Println(err) +} func TestClient_DeleteUser(t *testing.T) { client := NewClient(userPoolId, appSecret) @@ -156,9 +155,9 @@ func TestClient_ListArchivedUsers(t *testing.T) { func TestClient_FindUser(t *testing.T) { client := NewClient(userPoolId, appSecret) log.Println("==========查找用户==========") - + userName := "xxqq" resp, err := client.FindUser(&model.FindUserRequest{ - Username: "xxqq", + Username: &userName, }) log.Println(resp) log.Println(err) @@ -297,7 +296,7 @@ func TestClient_ListUserAuthorizedResources(t *testing.T) { req := &model.ListUserAuthResourceRequest{ Id: "616d41b7410a33da0cb70e65", Namespace: "default", - ResourceType: constant.API, + ResourceType: model.EnumResourceTypeAPI, } resp, err := client.ListUserAuthorizedResources(*req) log.Println(resp) @@ -362,21 +361,21 @@ func TestClient_UserHasRole(t *testing.T) { log.Println(err) } -//func TestClient_KickUser(t *testing.T) { -// client := NewClient(userPoolId, appSecret) -// log.Println("==========强制用户下线==========") -// -// resp, err := client.KickUser([]string{"5a597f35085a2000144a10ed"}) -// log.Println(resp) -// log.Println(err) -//} +func TestClient_KickUser(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========强制用户下线==========") + + resp, err := client.KickUser([]string{"5a597f35085a2000144a10ed"}) + log.Println(resp) + log.Println(err) +} func TestClient_ListAuthorizedResources(t *testing.T) { client := NewClient(userPoolId, appSecret) log.Println("==========获取用户被授权的所有资源列表==========") - req := model.ListUserAuthorizedResourcesRequest{ - UserId: "611b2ff477d701441c25e29e", + req := model.ListAuthorizedResourcesByIdRequest{ + Id: "611b2ff477d701441c25e29e", Namespace: "6123528118b7794b2420b311", ResourceType: nil, } @@ -402,3 +401,50 @@ func TestClient_GetUserGroupList(t *testing.T) { resp, _ := client.GetUserGroupList("611a149db64310ca4764ab15") log.Printf("%+v\n", resp) } + +func TestClient_CheckLoginStatus(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========检查用户登录状态==========") + + resp, err := client.CheckLoginStatus("5a597f35085a2000144a10ed", nil, nil) + log.Println(resp) + log.Println(err) +} + +func TestClient_LogOut(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========用户退出==========") + + resp, err := client.LogOut("5a597f35085a2000144a10ed", nil) + log.Println(resp) + log.Println(err) +} + +func TestClient_SendFirstLoginVerifyEmail(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========发送用户首次登录邮件==========") + + resp, err := client.SendFirstLoginVerifyEmail("616d4333b809f9f4768db847", "6168f95e81d5e20f9cb72f22") + log.Println(resp) + log.Println(err) +} + +func TestClient_CheckLoginStatus2(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========检验登录状态根据Token==========") + tx, e := GetAccessToken(client) + log.Println(tx, e) + resp, err := client.CheckLoginStatusByToken(tx) + log.Println(resp) + log.Println(err) +} + +func TestClient_IsPasswordValid(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========检验登录状态根据Token==========") + tx, e := GetAccessToken(client) + log.Println(tx, e) + resp, err := client.IsPasswordValid("tx") + log.Println(resp) + log.Println(err) +} diff --git a/lib/management/user_pool_management_client.go b/lib/management/user_pool_management_client.go new file mode 100644 index 0000000..054fa3b --- /dev/null +++ b/lib/management/user_pool_management_client.go @@ -0,0 +1,123 @@ +package management + +import ( + "errors" + "fmt" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +// UserPoolDetail +// 查询用户池配置 +func (c *Client) UserPoolDetail() (*model.UserPool, error) { + + url := fmt.Sprintf("%s/api/v2/userpools/detail", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.UserPool `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// UpdateUserPool +// 更新用户池配置 +func (c *Client) UpdateUserPool(request model.UpdateUserpoolInput) (*model.UserPool, error) { + variables := make(map[string]interface{}) + variables["input"] = request + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.UpdateUserPoolDocument, variables) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + UpdateUserPool model.UserPool `json:"updateUserpool"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + + jsoniter.Unmarshal(b, &response) + + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.UpdateUserPool, nil + +} + +// ListUserPoolEnv +// 获取环境变量列表 +func (c *Client) ListUserPoolEnv() (*[]model.UserPoolEnv, error) { + + url := fmt.Sprintf("%s/api/v2/env", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodGet, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data []model.UserPoolEnv `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} + +// RemoveUserPoolEnv +// 移除环境变量列表 +func (c *Client) RemoveUserPoolEnv(key string) (*model.CommonMessageAndCode, error) { + + url := fmt.Sprintf("%s/api/v2/env/%s", c.Host, key) + b, err := c.SendHttpRestRequest(url, http.MethodDelete, nil) + if err != nil { + return nil, err + } + log.Println(string(b)) + var resp model.CommonMessageAndCode + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp, nil +} + +// AddUserPoolEnv +// 新增环境变量列表 +func (c *Client) AddUserPoolEnv(key, value string) (*model.UserPoolEnv, error) { + + url := fmt.Sprintf("%s/api/v2/env", c.Host) + b, err := c.SendHttpRestRequest(url, http.MethodPost, map[string]interface{}{ + "key": key, "value": value, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + resp := &struct { + Message string `json:"message"` + Code int64 `json:"code"` + Data model.UserPoolEnv `json:"data"` + }{} + jsoniter.Unmarshal(b, &resp) + if resp.Code != 200 { + return nil, errors.New(resp.Message) + } + return &resp.Data, nil +} diff --git a/lib/management/user_pool_management_client_test.go b/lib/management/user_pool_management_client_test.go new file mode 100644 index 0000000..6c8c3a9 --- /dev/null +++ b/lib/management/user_pool_management_client_test.go @@ -0,0 +1,49 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_UserPoolDetail(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========用户池详情==========") + resp, err := client.UserPoolDetail() + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_UpdateUserPool(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========修改用户池==========") + userPoolName := "otherSdk9989995" + req := &model.UpdateUserpoolInput{ + Name: &userPoolName, + Domain: &userPoolName, + } + resp, err := client.UpdateUserPool(*req) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_UserPoolEnv(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========用户池环境变量==========") + + resp, err := client.ListUserPoolEnv() + if err != nil { + fmt.Println(err) + } + resp1, err1 := client.AddUserPoolEnv("qnm", "qnm") + fmt.Println(resp1, err1) + resp2, err2 := client.RemoveUserPoolEnv("qnm") + fmt.Println(resp2, err2) + resp, err = client.ListUserPoolEnv() + log.Printf("%+v\n", resp) +} diff --git a/lib/management/while_list_manangement_client.go b/lib/management/while_list_manangement_client.go new file mode 100644 index 0000000..8feb224 --- /dev/null +++ b/lib/management/while_list_manangement_client.go @@ -0,0 +1,146 @@ +package management + +import ( + "errors" + "github.com/Authing/authing-go-sdk/lib/constant" + "github.com/Authing/authing-go-sdk/lib/model" + jsoniter "github.com/json-iterator/go" + "log" + "net/http" +) + +//GetWhileList +//获取白名单记录 +func (c *Client) GetWhileList(whileListType model.EnumWhitelistType) (*[]model.WhiteList, error) { + + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.WhileListDocument, map[string]interface{}{ + "type": whileListType, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + WhileList []model.WhiteList `json:"whitelist"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.WhileList, nil +} + +//AddWhileList +//添加白名单记录 +func (c *Client) AddWhileList(whileListType model.EnumWhitelistType, ids []string) (*[]model.WhiteList, error) { + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.AddWhileListDocument, map[string]interface{}{ + "type": whileListType, + "list": ids, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + WhileList []model.WhiteList `json:"addWhitelist"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.WhileList, nil +} + +//RemoveWhileList +//移除白名单记录 +func (c *Client) RemoveWhileList(whileListType model.EnumWhitelistType, ids []string) (*[]model.WhiteList, error) { + b, err := c.SendHttpRequest(c.Host+constant.CoreAuthingGraphqlPath, http.MethodPost, constant.RemoveWhileListDocument, map[string]interface{}{ + "type": whileListType, + "list": ids, + }) + if err != nil { + return nil, err + } + log.Println(string(b)) + var response = &struct { + Data struct { + WhileList []model.WhiteList `json:"removeWhitelist"` + } `json:"data"` + Errors []model.GqlCommonErrors `json:"errors"` + }{} + jsoniter.Unmarshal(b, &response) + if len(response.Errors) > 0 { + return nil, errors.New(response.Errors[0].Message.Message) + } + return &response.Data.WhileList, nil +} + +//EnableWhileList +//开启白名单 +func (c *Client) EnableWhileList(whileListType model.EnumWhitelistType) (*model.UserPool, error) { + var req model.UpdateUserpoolInput + enable := true + if whileListType == model.EnumWhitelistTypeUsername { + req = model.UpdateUserpoolInput{ + Whitelist: &model.RegisterWhiteListConfigInput{ + UsernameEnabled: &enable, + }, + } + } + + if whileListType == model.EnumWhitelistTypeEmail { + req = model.UpdateUserpoolInput{ + Whitelist: &model.RegisterWhiteListConfigInput{ + EmailEnabled: &enable, + }, + } + } + + if whileListType == model.EnumWhitelistTypePhone { + req = model.UpdateUserpoolInput{ + Whitelist: &model.RegisterWhiteListConfigInput{ + PhoneEnabled: &enable, + }, + } + } + rep, err := c.UpdateUserPool(req) + return rep, err +} + +//DisableWhileList +//关闭白名单 +func (c *Client) DisableWhileList(whileListType model.EnumWhitelistType) (*model.UserPool, error) { + var req model.UpdateUserpoolInput + flag := false + if whileListType == model.EnumWhitelistTypeUsername { + req = model.UpdateUserpoolInput{ + Whitelist: &model.RegisterWhiteListConfigInput{ + UsernameEnabled: &flag, + }, + } + } + + if whileListType == model.EnumWhitelistTypeEmail { + req = model.UpdateUserpoolInput{ + Whitelist: &model.RegisterWhiteListConfigInput{ + EmailEnabled: &flag, + }, + } + } + + if whileListType == model.EnumWhitelistTypePhone { + req = model.UpdateUserpoolInput{ + Whitelist: &model.RegisterWhiteListConfigInput{ + PhoneEnabled: &flag, + }, + } + } + rep, err := c.UpdateUserPool(req) + return rep, err +} diff --git a/lib/management/while_list_manangement_client_test.go b/lib/management/while_list_manangement_client_test.go new file mode 100644 index 0000000..3fe86bc --- /dev/null +++ b/lib/management/while_list_manangement_client_test.go @@ -0,0 +1,52 @@ +package management + +import ( + "fmt" + "github.com/Authing/authing-go-sdk/lib/model" + "log" + "testing" +) + +func TestClient_GetWhileList(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取白名单==========") + + resp, err := client.GetWhileList(model.EnumWhitelistTypeUsername) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_AddWhileList(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========获取白名单==========") + + resp, err := client.AddWhileList(model.EnumWhitelistTypeUsername, []string{"qqxccx", "qweqwe"}) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_RemoveWhileList(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========移除白名单==========") + + resp, err := client.RemoveWhileList(model.EnumWhitelistTypeUsername, []string{"qqxccx"}) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} + +func TestClient_EnableWhileList(t *testing.T) { + client := NewClient(userPoolId, appSecret) + log.Println("==========移除白名单==========") + + resp, err := client.EnableWhileList(model.EnumWhitelistTypeUsername) + if err != nil { + fmt.Println(err) + } + log.Printf("%+v\n", resp) +} diff --git a/lib/model/application_model.go b/lib/model/application_model.go new file mode 100644 index 0000000..d39163d --- /dev/null +++ b/lib/model/application_model.go @@ -0,0 +1,213 @@ +package model + +import "time" + +type Application struct { + QrcodeScanning struct { + Redirect bool `json:"redirect"` + Interval int `json:"interval"` + } `json:"qrcodeScanning"` + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserPoolId string `json:"userPoolId"` + Protocol string `json:"protocol"` + IsOfficial bool `json:"isOfficial"` + IsDeleted bool `json:"isDeleted"` + IsDefault bool `json:"isDefault"` + IsDemo bool `json:"isDemo"` + Name string `json:"name"` + Description string `json:"description"` + Secret string `json:"secret"` + Identifier string `json:"identifier"` + Jwks struct { + Keys []struct { + E string `json:"e"` + N string `json:"n"` + D string `json:"d"` + P string `json:"p"` + Q string `json:"q"` + Dp string `json:"dp"` + Dq string `json:"dq"` + Qi string `json:"qi"` + Kty string `json:"kty"` + Kid string `json:"kid"` + Alg string `json:"alg"` + Use string `json:"use"` + } `json:"keys"` + } `json:"jwks"` + SsoPageCustomizationSettings interface{} `json:"ssoPageCustomizationSettings"` + Logo string `json:"logo"` + RedirectUris []string `json:"redirectUris"` + LogoutRedirectUris []interface{} `json:"logoutRedirectUris"` + OidcProviderEnabled bool `json:"oidcProviderEnabled"` + OauthProviderEnabled bool `json:"oauthProviderEnabled"` + SamlProviderEnabled bool `json:"samlProviderEnabled"` + CasProviderEnabled bool `json:"casProviderEnabled"` + RegisterDisabled bool `json:"registerDisabled"` + LoginTabs []string `json:"loginTabs"` + PasswordTabConfig struct { + EnabledLoginMethods []string `json:"enabledLoginMethods"` + } `json:"passwordTabConfig"` + DefaultLoginTab string `json:"defaultLoginTab"` + RegisterTabs []string `json:"registerTabs"` + DefaultRegisterTab string `json:"defaultRegisterTab"` + LdapConnections interface{} `json:"ldapConnections"` + AdConnections []interface{} `json:"adConnections"` + DisabledSocialConnections interface{} `json:"disabledSocialConnections"` + DisabledOidcConnections []interface{} `json:"disabledOidcConnections"` + DisabledSamlConnections []interface{} `json:"disabledSamlConnections"` + DisabledOauth2Connections []interface{} `json:"disabledOauth2Connections"` + DisabledCasConnections []interface{} `json:"disabledCasConnections"` + DisabledAzureAdConnections []interface{} `json:"disabledAzureAdConnections"` + ExtendsFieldsEnabled bool `json:"extendsFieldsEnabled"` + ExtendsFields []interface{} `json:"extendsFields"` + Ext struct { + DontFinishNotYet bool `json:"_dontFinishNotYet"` + AppName string `json:"_appName"` + AliyunDomain string `json:"AliyunDomain"` + AliyunAccountId string `json:"AliyunAccountId"` + SamlConfig struct { + } `json:"samlConfig"` + } `json:"ext"` + Css interface{} `json:"css"` + OidcConfig struct { + GrantTypes []string `json:"grant_types"` + ResponseTypes []string `json:"response_types"` + IdTokenSignedResponseAlg string `json:"id_token_signed_response_alg"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + AuthorizationCodeExpire int `json:"authorization_code_expire"` + IdTokenExpire int `json:"id_token_expire"` + AccessTokenExpire int `json:"access_token_expire"` + RefreshTokenExpire int `json:"refresh_token_expire"` + CasExpire int `json:"cas_expire"` + SkipConsent bool `json:"skip_consent"` + RedirectUris []string `json:"redirect_uris"` + PostLogoutRedirectUris []interface{} `json:"post_logout_redirect_uris"` + ClientId string `json:"client_id"` + ClientSecret string `json:"client_secret"` + } `json:"oidcConfig"` + OidcJWEConfig interface{} `json:"oidcJWEConfig"` + SamlConfig struct { + Acs string `json:"acs"` + Audience string `json:"audience"` + Recipient string `json:"recipient"` + Destination string `json:"destination"` + Mappings interface{} `json:"mappings"` + DigestAlgorithm string `json:"digestAlgorithm"` + SignatureAlgorithm string `json:"signatureAlgorithm"` + AuthnContextClassRef string `json:"authnContextClassRef"` + LifetimeInSeconds int `json:"lifetimeInSeconds"` + SignResponse bool `json:"signResponse"` + NameIdentifierFormat string `json:"nameIdentifierFormat"` + SamlRequestSigningCert string `json:"samlRequestSigningCert"` + SamlResponseSigningCert string `json:"samlResponseSigningCert"` + SamlResponseSigningKey string `json:"samlResponseSigningKey"` + SamlResponseSigningCertFingerprint string `json:"samlResponseSigningCertFingerprint"` + EmailDomainSubstitution string `json:"emailDomainSubstitution"` + } `json:"samlConfig"` + OauthConfig interface{} `json:"oauthConfig"` + CasConfig interface{} `json:"casConfig"` + ShowAuthorizationPage bool `json:"showAuthorizationPage"` + EnableSubAccount bool `json:"enableSubAccount"` + EnableDeviceMutualExclusion bool `json:"enableDeviceMutualExclusion"` + LoginRequireEmailVerified bool `json:"loginRequireEmailVerified"` + AgreementEnabled bool `json:"agreementEnabled"` + IsIntegrate bool `json:"isIntegrate"` + SsoEnabled bool `json:"ssoEnabled"` + Template string `json:"template"` + SkipMfa bool `json:"skipMfa"` + CasExpireBaseBrowser bool `json:"casExpireBaseBrowser"` + PermissionStrategy struct { + Enabled bool `json:"enabled"` + DefaultStrategy string `json:"defaultStrategy"` + AllowPolicyId interface{} `json:"allowPolicyId"` + DenyPolicyId interface{} `json:"denyPolicyId"` + } `json:"permissionStrategy"` +} + +type ApplicationActiveUsers struct { + ThirdPartyIdentity struct { + Provider string `json:"provider"` + RefreshToken string `json:"refreshToken"` + AccessToken string `json:"accessToken"` + Scope string `json:"scope"` + ExpiresIn string `json:"expiresIn"` + UpdatedAt string `json:"updatedAt"` + } `json:"thirdPartyIdentity"` + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserPoolId string `json:"userPoolId"` + IsRoot bool `json:"isRoot"` + Status string `json:"status"` + Oauth string `json:"oauth"` + Email string `json:"email"` + Phone string `json:"phone"` + Username string `json:"username"` + Unionid string `json:"unionid"` + Openid string `json:"openid"` + Nickname string `json:"nickname"` + Company string `json:"company"` + Photo string `json:"photo"` + Browser string `json:"browser"` + Device string `json:"device"` + Password string `json:"password"` + Salt string `json:"salt"` + LoginsCount int `json:"loginsCount"` + LastIp string `json:"lastIp"` + Name string `json:"name"` + GivenName string `json:"givenName"` + FamilyName string `json:"familyName"` + MiddleName string `json:"middleName"` + Profile string `json:"profile"` + PreferredUsername string `json:"preferredUsername"` + Website string `json:"website"` + Gender string `json:"gender"` + Birthdate string `json:"birthdate"` + Zoneinfo string `json:"zoneinfo"` + Locale string `json:"locale"` + Address string `json:"address"` + Formatted string `json:"formatted"` + StreetAddress string `json:"streetAddress"` + Locality string `json:"locality"` + Region string `json:"region"` + PostalCode string `json:"postalCode"` + City string `json:"city"` + Province string `json:"province"` + Country string `json:"country"` + RegisterSource []string `json:"registerSource"` + SecretInfo interface{} `json:"secretInfo"` + EmailVerified bool `json:"emailVerified"` + PhoneVerified bool `json:"phoneVerified"` + LastLogin time.Time `json:"lastLogin"` + Blocked bool `json:"blocked"` + IsDeleted bool `json:"isDeleted"` + SendSmsCount int `json:"sendSmsCount"` + SendSmsLimitCount int `json:"sendSmsLimitCount"` + DataVersion string `json:"dataVersion"` + EncryptedPassword string `json:"encryptedPassword"` + SignedUp time.Time `json:"signedUp"` + ExternalId string `json:"externalId"` + MainDepartmentId string `json:"mainDepartmentId"` + MainDepartmentCode string `json:"mainDepartmentCode"` + LastMfaTime string `json:"lastMfaTime"` + PasswordSecurityLevel int `json:"passwordSecurityLevel"` + ResetPasswordOnFirstLogin bool `json:"resetPasswordOnFirstLogin"` + SyncExtInfo string `json:"syncExtInfo"` + PhoneCountryCode string `json:"phoneCountryCode"` + Source interface{} `json:"source"` + LastIP string `json:"lastIP"` + Token string `json:"token"` + TokenExpiredAt time.Time `json:"tokenExpiredAt"` +} + +type ApplicationAgreement struct { + UserPoolId string `json:"userPoolId"` + AppId string `json:"appId"` + Title string `json:"title"` + Lang string `json:"lang"` + Required bool `json:"required"` + Order int `json:"order"` + Id int `json:"id"` +} diff --git a/lib/model/group_model.go b/lib/model/group_model.go index 1496854..e633d1a 100644 --- a/lib/model/group_model.go +++ b/lib/model/group_model.go @@ -9,3 +9,23 @@ type GroupModel struct { CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } + +type CreateGroupsRequest struct { + Code string `json:"code"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` +} + +type UpdateGroupsRequest struct { + Code string `json:"code"` + NewCode *string `json:"newCode,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` +} + +type GetGroupUserResponse struct { + Users struct { + TotalCount int `json:"totalCount"` + List []User `json:"list"` + } `json:"users"` +} diff --git a/lib/model/mfa_model.go b/lib/model/mfa_model.go new file mode 100644 index 0000000..13947fe --- /dev/null +++ b/lib/model/mfa_model.go @@ -0,0 +1,39 @@ +package model + +import ( + "github.com/Authing/authing-go-sdk/lib/constant" + "time" +) + +type MfaInput struct { + MfaToken *string + MfaType *string `json:"type"` + MfaSource *constant.MfaSource `json:"source"` +} + +type GetMfaAuthenticatorsResponse struct { + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserId string `json:"userId"` + Enable bool `json:"enable"` + Secret string `json:"secret"` + AuthenticatorType string `json:"authenticatorType"` + RecoveryCode string `json:"recoveryCode"` + Source string `json:"source"` +} + +type AssociateMfaAuthenticatorResponse struct { + AuthenticatorType string `json:"authenticator_type"` + Secret string `json:"secret"` + QrcodeUri string `json:"qrcode_uri"` + QrcodeDataUrl string `json:"qrcode_data_url"` + RecoveryCode string `json:"recovery_code"` +} + +type ConfirmAssociateMfaAuthenticatorRequest struct { + Totp string `json:"totp"` + AuthenticatorType *string `json:"authenticatorType"` + MfaSource *constant.MfaSource `json:"source"` + MfaToken *string +} diff --git a/lib/model/models.go b/lib/model/models.go index af48416..c2ca85a 100644 --- a/lib/model/models.go +++ b/lib/model/models.go @@ -3,14 +3,16 @@ package model +import "time" + type EnumEmailTemplateType string -const EnumEmailTemplateTypeRESET_PASSWORD EnumEmailTemplateType = "RESET_PASSWORD" -const EnumEmailTemplateTypePASSWORD_RESETED_NOTIFICATION EnumEmailTemplateType = "PASSWORD_RESETED_NOTIFICATION" -const EnumEmailTemplateTypeCHANGE_PASSWORD EnumEmailTemplateType = "CHANGE_PASSWORD" -const EnumEmailTemplateTypeWELCOME EnumEmailTemplateType = "WELCOME" -const EnumEmailTemplateTypeVERIFY_EMAIL EnumEmailTemplateType = "VERIFY_EMAIL" -const EnumEmailTemplateTypeCHANGE_EMAIL EnumEmailTemplateType = "CHANGE_EMAIL" +const EnumEmailTemplateTypeResetPassword EnumEmailTemplateType = "RESET_PASSWORD" +const EnumEmailTemplateTypePasswordResetedNotification EnumEmailTemplateType = "PASSWORD_RESETED_NOTIFICATION" +const EnumEmailTemplateTypeChangePassword EnumEmailTemplateType = "CHANGE_PASSWORD" +const EnumEmailTemplateTypeWelcome EnumEmailTemplateType = "WELCOME" +const EnumEmailTemplateTypeVerifyEmail EnumEmailTemplateType = "VERIFY_EMAIL" +const EnumEmailTemplateTypeChangeEmail EnumEmailTemplateType = "CHANGE_EMAIL" type EnumResourceType string @@ -36,39 +38,39 @@ const EnumUserStatusArchived EnumUserStatus = "Archived" type Enum__TypeKind string -const Enum__TypeKindSCALAR Enum__TypeKind = "SCALAR" -const Enum__TypeKindOBJECT Enum__TypeKind = "OBJECT" -const Enum__TypeKindINTERFACE Enum__TypeKind = "INTERFACE" -const Enum__TypeKindUNION Enum__TypeKind = "UNION" -const Enum__TypeKindENUM Enum__TypeKind = "ENUM" -const Enum__TypeKindINPUT_OBJECT Enum__TypeKind = "INPUT_OBJECT" -const Enum__TypeKindLIST Enum__TypeKind = "LIST" -const Enum__TypeKindNON_NULL Enum__TypeKind = "NON_NULL" +const TypeKindScalar Enum__TypeKind = "SCALAR" +const TypeKindObject Enum__TypeKind = "OBJECT" +const TypeKindInterface Enum__TypeKind = "INTERFACE" +const TypeKindUnion Enum__TypeKind = "UNION" +const TypeKindEnum Enum__TypeKind = "ENUM" +const TypeKindInputObject Enum__TypeKind = "INPUT_OBJECT" +const TypeKindList Enum__TypeKind = "LIST" +const TypeKindNonNull Enum__TypeKind = "NON_NULL" type EnumEmailScene string -const EnumEmailSceneRESET_PASSWORD EnumEmailScene = "RESET_PASSWORD" -const EnumEmailSceneVERIFY_EMAIL EnumEmailScene = "VERIFY_EMAIL" -const EnumEmailSceneCHANGE_EMAIL EnumEmailScene = "CHANGE_EMAIL" -const EnumEmailSceneMFA_VERIFY EnumEmailScene = "MFA_VERIFY" +const EnumEmailSceneResetPassword EnumEmailScene = "RESET_PASSWORD" +const EnumEmailSceneVerifyEmail EnumEmailScene = "VERIFY_EMAIL" +const EnumEmailSceneChangeEmail EnumEmailScene = "CHANGE_EMAIL" +const EnumEmailSceneMfaVerify EnumEmailScene = "MFA_VERIFY" type EnumOperator string -const EnumOperatorAND EnumOperator = "AND" -const EnumOperatorOR EnumOperator = "OR" +const EnumOperatorAnd EnumOperator = "AND" +const EnumOperatorOr EnumOperator = "OR" type EnumPolicyAssignmentTargetType string -const EnumPolicyAssignmentTargetTypeUSER EnumPolicyAssignmentTargetType = "USER" -const EnumPolicyAssignmentTargetTypeROLE EnumPolicyAssignmentTargetType = "ROLE" -const EnumPolicyAssignmentTargetTypeGROUP EnumPolicyAssignmentTargetType = "GROUP" -const EnumPolicyAssignmentTargetTypeORG EnumPolicyAssignmentTargetType = "ORG" -const EnumPolicyAssignmentTargetTypeAK_SK EnumPolicyAssignmentTargetType = "AK_SK" +const EnumPolicyAssignmentTargetTypeUser EnumPolicyAssignmentTargetType = "USER" +const EnumPolicyAssignmentTargetTypeRole EnumPolicyAssignmentTargetType = "ROLE" +const EnumPolicyAssignmentTargetTypeGroup EnumPolicyAssignmentTargetType = "GROUP" +const EnumPolicyAssignmentTargetTypeOrg EnumPolicyAssignmentTargetType = "ORG" +const EnumPolicyAssignmentTargetTypeAkSk EnumPolicyAssignmentTargetType = "AK_SK" type EnumPolicyEffect string -const EnumPolicyEffectALLOW EnumPolicyEffect = "ALLOW" -const EnumPolicyEffectDENY EnumPolicyEffect = "DENY" +const EnumPolicyEffectAllow EnumPolicyEffect = "ALLOW" +const EnumPolicyEffectDeny EnumPolicyEffect = "DENY" type EnumUDFDataType string @@ -90,31 +92,31 @@ const EnumUDFTargetTypeAPPLICATION EnumUDFTargetType = "APPLICATION" type EnumWhitelistType string -const EnumWhitelistTypeUSERNAME EnumWhitelistType = "USERNAME" -const EnumWhitelistTypeEMAIL EnumWhitelistType = "EMAIL" -const EnumWhitelistTypePHONE EnumWhitelistType = "PHONE" +const EnumWhitelistTypeUsername EnumWhitelistType = "USERNAME" +const EnumWhitelistTypeEmail EnumWhitelistType = "EMAIL" +const EnumWhitelistTypePhone EnumWhitelistType = "PHONE" type Enum__DirectiveLocation string -const Enum__DirectiveLocationQUERY Enum__DirectiveLocation = "QUERY" -const Enum__DirectiveLocationMUTATION Enum__DirectiveLocation = "MUTATION" -const Enum__DirectiveLocationSUBSCRIPTION Enum__DirectiveLocation = "SUBSCRIPTION" -const Enum__DirectiveLocationFIELD Enum__DirectiveLocation = "FIELD" -const Enum__DirectiveLocationFRAGMENT_DEFINITION Enum__DirectiveLocation = "FRAGMENT_DEFINITION" -const Enum__DirectiveLocationFRAGMENT_SPREAD Enum__DirectiveLocation = "FRAGMENT_SPREAD" -const Enum__DirectiveLocationINLINE_FRAGMENT Enum__DirectiveLocation = "INLINE_FRAGMENT" -const Enum__DirectiveLocationVARIABLE_DEFINITION Enum__DirectiveLocation = "VARIABLE_DEFINITION" -const Enum__DirectiveLocationSCHEMA Enum__DirectiveLocation = "SCHEMA" -const Enum__DirectiveLocationSCALAR Enum__DirectiveLocation = "SCALAR" -const Enum__DirectiveLocationOBJECT Enum__DirectiveLocation = "OBJECT" -const Enum__DirectiveLocationFIELD_DEFINITION Enum__DirectiveLocation = "FIELD_DEFINITION" -const Enum__DirectiveLocationARGUMENT_DEFINITION Enum__DirectiveLocation = "ARGUMENT_DEFINITION" -const Enum__DirectiveLocationINTERFACE Enum__DirectiveLocation = "INTERFACE" -const Enum__DirectiveLocationUNION Enum__DirectiveLocation = "UNION" -const Enum__DirectiveLocationENUM Enum__DirectiveLocation = "ENUM" -const Enum__DirectiveLocationENUM_VALUE Enum__DirectiveLocation = "ENUM_VALUE" -const Enum__DirectiveLocationINPUT_OBJECT Enum__DirectiveLocation = "INPUT_OBJECT" -const Enum__DirectiveLocationINPUT_FIELD_DEFINITION Enum__DirectiveLocation = "INPUT_FIELD_DEFINITION" +const DirectiveLocationQuery Enum__DirectiveLocation = "QUERY" +const DirectiveLocationMutation Enum__DirectiveLocation = "MUTATION" +const DirectiveLocationSubscription Enum__DirectiveLocation = "SUBSCRIPTION" +const DirectiveLocationField Enum__DirectiveLocation = "FIELD" +const DirectiveLocationFragmentDefinition Enum__DirectiveLocation = "FRAGMENT_DEFINITION" +const DirectiveLocationFragmentSpread Enum__DirectiveLocation = "FRAGMENT_SPREAD" +const DirectiveLocationInlineFragment Enum__DirectiveLocation = "INLINE_FRAGMENT" +const DirectiveLocationVariableDefinition Enum__DirectiveLocation = "VARIABLE_DEFINITION" +const DirectiveLocationSchema Enum__DirectiveLocation = "SCHEMA" +const DirectiveLocationScalar Enum__DirectiveLocation = "SCALAR" +const DirectiveLocationObject Enum__DirectiveLocation = "OBJECT" +const DirectiveLocationFieldDefinition Enum__DirectiveLocation = "FIELD_DEFINITION" +const DirectiveLocationArgumentDefinition Enum__DirectiveLocation = "ARGUMENT_DEFINITION" +const DirectiveLocationInterface Enum__DirectiveLocation = "INTERFACE" +const DirectiveLocationUnion Enum__DirectiveLocation = "UNION" +const DirectiveLocationEnum Enum__DirectiveLocation = "ENUM" +const DirectiveLocationEnumValue Enum__DirectiveLocation = "ENUM_VALUE" +const DirectiveLocationInputObject Enum__DirectiveLocation = "INPUT_OBJECT" +const DirectiveLocationInputFieldDefinition Enum__DirectiveLocation = "INPUT_FIELD_DEFINITION" type __Schema struct { Types []__Type `json:"types"` @@ -179,8 +181,8 @@ type App2WxappLoginStrategy struct { } type App2WxappLoginStrategyInput struct { - TicketExpriresAfter *int64 `json:"ticketExpriresAfter"` - TicketExchangeUserInfoNeedSecret *bool `json:"ticketExchangeUserInfoNeedSecret"` + TicketExpriresAfter *int64 `json:"ticketExpriresAfter,omitempty"` + TicketExchangeUserInfoNeedSecret *bool `json:"ticketExchangeUserInfoNeedSecret,omitempty"` } type AuthorizedResource struct { @@ -208,19 +210,19 @@ type BatchOperationResult struct { } type ChangeEmailStrategy struct { - VerifyOldEmail *bool `json:"verifyOldEmail"` + VerifyOldEmail *bool `json:"verifyOldEmail,omitempty"` } type ChangeEmailStrategyInput struct { - VerifyOldEmail *bool `json:"verifyOldEmail"` + VerifyOldEmail *bool `json:"verifyOldEmail,omitempty"` } type ChangePhoneStrategy struct { - VerifyOldPhone *bool `json:"verifyOldPhone"` + VerifyOldPhone *bool `json:"verifyOldPhone,omitempty"` } type ChangePhoneStrategyInput struct { - VerifyOldPhone *bool `json:"verifyOldPhone"` + VerifyOldPhone *bool `json:"verifyOldPhone,omitempty"` } type CheckPasswordStrengthResult struct { @@ -276,9 +278,9 @@ type CustomSMSProvider struct { } type CustomSMSProviderInput struct { - Enabled *bool `json:"enabled"` - Provider *string `json:"provider"` - Config *string `json:"config"` + Enabled *bool `json:"enabled,omitempty"` + Provider *string `json:"provider,omitempty"` + Config *string `json:"config,omitempty"` } type EmailTemplate struct { @@ -301,9 +303,9 @@ type FrequentRegisterCheckConfig struct { } type FrequentRegisterCheckConfigInput struct { - TimeInterval *int64 `json:"timeInterval"` - Limit *int64 `json:"limit"` - Enabled *bool `json:"enabled"` + TimeInterval *int64 `json:"timeInterval,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Enabled *bool `json:"enabled,omitempty"` } type Function struct { @@ -402,21 +404,21 @@ type LoginFailCheckConfig struct { } type LoginFailCheckConfigInput struct { - TimeInterval *int64 `json:"timeInterval"` - Limit *int64 `json:"limit"` - Enabled *bool `json:"enabled"` + TimeInterval *int64 `json:"timeInterval,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Enabled *bool `json:"enabled,omitempty"` } type LoginPasswordFailCheckConfig struct { - TimeInterval *int64 `json:"timeInterval"` - Limit *int64 `json:"limit"` - Enabled *bool `json:"enabled"` + TimeInterval *int64 `json:"timeInterval,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Enabled *bool `json:"enabled,omitempty"` } type LoginPasswordFailCheckConfigInput struct { - TimeInterval *int64 `json:"timeInterval"` - Limit *int64 `json:"limit"` - Enabled *bool `json:"enabled"` + TimeInterval *int64 `json:"timeInterval,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Enabled *bool `json:"enabled,omitempty"` } type Mfa struct { @@ -427,33 +429,6 @@ type Mfa struct { Secret *string `json:"secret"` } -type Node struct { - Id string `json:"id"` - OrgId *string `json:"orgId"` - Name string `json:"name"` - NameI18n *string `json:"nameI18n"` - Description *string `json:"description"` - DescriptionI18n *string `json:"descriptionI18n"` - Order *int64 `json:"order"` - Code *string `json:"code"` - Root *bool `json:"root"` - Depth *int64 `json:"depth"` - Path []string `json:"path"` - CodePath []*string `json:"codePath"` - NamePath []string `json:"namePath"` - CreatedAt *string `json:"createdAt"` - UpdatedAt *string `json:"updatedAt"` - Children []string `json:"children"` - Users PaginatedUsers `json:"users"` - AuthorizedResources *PaginatedAuthorizedResources `json:"authorizedResources"` -} - -type Org struct { - Id string `json:"id"` - RootNode Node `json:"rootNode"` - Nodes []Node `json:"nodes"` -} - type PaginatedAuthorizedResources struct { TotalCount int64 `json:"totalCount"` List []AuthorizedResource `json:"list"` @@ -479,21 +454,6 @@ type PaginatedGroups struct { List []Group `json:"list"` } -type PaginatedOrgs struct { - TotalCount int64 `json:"totalCount"` - List []Org `json:"list"` -} - -type PaginatedPolicies struct { - TotalCount int64 `json:"totalCount"` - List []Policy `json:"list"` -} - -type PaginatedPolicyAssignments struct { - TotalCount int64 `json:"totalCount"` - List []PolicyAssignment `json:"list"` -} - type PaginatedRoles struct { TotalCount int64 `json:"totalCount"` List []Role `json:"list"` @@ -509,50 +469,6 @@ type PaginatedUsers struct { List []User `json:"list"` } -type Policy struct { - Namespace string `json:"namespace"` - Code string `json:"code"` - IsDefault bool `json:"isDefault"` - Description *string `json:"description"` - Statements []PolicyStatement `json:"statements"` - CreatedAt *string `json:"createdAt"` - UpdatedAt *string `json:"updatedAt"` - AssignmentsCount int64 `json:"assignmentsCount"` - Assignments []PolicyAssignment `json:"assignments"` -} - -type PolicyAssignment struct { - Code string `json:"code"` - TargetType EnumPolicyAssignmentTargetType `json:"targetType"` - TargetIdentifier string `json:"targetIdentifier"` -} - -type PolicyStatement struct { - Resource string `json:"resource"` - Actions []string `json:"actions"` - Effect *EnumPolicyEffect `json:"effect"` - Condition []PolicyStatementCondition `json:"condition"` -} - -type PolicyStatementCondition struct { - Param string `json:"param"` - Operator string `json:"operator"` - //Value Object `json:"value"` -} - -type PolicyStatementConditionInput struct { - Param string `json:"param"` - Operator string `json:"operator"` - //Value Object `json:"value"` -} - -type PolicyStatementInput struct { - Resource string `json:"resource"` - Actions []string `json:"actions"` - Effect *EnumPolicyEffect `json:"effect"` - Condition []PolicyStatementConditionInput `json:"condition"` -} - type QrcodeLoginStrategy struct { QrcodeExpiresAfter *int64 `json:"qrcodeExpiresAfter"` ReturnFullUserInfo *bool `json:"returnFullUserInfo"` @@ -561,10 +477,10 @@ type QrcodeLoginStrategy struct { } type QrcodeLoginStrategyInput struct { - QrcodeExpiresAfter *int64 `json:"qrcodeExpiresAfter"` - ReturnFullUserInfo *bool `json:"returnFullUserInfo"` - AllowExchangeUserInfoFromBrowser *bool `json:"allowExchangeUserInfoFromBrowser"` - TicketExpiresAfter *int64 `json:"ticketExpiresAfter"` + QrcodeExpiresAfter *int64 `json:"qrcodeExpiresAfter,omitempty"` + ReturnFullUserInfo *bool `json:"returnFullUserInfo,omitempty"` + AllowExchangeUserInfoFromBrowser *bool `json:"allowExchangeUserInfoFromBrowser,omitempty"` + TicketExpiresAfter *int64 `json:"ticketExpiresAfter,omitempty"` } type RefreshAccessTokenRes struct { @@ -582,12 +498,12 @@ type RefreshToken struct { type RegisterByEmailInput struct { Email string `json:"email"` Password string `json:"password"` - Profile *RegisterProfile `json:"profile"` - ForceLogin *bool `json:"forceLogin"` - GenerateToken *bool `json:"generateToken"` - ClientIp *string `json:"clientIp"` - Params *string `json:"params"` - Context *string `json:"context"` + Profile *RegisterProfile `json:"profile,omitempty"` + ForceLogin *bool `json:"forceLogin,omitempty"` + GenerateToken *bool `json:"generateToken,omitempty"` + ClientIp *string `json:"clientIp,omitempty"` + Params *string `json:"params,omitempty"` + Context *string `json:"context,omitempty"` } type RegisterByPhoneCodeInput struct { @@ -650,9 +566,9 @@ type RegisterWhiteListConfig struct { } type RegisterWhiteListConfigInput struct { - PhoneEnabled *bool `json:"phoneEnabled"` - EmailEnabled *bool `json:"emailEnabled"` - UsernameEnabled *bool `json:"usernameEnabled"` + PhoneEnabled *bool `json:"phoneEnabled,omitempty"` + EmailEnabled *bool `json:"emailEnabled,omitempty"` + UsernameEnabled *bool `json:"usernameEnabled,omitempty"` } type ResourcePermissionAssignment struct { @@ -725,29 +641,29 @@ type UpdateFunctionInput struct { } type UpdateUserpoolInput struct { - Name *string `json:"name"` - Logo *string `json:"logo"` - Domain *string `json:"domain"` - Description *string `json:"description"` - UserpoolTypes []string `json:"userpoolTypes"` - EmailVerifiedDefault *bool `json:"emailVerifiedDefault"` - SendWelcomeEmail *bool `json:"sendWelcomeEmail"` - RegisterDisabled *bool `json:"registerDisabled"` - AppSsoEnabled *bool `json:"appSsoEnabled"` - AllowedOrigins *string `json:"allowedOrigins"` - TokenExpiresAfter *int64 `json:"tokenExpiresAfter"` - FrequentRegisterCheck *FrequentRegisterCheckConfigInput `json:"frequentRegisterCheck"` - LoginFailCheck *LoginFailCheckConfigInput `json:"loginFailCheck"` - LoginFailStrategy *string `json:"loginFailStrategy"` - LoginPasswordFailCheck *LoginPasswordFailCheckConfigInput `json:"loginPasswordFailCheck"` - ChangePhoneStrategy *ChangePhoneStrategyInput `json:"changePhoneStrategy"` - ChangeEmailStrategy *ChangeEmailStrategyInput `json:"changeEmailStrategy"` - QrcodeLoginStrategy *QrcodeLoginStrategyInput `json:"qrcodeLoginStrategy"` - App2WxappLoginStrategy *App2WxappLoginStrategyInput `json:"app2WxappLoginStrategy"` - Whitelist *RegisterWhiteListConfigInput `json:"whitelist"` - CustomSMSProvider *CustomSMSProviderInput `json:"customSMSProvider"` - LoginRequireEmailVerified *bool `json:"loginRequireEmailVerified"` - VerifyCodeLength *int64 `json:"verifyCodeLength"` + Name *string `json:"name,omitempty"` + Logo *string `json:"logo,omitempty"` + Domain *string `json:"domain,omitempty"` + Description *string `json:"description,omitempty"` + UserpoolTypes []string `json:"userpoolTypes,omitempty"` + EmailVerifiedDefault *bool `json:"emailVerifiedDefault,omitempty"` + SendWelcomeEmail *bool `json:"sendWelcomeEmail,omitempty"` + RegisterDisabled *bool `json:"registerDisabled,omitempty"` + AppSsoEnabled *bool `json:"appSsoEnabled,omitempty"` + AllowedOrigins *string `json:"allowedOrigins,omitempty"` + TokenExpiresAfter *int64 `json:"tokenExpiresAfter,omitempty"` + FrequentRegisterCheck *FrequentRegisterCheckConfigInput `json:"frequentRegisterCheck,omitempty"` + LoginFailCheck *LoginFailCheckConfigInput `json:"loginFailCheck,omitempty"` + LoginFailStrategy *string `json:"loginFailStrategy,omitempty"` + LoginPasswordFailCheck *LoginPasswordFailCheckConfigInput `json:"loginPasswordFailCheck,omitempty"` + ChangePhoneStrategy *ChangePhoneStrategyInput `json:"changePhoneStrategy,omitempty"` + ChangeEmailStrategy *ChangeEmailStrategyInput `json:"changeEmailStrategy,omitempty"` + QrcodeLoginStrategy *QrcodeLoginStrategyInput `json:"qrcodeLoginStrategy,omitempty"` + App2WxappLoginStrategy *App2WxappLoginStrategyInput `json:"app2WxappLoginStrategy,omitempty"` + Whitelist *RegisterWhiteListConfigInput `json:"whitelist,omitempty"` + CustomSMSProvider *CustomSMSProviderInput `json:"customSMSProvider,omitempty"` + LoginRequireEmailVerified *bool `json:"loginRequireEmailVerified,omitempty"` + VerifyCodeLength *int64 `json:"verifyCodeLength,omitempty"` } type UserDepartment struct { @@ -824,3 +740,55 @@ type CommonMessageAndCode struct { Message string `json:"message"` Code int64 `json:"code"` } + +type UserPoolEnv struct { + UserPoolId string `json:"userPoolId"` + Key string `json:"key"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + Id string `json:"id"` +} + +type UserOrgs []struct { + Type string `json:"type"` + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserPoolId string `json:"userPoolId"` + RootNodeId string `json:"rootNodeId,omitempty"` + Logo string `json:"logo"` + OrgId string `json:"orgId,omitempty"` + Name string `json:"name,omitempty"` + NameI18N string `json:"nameI18n"` + Description *string `json:"description,omitempty"` + DescriptionI18N string `json:"descriptionI18n"` + Order string `json:"order"` + Code *string `json:"code,omitempty"` + LeaderUserId string `json:"leaderUserId"` + Source []interface{} `json:"source,omitempty"` + DataVersion interface{} `json:"dataVersion"` + SourceData interface{} `json:"sourceData"` +} + +type GetSecurityLevelResponse struct { + Score int `json:"score"` + Email bool `json:"email"` + Phone bool `json:"phone"` + Password bool `json:"password"` + PasswordSecurityLevel int `json:"passwordSecurityLevel"` + Mfa bool `json:"mfa"` +} + +type LoginBySubAccountRequest struct { + Account string `json:"account"` + Password string `json:"password"` + CaptchaCode string `json:"captchaCode,omitempty"` + ClientIp string `json:"clientIp,omitempty"` +} + +type IsUserExistsRequest struct { + Username *string `json:"username,omitempty"` + Email *string `json:"email,omitempty"` + Phone *string `json:"phone,omitempty"` + ExternalId *string `json:"externalId,omitempty"` +} diff --git a/lib/model/namespace_model.go b/lib/model/namespace_model.go new file mode 100644 index 0000000..e76e7b4 --- /dev/null +++ b/lib/model/namespace_model.go @@ -0,0 +1,25 @@ +package model + +type Namespace struct { + UserPoolId string `json:"userPoolId"` + Name string `json:"name"` + Code string `json:"code"` + Description string `json:"description"` + Status int `json:"status"` + ApplicationId string `json:"applicationId"` + IsIntegrateApp bool `json:"isIntegrateApp"` + IsDefaultApp bool `json:"isDefaultApp"` + Id int `json:"id"` +} + +type EditNamespaceRequest struct { + Code *string `json:"code,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` +} + +type ListGroupsAuthorizedResourcesRequest struct { + Code string `json:"code"` + Namespace *string `json:"namespace,omitempty"` + ResourceType *EnumResourceType `json:"resourceType,omitempty"` +} diff --git a/lib/model/org_model.go b/lib/model/org_model.go index 8b53790..6b08b7e 100644 --- a/lib/model/org_model.go +++ b/lib/model/org_model.go @@ -1 +1,109 @@ package model + +type CreateOrgRequest struct { + Name string `json:"name"` + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` +} + +type OrgNode struct { + Id string `json:"id"` + OrgId *string `json:"orgId"` + CreatedAt *string `json:"createdAt"` + UpdatedAt *string `json:"updatedAt"` + UserPoolId *string `json:"userPoolId"` + Name string `json:"name"` + Description *string `json:"description"` + DescriptionI18n *string `json:"descriptionI18n"` + Order *int64 `json:"order"` + Code *string `json:"code"` + Members *[]User `json:"members,omitempty"` + Children *[]OrgNode `json:"children,omitempty"` +} + +type OrgResponse struct { + Id string `json:"id"` + RootNode *OrgNode `json:"rootNode,omitempty"` + Nodes *[]OrgNode `json:"nodes,omitempty"` +} + +type PaginatedOrgs struct { + TotalCount int64 `json:"totalCount"` + List []Org `json:"list"` +} + +type Node struct { + Id string `json:"id"` + OrgId *string `json:"orgId"` + Name string `json:"name"` + NameI18n *string `json:"nameI18n"` + Description *string `json:"description"` + DescriptionI18n *string `json:"descriptionI18n"` + Order *int64 `json:"order"` + Code *string `json:"code"` + Root *bool `json:"root"` + Depth *int64 `json:"depth"` + Path []string `json:"path"` + CodePath []*string `json:"codePath"` + NamePath []string `json:"namePath"` + CreatedAt *string `json:"createdAt"` + UpdatedAt *string `json:"updatedAt"` + Children []string `json:"children"` + Users PaginatedUsers `json:"users"` + AuthorizedResources *PaginatedAuthorizedResources `json:"authorizedResources"` +} + +type Org struct { + Id string `json:"id"` + RootNode Node `json:"rootNode"` + Nodes []Node `json:"nodes"` +} + +type AddNodeOrg struct { + Id string `json:"id"` + RootNode OrgNodeChildStr `json:"rootNode"` + Nodes []OrgNodeChildStr `json:"nodes"` +} +type AddOrgNodeRequest struct { + OrgId string `json:"orgId"` + ParentNodeId string `json:"parentNodeId"` + Name string `json:"name"` + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` + Order *int `json:"order,omitempty"` + NameI18N *string `json:"nameI18n,omitempty"` + DescriptionI18N *string `json:"descriptionI18n,omitempty"` +} + +type OrgNodeChildStr struct { + Id string `json:"id"` + OrgId *string `json:"orgId"` + Name string `json:"name"` + NameI18n *string `json:"nameI18n"` + Description *string `json:"description"` + DescriptionI18n *string `json:"descriptionI18n"` + Order *int64 `json:"order"` + Code *string `json:"code"` + Root *bool `json:"root"` + Depth *int64 `json:"depth"` + Path []string `json:"path"` + CodePath []*string `json:"codePath"` + NamePath []string `json:"namePath"` + CreatedAt *string `json:"createdAt"` + UpdatedAt *string `json:"updatedAt"` + Children []string `json:"children"` +} + +type UpdateOrgNodeRequest struct { + Id string `json:"id"` + Name *string `json:"name,omitempty"` + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` +} + +type ListAuthorizedResourcesByNodeCodeRequest struct { + Id string `json:"id"` + Code string `json:"code"` + Namespace *string `json:"namespace,omitempty"` + ResourceType *string `json:"resourceType,omitempty"` +} diff --git a/lib/model/policy_model.go b/lib/model/policy_model.go new file mode 100644 index 0000000..8407513 --- /dev/null +++ b/lib/model/policy_model.go @@ -0,0 +1,99 @@ +package model + +import ( + "time" +) + +type PolicyRequest struct { + Code string `json:"code"` + Description *string `json:"description,omitempty"` + Statements []PolicyStatement `json:"statements,omitempty"` +} + +type CreatePolicyResponse struct { + Namespace string `json:"namespace"` + Code string `json:"code"` + IsDefault bool `json:"isDefault"` + Description string `json:"description"` + Statements []PolicyStatement `json:"statements"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + AssignmentsCount int `json:"assignmentsCount"` +} + +type UpdatePolicyResponse struct { + Namespace string `json:"namespace"` + Code string `json:"code"` + IsDefault bool `json:"isDefault"` + Description string `json:"description"` + Statements []PolicyStatement `json:"statements"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type PaginatedPolicies struct { + TotalCount int64 `json:"totalCount"` + List []Policy `json:"list"` +} + +type PaginatedPolicyAssignments struct { + TotalCount int64 `json:"totalCount"` + List []PolicyAssignment `json:"list"` +} + +type Policy struct { + Namespace string `json:"namespace"` + Code string `json:"code"` + IsDefault bool `json:"isDefault"` + Description *string `json:"description"` + Statements []PolicyStatement `json:"statements"` + CreatedAt *string `json:"createdAt"` + UpdatedAt *string `json:"updatedAt"` + AssignmentsCount int64 `json:"assignmentsCount"` + Assignments []PolicyAssignment `json:"assignments"` +} + +type PolicyAssignment struct { + Code string `json:"code"` + TargetType EnumPolicyAssignmentTargetType `json:"targetType"` + TargetIdentifier string `json:"targetIdentifier"` +} + +type PolicyStatement struct { + Resource string `json:"resource"` + Actions []string `json:"actions"` + Effect *EnumPolicyEffect `json:"effect"` + Condition []PolicyStatementCondition `json:"condition,omitempty"` +} + +type PolicyStatementCondition struct { + Param string `json:"param"` + Operator string `json:"operator"` + //Value Object `json:"value"` +} + +type PolicyStatementConditionInput struct { + Param string `json:"param"` + Operator string `json:"operator"` + //Value Object `json:"value"` +} + +type PolicyStatementInput struct { + Resource string `json:"resource"` + Actions []string `json:"actions"` + Effect *EnumPolicyEffect `json:"effect"` + Condition []PolicyStatementConditionInput `json:"condition"` +} + +type PolicyAssignmentsRequest struct { + Policies []string `json:"policies"` + TargetType EnumPolicyAssignmentTargetType `json:"targetType"` + TargetIdentifiers []string `json:"targetIdentifiers"` +} + +type SwitchPolicyAssignmentsRequest struct { + Policy string `json:"policy"` + TargetType EnumPolicyAssignmentTargetType `json:"targetType"` + TargetIdentifier string `json:"targetIdentifier"` + Namespace *string `json:"namespace,omitempty"` +} diff --git a/lib/model/role_model.go b/lib/model/role_model.go index c6a4514..c6ca38f 100644 --- a/lib/model/role_model.go +++ b/lib/model/role_model.go @@ -7,13 +7,13 @@ type Role struct { Namespace string `json:"namespace"` Code string `json:"code"` Arn string `json:"arn"` - Description *string `json:"description"` - IsSystem *bool `json:"isSystem"` - CreatedAt *string `json:"createdAt"` - UpdatedAt *string `json:"updatedAt"` + Description *string `json:"description,omitempty"` + IsSystem *bool `json:"isSystem,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` Users PaginatedUsers `json:"users"` - AuthorizedResources *PaginatedAuthorizedResources `json:"authorizedResources"` - Parent *Role `json:"parent"` + AuthorizedResources *PaginatedAuthorizedResources `json:"authorizedResources,omitempty"` + Parent *Role `json:"parent,omitempty"` } type RoleModel struct { @@ -21,18 +21,18 @@ type RoleModel struct { Namespace string `json:"namespace"` Code string `json:"code"` Arn string `json:"arn"` - Description *string `json:"description"` - CreatedAt *string `json:"createdAt"` - UpdatedAt *string `json:"updatedAt"` + Description *string `json:"description,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` Parent *struct { - Id string `json:"id"` - Namespace string `json:"namespace"` - Code string `json:"code"` - Arn string `json:"arn"` - Description *string `json:"description"` - CreatedAt *string `json:"createdAt"` - UpdatedAt *string `json:"updatedAt"` - } `json:"parent"` + Id string `json:"id,omitempty"` + Namespace string `json:"namespace,omitempty"` + Code string `json:"code,omitempty"` + Arn string `json:"arn,omitempty"` + Description *string `json:"description,omitempty"` + CreatedAt *string `json:"createdAt,omitempty"` + UpdatedAt *string `json:"updatedAt,omitempty"` + } `json:"parent,omitempty"` } type GetRoleListRequest struct { @@ -50,22 +50,22 @@ type GetRoleListResponse struct { } type GetRoleUserListRequest struct { - Page int `json:"page"` - Limit int `json:"limit"` - Code string `json:"code"` - Namespace string `json:"namespace"` + Page int `json:"page"` + Limit int `json:"limit"` + Code string `json:"code"` + Namespace *string `json:"namespace,omitempty"` } type CreateRoleRequest struct { - Code string `json:"code"` - Namespace string `json:"namespace,omitempty"` - Description string `json:"description,omitempty"` - ParentCode string `json:"parent,omitempty"` + Code string `json:"code"` + Namespace *string `json:"namespace,omitempty"` + Description *string `json:"description,omitempty"` + ParentCode *string `json:"parent,omitempty"` } type DeleteRoleRequest struct { - Code string `json:"code"` - Namespace string `json:"namespace,omitempty"` + Code string `json:"code"` + Namespace *string `json:"namespace,omitempty"` } type DeleteRole struct { @@ -74,25 +74,25 @@ type DeleteRole struct { type BatchDeleteRoleRequest struct { CodeList []string `json:"codeList"` - Namespace string `json:"namespace,omitempty"` + Namespace *string `json:"namespace,omitempty"` } type UpdateRoleRequest struct { - Code string `json:"code"` - NewCode string `json:"newCode,omitempty"` - Namespace string `json:"namespace,omitempty"` - Description string `json:"description,omitempty"` - ParentCode string `json:"parent,omitempty"` + Code string `json:"code"` + NewCode *string `json:"newCode,omitempty"` + Namespace *string `json:"namespace,omitempty"` + Description *string `json:"description,omitempty"` + ParentCode *string `json:"parent,omitempty"` } type RoleDetailRequest struct { - Code string `json:"code"` - Namespace string `json:"namespace,omitempty"` + Code string `json:"code"` + Namespace *string `json:"namespace,omitempty"` } type AssignAndRevokeRoleRequest struct { RoleCodes []string `json:"roleCodes"` - Namespace string `json:"namespace,omitempty"` + Namespace *string `json:"namespace,omitempty"` UserIds []string `json:"userIds"` } diff --git a/lib/model/user_model.go b/lib/model/user_model.go index 48d6a07..d782b06 100644 --- a/lib/model/user_model.go +++ b/lib/model/user_model.go @@ -1,94 +1,93 @@ package model import ( - "github.com/Authing/authing-go-sdk/lib/constant" "time" ) type CreateUserInput struct { - Username *string `json:"username"` - Email *string `json:"email"` - EmailVerified *bool `json:"emailVerified"` - Phone *string `json:"phone"` - PhoneVerified *bool `json:"phoneVerified"` - Unionid *string `json:"unionid"` - Openid *string `json:"openid"` - Nickname *string `json:"nickname"` - Photo *string `json:"photo"` - Password *string `json:"password"` - RegisterSource []string `json:"registerSource"` - Browser *string `json:"browser"` - Oauth *string `json:"oauth"` - LoginsCount *int64 `json:"loginsCount"` - LastLogin *string `json:"lastLogin"` - Company *string `json:"company"` - LastIP *string `json:"lastIP"` - SignedUp *string `json:"signedUp"` - Blocked *bool `json:"blocked"` - IsDeleted *bool `json:"isDeleted"` - Device *string `json:"device"` - Name *string `json:"name"` - GivenName *string `json:"givenName"` - FamilyName *string `json:"familyName"` - MiddleName *string `json:"middleName"` - Profile *string `json:"profile"` - PreferredUsername *string `json:"preferredUsername"` - Website *string `json:"website"` - Gender *string `json:"gender"` - Birthdate *string `json:"birthdate"` - Zoneinfo *string `json:"zoneinfo"` - Locale *string `json:"locale"` - Address *string `json:"address"` - Formatted *string `json:"formatted"` - StreetAddress *string `json:"streetAddress"` - Locality *string `json:"locality"` - Region *string `json:"region"` - PostalCode *string `json:"postalCode"` - Country *string `json:"country"` - ExternalId *string `json:"externalId"` + Username *string `json:"username,omitempty"` + Email *string `json:"email,omitempty"` + EmailVerified *bool `json:"emailVerified,omitempty"` + Phone *string `json:"phone,omitempty"` + PhoneVerified *bool `json:"phoneVerified,omitempty"` + Unionid *string `json:"unionid,omitempty"` + Openid *string `json:"openid,omitempty"` + Nickname *string `json:"nickname,omitempty"` + Photo *string `json:"photo,omitempty"` + Password *string `json:"password,omitempty"` + RegisterSource []string `json:"registerSource,omitempty"` + Browser *string `json:"browser,omitempty"` + Oauth *string `json:"oauth,omitempty"` + LoginsCount *int64 `json:"loginsCount,omitempty"` + LastLogin *string `json:"lastLogin,omitempty"` + Company *string `json:"company,omitempty"` + LastIP *string `json:"lastIP,omitempty"` + SignedUp *string `json:"signedUp,omitempty"` + Blocked *bool `json:"blocked,omitempty"` + IsDeleted *bool `json:"isDeleted,omitempty"` + Device *string `json:"device,omitempty"` + Name *string `json:"name,omitempty"` + GivenName *string `json:"givenName,omitempty"` + FamilyName *string `json:"familyName,omitempty"` + MiddleName *string `json:"middleName,omitempty"` + Profile *string `json:"profile,omitempty"` + PreferredUsername *string `json:"preferredUsername,omitempty"` + Website *string `json:"website,omitempty"` + Gender *string `json:"gender,omitempty"` + Birthdate *string `json:"birthdate,omitempty"` + Zoneinfo *string `json:"zoneinfo,omitempty"` + Locale *string `json:"locale,omitempty"` + Address *string `json:"address,omitempty"` + Formatted *string `json:"formatted,omitempty"` + StreetAddress *string `json:"streetAddress,omitempty"` + Locality *string `json:"locality,omitempty"` + Region *string `json:"region,omitempty"` + PostalCode *string `json:"postalCode,omitempty"` + Country *string `json:"country,omitempty"` + ExternalId *string `json:"externalId,omitempty"` } type UpdateUserInput struct { - Email *string `json:"email"` - Unionid *string `json:"unionid"` - Openid *string `json:"openid"` - EmailVerified *bool `json:"emailVerified"` - Phone *string `json:"phone"` - PhoneVerified *bool `json:"phoneVerified"` - Username *string `json:"username"` - Nickname *string `json:"nickname"` - Password *string `json:"password"` - Photo *string `json:"photo"` - Company *string `json:"company"` - Browser *string `json:"browser"` - Device *string `json:"device"` - Oauth *string `json:"oauth"` - TokenExpiredAt *string `json:"tokenExpiredAt"` - LoginsCount *int64 `json:"loginsCount"` - LastLogin *string `json:"lastLogin"` - LastIP *string `json:"lastIP"` - Blocked *bool `json:"blocked"` - Name *string `json:"name"` - GivenName *string `json:"givenName"` - FamilyName *string `json:"familyName"` - MiddleName *string `json:"middleName"` - Profile *string `json:"profile"` + Email *string `json:"email,omitempty"` + Unionid *string `json:"unionid,omitempty"` + Openid *string `json:"openid,omitempty"` + EmailVerified *bool `json:"emailVerified,omitempty"` + Phone *string `json:"phone,omitempty"` + PhoneVerified *bool `json:"phoneVerified,omitempty"` + Username *string `json:"username,omitempty"` + Nickname *string `json:"nickname,omitempty"` + Password *string `json:"password,omitempty"` + Photo *string `json:"photo,omitempty"` + Company *string `json:"company,omitempty"` + Browser *string `json:"browser,omitempty"` + Device *string `json:"device,omitempty"` + Oauth *string `json:"oauth,omitempty"` + TokenExpiredAt *string `json:"tokenExpiredAt,omitempty"` + LoginsCount *int64 `json:"loginsCount,omitempty"` + LastLogin *string `json:"lastLogin,omitempty"` + LastIP *string `json:"lastIP,omitempty"` + Blocked *bool `json:"blocked,omitempty"` + Name *string `json:"name,omitempty"` + GivenName *string `json:"givenName,omitempty"` + FamilyName *string `json:"familyName,omitempty"` + MiddleName *string `json:"middleName,omitempty"` + Profile *string `json:"profile,omitempty"` PreferredUsername *string `json:"preferredUsername"` - Website *string `json:"website"` - Gender *string `json:"gender"` - Birthdate *string `json:"birthdate"` - Zoneinfo *string `json:"zoneinfo"` - Locale *string `json:"locale"` - Address *string `json:"address"` - Formatted *string `json:"formatted"` - StreetAddress *string `json:"streetAddress"` - Locality *string `json:"locality"` - Region *string `json:"region"` - PostalCode *string `json:"postalCode"` - City *string `json:"city"` - Province *string `json:"province"` - Country *string `json:"country"` - ExternalId *string `json:"externalId"` + Website *string `json:"website,omitempty"` + Gender *string `json:"gender,omitempty"` + Birthdate *string `json:"birthdate,omitempty"` + Zoneinfo *string `json:"zoneinfo,omitempty"` + Locale *string `json:"locale,omitempty"` + Address *string `json:"address,omitempty"` + Formatted *string `json:"formatted,omitempty"` + StreetAddress *string `json:"streetAddress,omitempty"` + Locality *string `json:"locality,omitempty"` + Region *string `json:"region,omitempty"` + PostalCode *string `json:"postalCode,omitempty"` + City *string `json:"city,omitempty"` + Province *string `json:"province,omitempty"` + Country *string `json:"country,omitempty"` + ExternalId *string `json:"externalId,omitempty"` } type User struct { @@ -151,27 +150,27 @@ type User struct { } type UserCustomData struct { - Key string `json:"key"` - Value *string `json:"value"` - Label *string `json:"label"` - DataType EnumUDFDataType `json:"dataType"` + Key string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` + Label *string `json:"label,omitempty"` + DataType EnumUDFDataType `json:"dataType,omitempty"` } type UserDdfInput struct { - Key string `json:"key"` - Value string `json:"value"` + Key string `json:"key,omitempty"` + Value string `json:"value,omitempty"` } type UserDefinedData struct { - Key string `json:"key"` - DataType EnumUDFDataType `json:"dataType"` - Value string `json:"value"` - Label *string `json:"label"` + Key string `json:"key,omitempty"` + DataType EnumUDFDataType `json:"dataType,omitempty"` + Value string `json:"value,omitempty"` + Label *string `json:"label,omitempty"` } type UserDefinedDataInput struct { - Key string `json:"key"` - Value *string `json:"value"` + Key string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` } type UserDefinedDataMap struct { @@ -188,9 +187,9 @@ type UserDefinedField struct { } type CreateUserRequest struct { - UserInfo CreateUserInput `json:"userInfo"` - KeepPassword bool `json:"keepPassword"` - CustomData []KeyValuePair `json:"params"` + UserInfo CreateUserInput `json:"userInfo,omitempty"` + KeepPassword bool `json:"keepPassword,omitempty"` + CustomData []KeyValuePair `json:"params,omitempty"` } type CommonPageUsersResponse struct { @@ -199,20 +198,20 @@ type CommonPageUsersResponse struct { } type FindUserRequest struct { - Email string `json:"email"` - Username string `json:"username"` - Phone string `json:"phone"` - ExternalId string `json:"externalId"` - WithCustomData bool `json:"withCustomData"` + Email *string `json:"email,omitempty"` + Username *string `json:"username,omitempty"` + Phone *string `json:"phone,omitempty"` + ExternalId *string `json:"externalId,omitempty"` + WithCustomData bool `json:"withCustomData,omitempty"` } type SearchUserRequest struct { - Query string `json:"query"` - Page int `json:"page"` - Limit int `json:"limit"` - DepartmentOpts []string `json:"departmentOpts"` - GroupOpts []string `json:"groupOpts"` - RoleOpts []string `json:"roleOpts"` + Query string `json:"query"` + Page int `json:"page"` + Limit int `json:"limit"` + DepartmentOpts *[]string `json:"departmentOpts,omitempty"` + GroupOpts *[]string `json:"groupOpts,omitempty"` + RoleOpts *[]string `json:"roleOpts,omitempty"` WithCustomData bool } @@ -225,7 +224,7 @@ type GetUserGroupsResponse struct { type GetUserRolesRequest struct { Id string `json:"id"` - Namespace string `json:"namespace"` + Namespace string `json:"namespace,omitempty"` } type GetUserRolesResponse struct { @@ -269,7 +268,7 @@ type ListUserOrgResponse struct { } type ListUserAuthResourceRequest struct { - Id string `json:"id"` - Namespace string `json:"namespace"` - ResourceType constant.ResourceTypeEnum `json:"resourceType"` + Id string `json:"id"` + Namespace string `json:"namespace"` + ResourceType EnumResourceType `json:"resourceType"` } diff --git a/lib/model/vo_model.go b/lib/model/vo_model.go index 4d1326e..60a140c 100644 --- a/lib/model/vo_model.go +++ b/lib/model/vo_model.go @@ -1,7 +1,9 @@ package model import ( + "github.com/Authing/authing-go-sdk/lib/constant" "github.com/Authing/authing-go-sdk/lib/enum" + "time" ) type ListMemberRequest struct { @@ -109,21 +111,6 @@ type OidcParams struct { CodeChallenge string } -type OrgNode struct { - Id string `json:"id"` - OrgId *string `json:"orgId"` - CreatedAt *string `json:"createdAt"` - UpdatedAt *string `json:"updatedAt"` - UserPoolId *string `json:"userPoolId"` - Name string `json:"name"` - Description *string `json:"description"` - DescriptionI18n *string `json:"descriptionI18n"` - Order *int64 `json:"order"` - Code *string `json:"code"` - Members []User `json:"members"` - Children []OrgNode `json:"children"` -} - type GetUserDepartmentsRequest struct { Id string `json:"id"` OrgId *string `json:"orgId"` @@ -179,9 +166,9 @@ type ListPoliciesOnIdRequest struct { Limit int `json:"limit"` } -type ListUserAuthorizedResourcesRequest struct { - UserId string `json:"id"` - Namespace string `json:"namespace"` +type ListAuthorizedResourcesByIdRequest struct { + Id string `json:"id"` + Namespace string `json:"namespace,omitempty"` ResourceType *string `json:"resourceType"` } @@ -233,3 +220,189 @@ type GetAuthorizedResourcesOfResourceKindRequest struct { Namespace string `json:"namespace"` Resource string `json:"resource"` } + +type ListAuthorizedResourcesRequest struct { + TargetIdentifier string `json:"targetIdentifier"` + Namespace string `json:"namespace"` + TargetType constant.ResourceTargetTypeEnum `json:"targetType"` + ResourceType *EnumResourceType `json:"resourceType"` +} + +type ProgrammaticAccessAccount struct { + AppId string `json:"appId"` + Secret string `json:"secret"` + TokenLifetime int `json:"tokenLifetime"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + Id string `json:"id"` + Remarks string `json:"remarks"` + UserId string `json:"userId"` + Enabled bool `json:"enabled"` +} + +type ListResourceRequest struct { + Namespace string `json:"namespace"` + ResourceType EnumResourceType `json:"resourceType,omitempty"` + Page int `json:"page"` + Limit int `json:"limit"` +} +type ActionsModel struct { + Name string `json:"name"` + Description string `json:"description"` +} +type Resource struct { + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserPoolId string `json:"userPoolId"` + Code string `json:"code"` + Actions []ActionsModel `json:"actions"` + Type string `json:"type"` + Description string `json:"description"` + NamespaceId int `json:"namespaceId"` + ApiIdentifier *string `json:"apiIdentifier"` + Namespace string `json:"namespace,omitempty"` +} +type ResourceResponse struct { + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserPoolId string `json:"userPoolId"` + Code string `json:"code"` + Actions []ActionsModel `json:"actions"` + Type string `json:"type"` + Description string `json:"description"` + NamespaceId int `json:"namespaceId"` + ApiIdentifier *string `json:"apiIdentifier"` +} + +type ListNamespaceResourceResponse struct { + List []Resource `json:"list"` + TotalCount int `json:"totalCount"` +} + +type CreateResourceRequest struct { + Code string `json:"code"` + Actions []ActionsModel `json:"actions,omitempty"` + Type string `json:"type,omitempty"` + Description *string `json:"description,omitempty"` + ApiIdentifier *string `json:"apiIdentifier,omitempty"` + Namespace string `json:"namespace,omitempty"` +} + +type UpdateResourceRequest struct { + Actions []ActionsModel `json:"actions,omitempty"` + Type string `json:"type,omitempty"` + Description *string `json:"description,omitempty"` + ApiIdentifier *string `json:"apiIdentifier,omitempty"` + Namespace string `json:"namespace,omitempty"` +} + +type ApplicationAccessPolicies struct { + AssignedAt time.Time `json:"assignedAt"` + InheritByChildren interface{} `json:"inheritByChildren"` + Enabled bool `json:"enabled"` + PolicyId string `json:"policyId"` + Code string `json:"code"` + Policy struct { + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserPoolId string `json:"userPoolId"` + IsDefault bool `json:"isDefault"` + IsAuto bool `json:"isAuto"` + Hidden bool `json:"hidden"` + Code string `json:"code"` + Description string `json:"description"` + Statements []struct { + Resource string `json:"resource"` + Actions []string `json:"actions"` + Effect string `json:"effect"` + Condition []interface{} `json:"condition"` + ResourceType EnumResourceType `json:"resourceType"` + } `json:"statements"` + NamespaceId int `json:"namespaceId"` + } `json:"policy"` + TargetNamespace string `json:"targetNamespace"` + TargetType string `json:"targetType"` + TargetIdentifier string `json:"targetIdentifier"` + Target struct { + Id string `json:"id"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + UserPoolId string `json:"userPoolId"` + Code string `json:"code"` + Description string `json:"description"` + ParentCode string `json:"parentCode"` + IsSystem bool `json:"isSystem"` + NamespaceId int `json:"namespaceId"` + } `json:"target"` + Namespace string `json:"namespace"` +} + +type GetApplicationAccessPoliciesResponse struct { + List []ApplicationAccessPolicies `json:"list"` + TotalCount int `json:"totalCount"` +} + +type ApplicationAccessPoliciesRequest struct { + TargetIdentifiers []string `json:"targetIdentifiers,omitempty"` + TargetType constant.ResourceTargetTypeEnum `json:"targetType,omitempty"` + Namespace string `json:"namespace,omitempty"` + InheritByChildren bool `json:"inheritByChildren,omitempty"` +} + +type GetAuthorizedTargetsRequest struct { + TargetType constant.ResourceTargetTypeEnum `json:"targetType"` + Namespace string `json:"namespace"` + Resource string `json:"resource"` + ResourceType EnumResourceType `json:"resourceType"` + Actions *struct { + Op constant.GetAuthorizedTargetsOpt `json:"op,omitempty"` + List []string `json:"list,omitempty"` + } `json:"actions,omitempty"` +} + +type ListAuditLogsRequest struct { + ClientIp *string `json:"clientip,omitempty"` + OperationNames *[]string `json:"operation_name,omitempty"` + UserIds *[]string `json:"operator_arn,omitempty"` + AppIds *[]string `json:"app_id,omitempty"` + Page *int `json:"page,omitempty"` + Limit *int `json:"limit,omitempty"` +} + +type ListUserActionRequest struct { + ClientIp *string `json:"clientip,omitempty"` + OperationNames *[]string `json:"operation_name,omitempty"` + UserIds *[]string `json:"operator_arn,omitempty"` + Page *int `json:"page,omitempty"` + Limit *int `json:"limit,omitempty"` +} + +type CheckLoginStatusResponse struct { + Code int `json:"code"` + Message string `json:"message"` + Status bool `json:"status"` + Exp int `json:"exp"` + Iat int `json:"iat"` + Data struct { + Id string `json:"id"` + UserPoolId string `json:"userPoolId"` + Arn string `json:"arn"` + } `json:"data"` +} + +type SetUdfInput struct { + TargetType EnumUDFTargetType `json:"targetType"` + Key string `json:"key"` + DataType EnumUDFDataType `json:"dataType"` + Label string `json:"label"` +} + +type PrincipalAuthenticateRequest struct { + Type constant.PrincipalAuthenticateType `json:"type"` + Name string `json:"name"` + IdCard string `json:"idCard"` + Ext string `json:"ext"` +}