Browse Source

flatten the packages

master v0.0.1
Nicolas Massé 5 years ago
parent
commit
51adea5521
  1. 64
      README.md
  2. 2
      attack_detection.go
  3. 43
      authentication_management.go
  4. 23
      client_attribute_certificate.go
  5. 11
      client_initial_access.go
  6. 7
      client_registration_policy.go
  7. 13
      client_role_mappings.go
  8. 25
      clients.go
  9. 15
      components.go
  10. 9
      credentials.go
  11. 2
      definitions.go
  12. 25
      groups.go
  13. 15
      identity_providers.go
  14. 3
      integration/integration-tests.go
  15. 33
      keycloak_client.go
  16. 19
      realm.go
  17. 11
      recovery_code.go
  18. 17
      roles.go
  19. 33
      users.go

64
README.md

@ -1,13 +1,61 @@
## Basic keycloak client in go # Golang Keycloak REST Client
This repo provides a basic keycloak client in go. This Golang library provides Types and Methods to drive a Keycloak instance through its REST Admin interface.
## Compile from sources ## Supported Features
* **Realms**: CRUD, Export, Import
* **Clients**: CRU
* **Users**: CRUD
* **Components**: CRUD
## Hello, World example
Create a directory for your project, initialize the Go module.
```sh ```sh
GO111MODULE=on go get github.com/golang/mock/mockgen@v1.4.4 mkdir kc-test
cd toolbox cd kc-test
go generate go mod init foo/bar
cd .. ```
go test ./...
**main.go**:
```go
package main
import (
"fmt"
"log"
"time"
keycloak "github.com/nmasse-itix/keycloak-client"
)
func main() {
config := keycloak.Config{
AddrTokenProvider: "http://localhost:8080/auth/realm/master",
AddrAPI: "http://localhost:8080/auth",
Timeout: 10 * time.Second,
}
client, err := keycloak.NewClient(config)
if err != nil {
log.Fatalf("could not create keycloak client: %v", err)
}
accessToken, err := client.GetToken("master", "admin", "admin")
if err != nil {
log.Fatalf("could not get access token: %v", err)
}
realms, err := client.GetRealms(accessToken)
if err != nil {
log.Fatalf("could not get realms: %v", err)
}
for _, realm := range realms {
fmt.Println(*realm.Realm)
}
}
``` ```

2
api/attack_detection.go → attack_detection.go

@ -1,4 +1,4 @@
package api package keycloak
import ( import (
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"

43
api/authentication_management.go → authentication_management.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -28,21 +27,21 @@ func (c *Client) GetClientAuthenticatorProviders(accessToken string, realmName s
} }
// GetAuthenticatorProviderConfig returns the authenticator provider’s configuration description. // GetAuthenticatorProviderConfig returns the authenticator provider’s configuration description.
func (c *Client) GetAuthenticatorProviderConfig(accessToken string, realmName, providerID string) (keycloak.AuthenticatorConfigInfoRepresentation, error) { func (c *Client) GetAuthenticatorProviderConfig(accessToken string, realmName, providerID string) (AuthenticatorConfigInfoRepresentation, error) {
var resp = keycloak.AuthenticatorConfigInfoRepresentation{} var resp = AuthenticatorConfigInfoRepresentation{}
var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/config-description/:providerID"), url.Param("realm", realmName), url.Param("providerID", providerID)) var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/config-description/:providerID"), url.Param("realm", realmName), url.Param("providerID", providerID))
return resp, err return resp, err
} }
// GetAuthenticatorConfig returns the authenticator configuration. // GetAuthenticatorConfig returns the authenticator configuration.
func (c *Client) GetAuthenticatorConfig(accessToken string, realmName, configID string) (keycloak.AuthenticatorConfigRepresentation, error) { func (c *Client) GetAuthenticatorConfig(accessToken string, realmName, configID string) (AuthenticatorConfigRepresentation, error) {
var resp = keycloak.AuthenticatorConfigRepresentation{} var resp = AuthenticatorConfigRepresentation{}
var err = c.get(accessToken, &resp, url.Path(authenticationConfigPath), url.Param("realm", realmName), url.Param("id", configID)) var err = c.get(accessToken, &resp, url.Path(authenticationConfigPath), url.Param("realm", realmName), url.Param("id", configID))
return resp, err return resp, err
} }
// UpdateAuthenticatorConfig updates the authenticator configuration. // UpdateAuthenticatorConfig updates the authenticator configuration.
func (c *Client) UpdateAuthenticatorConfig(accessToken string, realmName, configID string, config keycloak.AuthenticatorConfigRepresentation) error { func (c *Client) UpdateAuthenticatorConfig(accessToken string, realmName, configID string, config AuthenticatorConfigRepresentation) error {
return c.put(accessToken, url.Path(authenticationConfigPath), url.Param("realm", realmName), url.Param("id", configID), body.JSON(config)) return c.put(accessToken, url.Path(authenticationConfigPath), url.Param("realm", realmName), url.Param("id", configID), body.JSON(config))
} }
@ -52,7 +51,7 @@ func (c *Client) DeleteAuthenticatorConfig(accessToken string, realmName, config
} }
// CreateAuthenticationExecution add new authentication execution // CreateAuthenticationExecution add new authentication execution
func (c *Client) CreateAuthenticationExecution(accessToken string, realmName string, authExec keycloak.AuthenticationExecutionRepresentation) (string, error) { func (c *Client) CreateAuthenticationExecution(accessToken string, realmName string, authExec AuthenticationExecutionRepresentation) (string, error) {
return c.post(accessToken, nil, url.Path(authenticationManagementPath+"/executions"), url.Param("realm", realmName), body.JSON(authExec)) return c.post(accessToken, nil, url.Path(authenticationManagementPath+"/executions"), url.Param("realm", realmName), body.JSON(authExec))
} }
@ -62,7 +61,7 @@ func (c *Client) DeleteAuthenticationExecution(accessToken string, realmName, ex
} }
// UpdateAuthenticationExecution update execution with new configuration. // UpdateAuthenticationExecution update execution with new configuration.
func (c *Client) UpdateAuthenticationExecution(accessToken string, realmName, executionID string, authConfig keycloak.AuthenticatorConfigRepresentation) error { func (c *Client) UpdateAuthenticationExecution(accessToken string, realmName, executionID string, authConfig AuthenticatorConfigRepresentation) error {
_, err := c.post(accessToken, nil, url.Path(authenticationManagementPath+"/executions/:id/config"), url.Param("realm", realmName), url.Param("id", executionID), body.JSON(authConfig)) _, err := c.post(accessToken, nil, url.Path(authenticationManagementPath+"/executions/:id/config"), url.Param("realm", realmName), url.Param("id", executionID), body.JSON(authConfig))
return err return err
} }
@ -80,14 +79,14 @@ func (c *Client) RaiseExecutionPriority(accessToken string, realmName, execution
} }
// CreateAuthenticationFlow creates a new authentication flow. // CreateAuthenticationFlow creates a new authentication flow.
func (c *Client) CreateAuthenticationFlow(accessToken string, realmName string, authFlow keycloak.AuthenticationFlowRepresentation) error { func (c *Client) CreateAuthenticationFlow(accessToken string, realmName string, authFlow AuthenticationFlowRepresentation) error {
_, err := c.post(accessToken, nil, url.Path(authenticationManagementPath+"/flows"), url.Param("realm", realmName), body.JSON(authFlow)) _, err := c.post(accessToken, nil, url.Path(authenticationManagementPath+"/flows"), url.Param("realm", realmName), body.JSON(authFlow))
return err return err
} }
// GetAuthenticationFlows returns a list of authentication flows. // GetAuthenticationFlows returns a list of authentication flows.
func (c *Client) GetAuthenticationFlows(accessToken string, realmName string) ([]keycloak.AuthenticationFlowRepresentation, error) { func (c *Client) GetAuthenticationFlows(accessToken string, realmName string) ([]AuthenticationFlowRepresentation, error) {
var resp = []keycloak.AuthenticationFlowRepresentation{} var resp = []AuthenticationFlowRepresentation{}
var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/flows"), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/flows"), url.Param("realm", realmName))
return resp, err return resp, err
} }
@ -102,14 +101,14 @@ func (c *Client) CopyExistingAuthenticationFlow(accessToken string, realmName, f
} }
// GetAuthenticationExecutionForFlow returns the authentication executions for a flow. // GetAuthenticationExecutionForFlow returns the authentication executions for a flow.
func (c *Client) GetAuthenticationExecutionForFlow(accessToken string, realmName, flowAlias string) (keycloak.AuthenticationExecutionInfoRepresentation, error) { func (c *Client) GetAuthenticationExecutionForFlow(accessToken string, realmName, flowAlias string) (AuthenticationExecutionInfoRepresentation, error) {
var resp = keycloak.AuthenticationExecutionInfoRepresentation{} var resp = AuthenticationExecutionInfoRepresentation{}
var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/flows/:flowAlias/executions"), url.Param("realm", realmName), url.Param("flowAlias", flowAlias)) var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/flows/:flowAlias/executions"), url.Param("realm", realmName), url.Param("flowAlias", flowAlias))
return resp, err return resp, err
} }
// UpdateAuthenticationExecutionForFlow updates the authentication executions of a flow. // UpdateAuthenticationExecutionForFlow updates the authentication executions of a flow.
func (c *Client) UpdateAuthenticationExecutionForFlow(accessToken string, realmName, flowAlias string, authExecInfo keycloak.AuthenticationExecutionInfoRepresentation) error { func (c *Client) UpdateAuthenticationExecutionForFlow(accessToken string, realmName, flowAlias string, authExecInfo AuthenticationExecutionInfoRepresentation) error {
return c.put(accessToken, url.Path(authenticationManagementPath+"/flows/:flowAlias/executions"), url.Param("realm", realmName), url.Param("flowAlias", flowAlias), body.JSON(authExecInfo)) return c.put(accessToken, url.Path(authenticationManagementPath+"/flows/:flowAlias/executions"), url.Param("realm", realmName), url.Param("flowAlias", flowAlias), body.JSON(authExecInfo))
} }
@ -128,8 +127,8 @@ func (c *Client) CreateFlowWithExecutionForExistingFlow(accessToken string, real
} }
// GetAuthenticationFlow gets the authentication flow for id. // GetAuthenticationFlow gets the authentication flow for id.
func (c *Client) GetAuthenticationFlow(accessToken string, realmName, flowID string) (keycloak.AuthenticationFlowRepresentation, error) { func (c *Client) GetAuthenticationFlow(accessToken string, realmName, flowID string) (AuthenticationFlowRepresentation, error) {
var resp = keycloak.AuthenticationFlowRepresentation{} var resp = AuthenticationFlowRepresentation{}
var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/flows/:id"), url.Param("realm", realmName), url.Param("id", flowID)) var err = c.get(accessToken, &resp, url.Path(authenticationManagementPath+"/flows/:id"), url.Param("realm", realmName), url.Param("id", flowID))
return resp, err return resp, err
} }
@ -168,21 +167,21 @@ func (c *Client) RegisterRequiredAction(accessToken string, realmName, providerI
} }
// GetRequiredActions returns a list of required actions. // GetRequiredActions returns a list of required actions.
func (c *Client) GetRequiredActions(accessToken string, realmName string) ([]keycloak.RequiredActionProviderRepresentation, error) { func (c *Client) GetRequiredActions(accessToken string, realmName string) ([]RequiredActionProviderRepresentation, error) {
var resp = []keycloak.RequiredActionProviderRepresentation{} var resp = []RequiredActionProviderRepresentation{}
var err = c.get(accessToken, &resp, url.Path(authenticationRequiredActionsPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(authenticationRequiredActionsPath), url.Param("realm", realmName))
return resp, err return resp, err
} }
// GetRequiredAction returns the required action for the alias. // GetRequiredAction returns the required action for the alias.
func (c *Client) GetRequiredAction(accessToken string, realmName, actionAlias string) (keycloak.RequiredActionProviderRepresentation, error) { func (c *Client) GetRequiredAction(accessToken string, realmName, actionAlias string) (RequiredActionProviderRepresentation, error) {
var resp = keycloak.RequiredActionProviderRepresentation{} var resp = RequiredActionProviderRepresentation{}
var err = c.get(accessToken, &resp, url.Path(authenticationRequiredActionPath), url.Param("realm", realmName), url.Param("alias", actionAlias)) var err = c.get(accessToken, &resp, url.Path(authenticationRequiredActionPath), url.Param("realm", realmName), url.Param("alias", actionAlias))
return resp, err return resp, err
} }
// UpdateRequiredAction updates the required action. // UpdateRequiredAction updates the required action.
func (c *Client) UpdateRequiredAction(accessToken string, realmName, actionAlias string, action keycloak.RequiredActionProviderRepresentation) error { func (c *Client) UpdateRequiredAction(accessToken string, realmName, actionAlias string, action RequiredActionProviderRepresentation) error {
return c.put(accessToken, url.Path(authenticationRequiredActionPath), url.Param("realm", realmName), url.Param("alias", actionAlias), body.JSON(action)) return c.put(accessToken, url.Path(authenticationRequiredActionPath), url.Param("realm", realmName), url.Param("alias", actionAlias), body.JSON(action))
} }

23
api/client_attribute_certificate.go → client_attribute_certificate.go

@ -1,9 +1,8 @@
package api package keycloak
import ( import (
"bytes" "bytes"
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -13,43 +12,43 @@ const (
) )
// GetKeyInfo returns the key info. idClient is the id of client (not client-id). // GetKeyInfo returns the key info. idClient is the id of client (not client-id).
func (c *Client) GetKeyInfo(accessToken string, realmName, idClient, attr string) (keycloak.CertificateRepresentation, error) { func (c *Client) GetKeyInfo(accessToken string, realmName, idClient, attr string) (CertificateRepresentation, error) {
var resp = keycloak.CertificateRepresentation{} var resp = CertificateRepresentation{}
var err = c.get(accessToken, &resp, url.Path(clientAttrCertPath), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr)) var err = c.get(accessToken, &resp, url.Path(clientAttrCertPath), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr))
return resp, err return resp, err
} }
// GetKeyStore returns a keystore file for the client, containing private key and public certificate. idClient is the id of client (not client-id). // GetKeyStore returns a keystore file for the client, containing private key and public certificate. idClient is the id of client (not client-id).
func (c *Client) GetKeyStore(accessToken string, realmName, idClient, attr string, keyStoreConfig keycloak.KeyStoreConfig) ([]byte, error) { func (c *Client) GetKeyStore(accessToken string, realmName, idClient, attr string, keyStoreConfig KeyStoreConfig) ([]byte, error) {
var resp = []byte{} var resp = []byte{}
_, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/download"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.JSON(keyStoreConfig)) _, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/download"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.JSON(keyStoreConfig))
return resp, err return resp, err
} }
// GenerateCertificate generates a new certificate with new key pair. idClient is the id of client (not client-id). // GenerateCertificate generates a new certificate with new key pair. idClient is the id of client (not client-id).
func (c *Client) GenerateCertificate(accessToken string, realmName, idClient, attr string) (keycloak.CertificateRepresentation, error) { func (c *Client) GenerateCertificate(accessToken string, realmName, idClient, attr string) (CertificateRepresentation, error) {
var resp = keycloak.CertificateRepresentation{} var resp = CertificateRepresentation{}
_, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/generate"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr)) _, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/generate"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr))
return resp, err return resp, err
} }
// GenerateKeyPairAndCertificate generates a keypair and certificate and serves the private key in a specified keystore format. // GenerateKeyPairAndCertificate generates a keypair and certificate and serves the private key in a specified keystore format.
func (c *Client) GenerateKeyPairAndCertificate(accessToken string, realmName, idClient, attr string, keyStoreConfig keycloak.KeyStoreConfig) ([]byte, error) { func (c *Client) GenerateKeyPairAndCertificate(accessToken string, realmName, idClient, attr string, keyStoreConfig KeyStoreConfig) ([]byte, error) {
var resp = []byte{} var resp = []byte{}
_, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/generate-and-download"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.JSON(keyStoreConfig)) _, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/generate-and-download"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.JSON(keyStoreConfig))
return resp, err return resp, err
} }
// UploadCertificatePrivateKey uploads a certificate and eventually a private key. // UploadCertificatePrivateKey uploads a certificate and eventually a private key.
func (c *Client) UploadCertificatePrivateKey(accessToken string, realmName, idClient, attr string, file []byte) (keycloak.CertificateRepresentation, error) { func (c *Client) UploadCertificatePrivateKey(accessToken string, realmName, idClient, attr string, file []byte) (CertificateRepresentation, error) {
var resp = keycloak.CertificateRepresentation{} var resp = CertificateRepresentation{}
_, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/upload"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.Reader(bytes.NewReader(file))) _, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/upload"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.Reader(bytes.NewReader(file)))
return resp, err return resp, err
} }
// UploadCertificate uploads only a certificate, not the private key. // UploadCertificate uploads only a certificate, not the private key.
func (c *Client) UploadCertificate(accessToken string, realmName, idClient, attr string, file []byte) (keycloak.CertificateRepresentation, error) { func (c *Client) UploadCertificate(accessToken string, realmName, idClient, attr string, file []byte) (CertificateRepresentation, error) {
var resp = keycloak.CertificateRepresentation{} var resp = CertificateRepresentation{}
_, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/upload-certificate"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.Reader(bytes.NewReader(file))) _, err := c.post(accessToken, &resp, url.Path(clientAttrCertPath+"/upload-certificate"), url.Param("realm", realmName), url.Param("id", idClient), url.Param("attr", attr), body.Reader(bytes.NewReader(file)))
return resp, err return resp, err
} }

11
api/client_initial_access.go → client_initial_access.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -11,15 +10,15 @@ const (
) )
// CreateClientInitialAccess creates a new initial access token. // CreateClientInitialAccess creates a new initial access token.
func (c *Client) CreateClientInitialAccess(accessToken string, realmName string, access keycloak.ClientInitialAccessCreatePresentation) (keycloak.ClientInitialAccessPresentation, error) { func (c *Client) CreateClientInitialAccess(accessToken string, realmName string, access ClientInitialAccessCreatePresentation) (ClientInitialAccessPresentation, error) {
var resp = keycloak.ClientInitialAccessPresentation{} var resp = ClientInitialAccessPresentation{}
_, err := c.post(accessToken, &resp, nil, url.Path(clientInitialAccessPath), url.Param("realm", realmName), body.JSON(access)) _, err := c.post(accessToken, &resp, nil, url.Path(clientInitialAccessPath), url.Param("realm", realmName), body.JSON(access))
return resp, err return resp, err
} }
// GetClientInitialAccess returns a list of clients initial access. // GetClientInitialAccess returns a list of clients initial access.
func (c *Client) GetClientInitialAccess(accessToken string, realmName string) ([]keycloak.ClientInitialAccessPresentation, error) { func (c *Client) GetClientInitialAccess(accessToken string, realmName string) ([]ClientInitialAccessPresentation, error) {
var resp = []keycloak.ClientInitialAccessPresentation{} var resp = []ClientInitialAccessPresentation{}
var err = c.get(accessToken, &resp, url.Path(clientInitialAccessPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(clientInitialAccessPath), url.Param("realm", realmName))
return resp, err return resp, err
} }

7
api/client_registration_policy.go → client_registration_policy.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -10,8 +9,8 @@ const (
) )
// GetClientRegistrationPolicy is the base path to retrieve providers with the configProperties properly filled. // GetClientRegistrationPolicy is the base path to retrieve providers with the configProperties properly filled.
func (c *Client) GetClientRegistrationPolicy(accessToken string, realmName, configID string) ([]keycloak.ComponentTypeRepresentation, error) { func (c *Client) GetClientRegistrationPolicy(accessToken string, realmName, configID string) ([]ComponentTypeRepresentation, error) {
var resp = []keycloak.ComponentTypeRepresentation{} var resp = []ComponentTypeRepresentation{}
var err = c.get(accessToken, &resp, url.Path(clientRegistrationPolicyPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(clientRegistrationPolicyPath), url.Param("realm", realmName))
return resp, err return resp, err
} }

13
api/client_role_mappings.go → client_role_mappings.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -12,14 +11,14 @@ const (
) )
// AddClientRolesToUserRoleMapping add client-level roles to the user role mapping. // AddClientRolesToUserRoleMapping add client-level roles to the user role mapping.
func (c *Client) AddClientRolesToUserRoleMapping(accessToken string, realmName, userID, clientID string, roles []keycloak.RoleRepresentation) error { func (c *Client) AddClientRolesToUserRoleMapping(accessToken string, realmName, userID, clientID string, roles []RoleRepresentation) error {
_, err := c.post(accessToken, nil, url.Path(clientRoleMappingPath), url.Param("realm", realmName), url.Param("id", userID), url.Param("client", clientID), body.JSON(roles)) _, err := c.post(accessToken, nil, url.Path(clientRoleMappingPath), url.Param("realm", realmName), url.Param("id", userID), url.Param("client", clientID), body.JSON(roles))
return err return err
} }
// GetClientRoleMappings gets client-level role mappings for the user, and the app. // GetClientRoleMappings gets client-level role mappings for the user, and the app.
func (c *Client) GetClientRoleMappings(accessToken string, realmName, userID, clientID string) ([]keycloak.RoleRepresentation, error) { func (c *Client) GetClientRoleMappings(accessToken string, realmName, userID, clientID string) ([]RoleRepresentation, error) {
var resp = []keycloak.RoleRepresentation{} var resp = []RoleRepresentation{}
var err = c.get(accessToken, &resp, url.Path(clientRoleMappingPath), url.Param("realm", realmName), url.Param("id", userID), url.Param("client", clientID)) var err = c.get(accessToken, &resp, url.Path(clientRoleMappingPath), url.Param("realm", realmName), url.Param("id", userID), url.Param("client", clientID))
return resp, err return resp, err
} }
@ -30,8 +29,8 @@ func (c *Client) DeleteClientRolesFromUserRoleMapping(accessToken string, realmN
} }
// GetRealmLevelRoleMappings gets realm level role mappings // GetRealmLevelRoleMappings gets realm level role mappings
func (c *Client) GetRealmLevelRoleMappings(accessToken string, realmName, userID string) ([]keycloak.RoleRepresentation, error) { func (c *Client) GetRealmLevelRoleMappings(accessToken string, realmName, userID string) ([]RoleRepresentation, error) {
var resp = []keycloak.RoleRepresentation{} var resp = []RoleRepresentation{}
var err = c.get(accessToken, &resp, url.Path(realmRoleMappingPath), url.Param("realm", realmName), url.Param("id", userID)) var err = c.get(accessToken, &resp, url.Path(realmRoleMappingPath), url.Param("realm", realmName), url.Param("id", userID))
return resp, err return resp, err
} }

25
api/clients.go → clients.go

@ -1,9 +1,8 @@
package api package keycloak
import ( import (
"errors" "errors"
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -18,44 +17,44 @@ const (
// GetClients returns a list of clients belonging to the realm. // GetClients returns a list of clients belonging to the realm.
// Parameters: clientId (filter by clientId), // Parameters: clientId (filter by clientId),
// viewableOnly (filter clients that cannot be viewed in full by admin, default="false") // viewableOnly (filter clients that cannot be viewed in full by admin, default="false")
func (c *Client) GetClients(accessToken string, realmName string, paramKV ...string) ([]keycloak.ClientRepresentation, error) { func (c *Client) GetClients(accessToken string, realmName string, paramKV ...string) ([]ClientRepresentation, error) {
if len(paramKV)%2 != 0 { if len(paramKV)%2 != 0 {
return nil, errors.New(keycloak.MsgErrInvalidParam + "." + keycloak.EvenParams) return nil, errors.New(MsgErrInvalidParam + "." + EvenParams)
} }
var resp = []keycloak.ClientRepresentation{} var resp = []ClientRepresentation{}
var plugins = append(createQueryPlugins(paramKV...), url.Path(clientsPath), url.Param("realm", realmName)) var plugins = append(createQueryPlugins(paramKV...), url.Path(clientsPath), url.Param("realm", realmName))
var err = c.get(accessToken, &resp, plugins...) var err = c.get(accessToken, &resp, plugins...)
return resp, err return resp, err
} }
// GetClient get the representation of the client. idClient is the id of client (not client-id). // GetClient get the representation of the client. idClient is the id of client (not client-id).
func (c *Client) GetClient(accessToken string, realmName, idClient string) (keycloak.ClientRepresentation, error) { func (c *Client) GetClient(accessToken string, realmName, idClient string) (ClientRepresentation, error) {
var resp = keycloak.ClientRepresentation{} var resp = ClientRepresentation{}
var err = c.get(accessToken, &resp, url.Path(clientIDPath), url.Param("realm", realmName), url.Param("id", idClient)) var err = c.get(accessToken, &resp, url.Path(clientIDPath), url.Param("realm", realmName), url.Param("id", idClient))
return resp, err return resp, err
} }
// UpdateClient updates the client. idClient is the id of client (not client-id). // UpdateClient updates the client. idClient is the id of client (not client-id).
func (c *Client) UpdateClient(accessToken string, realmName, idClient string, clientRep keycloak.ClientRepresentation) error { func (c *Client) UpdateClient(accessToken string, realmName, idClient string, clientRep ClientRepresentation) error {
return c.put(accessToken, url.Path(clientIDPath), url.Param("realm", realmName), url.Param("id", idClient), body.JSON(clientRep)) return c.put(accessToken, url.Path(clientIDPath), url.Param("realm", realmName), url.Param("id", idClient), body.JSON(clientRep))
} }
// CreateClient creates a new client. // CreateClient creates a new client.
func (c *Client) CreateClient(accessToken string, realmName string, clientRep keycloak.ClientRepresentation) (string, error) { func (c *Client) CreateClient(accessToken string, realmName string, clientRep ClientRepresentation) (string, error) {
return c.post(accessToken, nil, url.Path(clientsPath), url.Param("realm", realmName), body.JSON(clientRep)) return c.post(accessToken, nil, url.Path(clientsPath), url.Param("realm", realmName), body.JSON(clientRep))
} }
// GetClientMappers gets mappers of the client specified by id // GetClientMappers gets mappers of the client specified by id
func (c *Client) GetClientMappers(accessToke string, realmName, idClient string) ([]keycloak.ClientMapperRepresentation, error) { func (c *Client) GetClientMappers(accessToke string, realmName, idClient string) ([]ClientMapperRepresentation, error) {
var resp = []keycloak.ClientMapperRepresentation{} var resp = []ClientMapperRepresentation{}
var err = c.get(accessToke, &resp, url.Path(clientMappersPath), url.Param("realm", realmName), url.Param("id", idClient)) var err = c.get(accessToke, &resp, url.Path(clientMappersPath), url.Param("realm", realmName), url.Param("id", idClient))
return resp, err return resp, err
} }
// GetSecret get the client secret. idClient is the id of client (not client-id). // GetSecret get the client secret. idClient is the id of client (not client-id).
func (c *Client) GetSecret(accessToken string, realmName, idClient string) (keycloak.CredentialRepresentation, error) { func (c *Client) GetSecret(accessToken string, realmName, idClient string) (CredentialRepresentation, error) {
var resp = keycloak.CredentialRepresentation{} var resp = CredentialRepresentation{}
var err = c.get(accessToken, &resp, url.Path(clientSecret), url.Param("realm", realmName), url.Param("id", idClient)) var err = c.get(accessToken, &resp, url.Path(clientSecret), url.Param("realm", realmName), url.Param("id", idClient))
return resp, err return resp, err
} }

15
api/components.go → components.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -12,26 +11,26 @@ const (
) )
// GetComponents gets all components of the realm // GetComponents gets all components of the realm
func (c *Client) GetComponents(accessToken string, realmName string) ([]keycloak.ComponentRepresentation, error) { func (c *Client) GetComponents(accessToken string, realmName string) ([]ComponentRepresentation, error) {
var resp = []keycloak.ComponentRepresentation{} var resp = []ComponentRepresentation{}
var err = c.get(accessToken, &resp, url.Path(componentsPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(componentsPath), url.Param("realm", realmName))
return resp, err return resp, err
} }
// GetComponent gets a component of the realm // GetComponent gets a component of the realm
func (c *Client) GetComponent(accessToken string, realmName string, componentID string) ([]keycloak.ComponentRepresentation, error) { func (c *Client) GetComponent(accessToken string, realmName string, componentID string) ([]ComponentRepresentation, error) {
var resp = []keycloak.ComponentRepresentation{} var resp = []ComponentRepresentation{}
var err = c.get(accessToken, &resp, url.Path(componentsByIDPath), url.Param("realm", realmName), url.Param("id", componentID)) var err = c.get(accessToken, &resp, url.Path(componentsByIDPath), url.Param("realm", realmName), url.Param("id", componentID))
return resp, err return resp, err
} }
// CreateComponent creates a new component in the realm // CreateComponent creates a new component in the realm
func (c *Client) CreateComponent(accessToken string, realmName string, component keycloak.ComponentRepresentation) (string, error) { func (c *Client) CreateComponent(accessToken string, realmName string, component ComponentRepresentation) (string, error) {
return c.post(accessToken, nil, url.Path(componentsPath), url.Param("realm", realmName), body.JSON(component)) return c.post(accessToken, nil, url.Path(componentsPath), url.Param("realm", realmName), body.JSON(component))
} }
// UpdateComponent updates a new component in the realm // UpdateComponent updates a new component in the realm
func (c *Client) UpdateComponent(accessToken string, realmName, componentID string, component keycloak.ComponentRepresentation) error { func (c *Client) UpdateComponent(accessToken string, realmName, componentID string, component ComponentRepresentation) error {
return c.put(accessToken, nil, url.Path(componentsPath), url.Param("realm", realmName), url.Param("id", componentID), body.JSON(component)) return c.put(accessToken, nil, url.Path(componentsPath), url.Param("realm", realmName), url.Param("id", componentID), body.JSON(component))
} }

9
api/credentials.go → credentials.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/headers" "gopkg.in/h2non/gentleman.v2/plugins/headers"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
@ -23,13 +22,13 @@ var (
) )
// ResetPassword resets password of the user. // ResetPassword resets password of the user.
func (c *Client) ResetPassword(accessToken string, realmName, userID string, cred keycloak.CredentialRepresentation) error { func (c *Client) ResetPassword(accessToken string, realmName, userID string, cred CredentialRepresentation) error {
return c.put(accessToken, url.Path(resetPasswordPath), url.Param("realm", realmName), url.Param("id", userID), body.JSON(cred)) return c.put(accessToken, url.Path(resetPasswordPath), url.Param("realm", realmName), url.Param("id", userID), body.JSON(cred))
} }
// GetCredentials returns the list of credentials of the user // GetCredentials returns the list of credentials of the user
func (c *Client) GetCredentials(accessToken string, realmName string, userID string) ([]keycloak.CredentialRepresentation, error) { func (c *Client) GetCredentials(accessToken string, realmName string, userID string) ([]CredentialRepresentation, error) {
var resp = []keycloak.CredentialRepresentation{} var resp = []CredentialRepresentation{}
var err = c.get(accessToken, &resp, url.Path(credentialsPath), url.Param("realm", realmName), url.Param("id", userID)) var err = c.get(accessToken, &resp, url.Path(credentialsPath), url.Param("realm", realmName), url.Param("id", userID))
return resp, err return resp, err

2
definitions.go

@ -112,7 +112,7 @@ type ClientInitialAccessPresentation struct {
} }
// ClientMapperRepresentation struct // ClientMapperRepresentation struct
// https://www.keycloak.org/docs-api/9.0/rest-api/index.html#_clientscopeevaluateresource-protocolmapperevaluationrepresentation // https://www.org/docs-api/9.0/rest-api/index.html#_clientscopeevaluateresource-protocolmapperevaluationrepresentation
type ClientMapperRepresentation struct { type ClientMapperRepresentation struct {
ContainerID *string `json:"containerId,omitempty"` ContainerID *string `json:"containerId,omitempty"`
ContainerName *string `json:"containerName,omitempty"` ContainerName *string `json:"containerName,omitempty"`

25
api/groups.go → groups.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -14,21 +13,21 @@ const (
) )
// GetGroups gets all groups for the realm // GetGroups gets all groups for the realm
func (c *Client) GetGroups(accessToken string, realmName string) ([]keycloak.GroupRepresentation, error) { func (c *Client) GetGroups(accessToken string, realmName string) ([]GroupRepresentation, error) {
var resp = []keycloak.GroupRepresentation{} var resp = []GroupRepresentation{}
var err = c.get(accessToken, &resp, url.Path(groupsPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(groupsPath), url.Param("realm", realmName))
return resp, err return resp, err
} }
// GetGroup gets a specific group’s representation // GetGroup gets a specific group’s representation
func (c *Client) GetGroup(accessToken string, realmName string, groupID string) (keycloak.GroupRepresentation, error) { func (c *Client) GetGroup(accessToken string, realmName string, groupID string) (GroupRepresentation, error) {
var resp = keycloak.GroupRepresentation{} var resp = GroupRepresentation{}
var err = c.get(accessToken, &resp, url.Path(groupByIDPath), url.Param("realm", realmName), url.Param("id", groupID)) var err = c.get(accessToken, &resp, url.Path(groupByIDPath), url.Param("realm", realmName), url.Param("id", groupID))
return resp, err return resp, err
} }
// CreateGroup creates the group from its GroupRepresentation. The group name must be unique. // CreateGroup creates the group from its GroupRepresentation. The group name must be unique.
func (c *Client) CreateGroup(accessToken string, reqRealmName string, group keycloak.GroupRepresentation) (string, error) { func (c *Client) CreateGroup(accessToken string, reqRealmName string, group GroupRepresentation) (string, error) {
return c.post(accessToken, nil, url.Path(groupsPath), url.Param("realm", reqRealmName), body.JSON(group)) return c.post(accessToken, nil, url.Path(groupsPath), url.Param("realm", reqRealmName), body.JSON(group))
} }
@ -38,26 +37,26 @@ func (c *Client) DeleteGroup(accessToken string, realmName string, groupID strin
} }
// AssignClientRole assigns client roles to a specific group // AssignClientRole assigns client roles to a specific group
func (c *Client) AssignClientRole(accessToken string, realmName string, groupID string, clientID string, roles []keycloak.RoleRepresentation) error { func (c *Client) AssignClientRole(accessToken string, realmName string, groupID string, clientID string, roles []RoleRepresentation) error {
_, err := c.post(accessToken, nil, url.Path(groupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID), body.JSON(roles)) _, err := c.post(accessToken, nil, url.Path(groupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID), body.JSON(roles))
return err return err
} }
// RemoveClientRole deletes client roles from a specific group // RemoveClientRole deletes client roles from a specific group
func (c *Client) RemoveClientRole(accessToken string, realmName string, groupID string, clientID string, roles []keycloak.RoleRepresentation) error { func (c *Client) RemoveClientRole(accessToken string, realmName string, groupID string, clientID string, roles []RoleRepresentation) error {
return c.delete(accessToken, url.Path(groupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID), body.JSON(roles)) return c.delete(accessToken, url.Path(groupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID), body.JSON(roles))
} }
// GetGroupClientRoles gets client roles assigned to a specific group // GetGroupClientRoles gets client roles assigned to a specific group
func (c *Client) GetGroupClientRoles(accessToken string, realmName string, groupID string, clientID string) ([]keycloak.RoleRepresentation, error) { func (c *Client) GetGroupClientRoles(accessToken string, realmName string, groupID string, clientID string) ([]RoleRepresentation, error) {
var roles = []keycloak.RoleRepresentation{} var roles = []RoleRepresentation{}
var err = c.get(accessToken, &roles, url.Path(groupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID)) var err = c.get(accessToken, &roles, url.Path(groupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID))
return roles, err return roles, err
} }
// GetAvailableGroupClientRoles gets client roles available in a specific group // GetAvailableGroupClientRoles gets client roles available in a specific group
func (c *Client) GetAvailableGroupClientRoles(accessToken string, realmName string, groupID string, clientID string) ([]keycloak.RoleRepresentation, error) { func (c *Client) GetAvailableGroupClientRoles(accessToken string, realmName string, groupID string, clientID string) ([]RoleRepresentation, error) {
var roles = []keycloak.RoleRepresentation{} var roles = []RoleRepresentation{}
var err = c.get(accessToken, &roles, url.Path(availableGroupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID)) var err = c.get(accessToken, &roles, url.Path(availableGroupClientRoleMappingPath), url.Param("realm", realmName), url.Param("id", groupID), url.Param("clientId", clientID))
return roles, err return roles, err
} }

15
api/identity_providers.go → identity_providers.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -12,22 +11,22 @@ const (
) )
// GetIdps gets the list of identity providers // GetIdps gets the list of identity providers
func (c *Client) GetIdps(accessToken string, realmName string) ([]keycloak.IdentityProviderRepresentation, error) { func (c *Client) GetIdps(accessToken string, realmName string) ([]IdentityProviderRepresentation, error) {
var resp = []keycloak.IdentityProviderRepresentation{} var resp = []IdentityProviderRepresentation{}
var err = c.get(accessToken, &resp, url.Path(idpsPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(idpsPath), url.Param("realm", realmName))
return resp, err return resp, err
} }
// GetIdp gets an identity provider matching the given alias // GetIdp gets an identity provider matching the given alias
func (c *Client) GetIdp(accessToken string, realmName string, idpAlias string) (keycloak.IdentityProviderRepresentation, error) { func (c *Client) GetIdp(accessToken string, realmName string, idpAlias string) (IdentityProviderRepresentation, error) {
var resp = keycloak.IdentityProviderRepresentation{} var resp = IdentityProviderRepresentation{}
var err = c.get(accessToken, &resp, url.Path(idpAliasPath), url.Param("realm", realmName), url.Param("alias", idpAlias)) var err = c.get(accessToken, &resp, url.Path(idpAliasPath), url.Param("realm", realmName), url.Param("alias", idpAlias))
return resp, err return resp, err
} }
// GetIdpMappers gets the mappers of the specified identity provider // GetIdpMappers gets the mappers of the specified identity provider
func (c *Client) GetIdpMappers(accessToken string, realmName string, idpAlias string) ([]keycloak.IdentityProviderMapperRepresentation, error) { func (c *Client) GetIdpMappers(accessToken string, realmName string, idpAlias string) ([]IdentityProviderMapperRepresentation, error) {
var resp = []keycloak.IdentityProviderMapperRepresentation{} var resp = []IdentityProviderMapperRepresentation{}
var err = c.get(accessToken, &resp, url.Path(idpMappersPath), url.Param("realm", realmName), url.Param("alias", idpAlias)) var err = c.get(accessToken, &resp, url.Path(idpMappersPath), url.Param("realm", realmName), url.Param("alias", idpAlias))
return resp, err return resp, err
} }

3
integration/integration-tests.go

@ -9,7 +9,6 @@ import (
"time" "time"
"github.com/nmasse-itix/keycloak-client" "github.com/nmasse-itix/keycloak-client"
api "github.com/nmasse-itix/keycloak-client/api"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -21,7 +20,7 @@ const (
func main() { func main() {
var conf = getKeycloakConfig() var conf = getKeycloakConfig()
fmt.Printf("Connecting to KC %s...\n", conf.AddrAPI) fmt.Printf("Connecting to KC %s...\n", conf.AddrAPI)
var client, err = api.New(*conf) var client, err = keycloak.NewClient(*conf)
if err != nil { if err != nil {
log.Fatalf("could not create keycloak client: %v", err) log.Fatalf("could not create keycloak client: %v", err)
} }

33
api/keycloak_client.go → keycloak_client.go

@ -1,10 +1,9 @@
package api package keycloak
import ( import (
"fmt" "fmt"
"net/url" "net/url"
"github.com/nmasse-itix/keycloak-client"
"github.com/pkg/errors" "github.com/pkg/errors"
"gopkg.in/h2non/gentleman.v2" "gopkg.in/h2non/gentleman.v2"
"gopkg.in/h2non/gentleman.v2/plugin" "gopkg.in/h2non/gentleman.v2/plugin"
@ -18,14 +17,14 @@ type Client struct {
httpClient *gentleman.Client httpClient *gentleman.Client
} }
// New returns a keycloak client. // NewClient returns a keycloak client.
func New(config keycloak.Config) (*Client, error) { func NewClient(config Config) (*Client, error) {
var uAPI *url.URL var uAPI *url.URL
{ {
var err error var err error
uAPI, err = url.Parse(config.AddrAPI) uAPI, err = url.Parse(config.AddrAPI)
if err != nil { if err != nil {
return nil, errors.Wrap(err, keycloak.MsgErrCannotParse+"."+keycloak.APIURL) return nil, errors.Wrap(err, MsgErrCannotParse+"."+APIURL)
} }
} }
@ -60,7 +59,7 @@ func (c *Client) GetToken(realm string, username string, password string) (strin
var err error var err error
resp, err = req.Do() resp, err = req.Do()
if err != nil { if err != nil {
return "", errors.Wrap(err, keycloak.MsgErrCannotObtain+"."+keycloak.TokenMsg) return "", errors.Wrap(err, MsgErrCannotObtain+"."+TokenMsg)
} }
} }
defer resp.Close() defer resp.Close()
@ -70,7 +69,7 @@ func (c *Client) GetToken(realm string, username string, password string) (strin
var err error var err error
err = resp.JSON(&unmarshalledBody) err = resp.JSON(&unmarshalledBody)
if err != nil { if err != nil {
return "", errors.Wrap(err, keycloak.MsgErrCannotUnmarshal+"."+keycloak.Response) return "", errors.Wrap(err, MsgErrCannotUnmarshal+"."+Response)
} }
} }
@ -79,7 +78,7 @@ func (c *Client) GetToken(realm string, username string, password string) (strin
var ok bool var ok bool
accessToken, ok = unmarshalledBody["access_token"] accessToken, ok = unmarshalledBody["access_token"]
if !ok { if !ok {
return "", fmt.Errorf(keycloak.MsgErrMissingParam + "." + keycloak.AccessToken) return "", fmt.Errorf(MsgErrMissingParam + "." + AccessToken)
} }
} }
@ -102,11 +101,11 @@ func (c *Client) get(accessToken string, data interface{}, plugins ...plugin.Plu
var err error var err error
resp, err = req.Do() resp, err = req.Do()
if err != nil { if err != nil {
return errors.Wrap(err, keycloak.MsgErrCannotObtain+"."+keycloak.Response) return errors.Wrap(err, MsgErrCannotObtain+"."+Response)
} }
if resp.StatusCode < 200 || resp.StatusCode >= 400 { if resp.StatusCode < 200 || resp.StatusCode >= 400 {
return keycloak.HTTPError{ return HTTPError{
HTTPStatus: resp.StatusCode, HTTPStatus: resp.StatusCode,
Message: string(resp.Bytes()), Message: string(resp.Bytes()),
} }
@ -119,7 +118,7 @@ func (c *Client) get(accessToken string, data interface{}, plugins ...plugin.Plu
_ = resp.Bytes() _ = resp.Bytes()
return nil return nil
default: default:
return fmt.Errorf("%s.%v", keycloak.MsgErrUnkownHTTPContentType, resp.Header.Get("Content-Type")) return fmt.Errorf("%s.%v", MsgErrUnkownHTTPContentType, resp.Header.Get("Content-Type"))
} }
} }
} }
@ -139,11 +138,11 @@ func (c *Client) post(accessToken string, data interface{}, plugins ...plugin.Pl
var err error var err error
resp, err = req.Do() resp, err = req.Do()
if err != nil { if err != nil {
return "", errors.Wrap(err, keycloak.MsgErrCannotObtain+"."+keycloak.Response) return "", errors.Wrap(err, MsgErrCannotObtain+"."+Response)
} }
if resp.StatusCode < 200 || resp.StatusCode >= 400 { if resp.StatusCode < 200 || resp.StatusCode >= 400 {
return "", keycloak.HTTPError{ return "", HTTPError{
HTTPStatus: resp.StatusCode, HTTPStatus: resp.StatusCode,
Message: string(resp.Bytes()), Message: string(resp.Bytes()),
} }
@ -178,11 +177,11 @@ func (c *Client) delete(accessToken string, plugins ...plugin.Plugin) error {
var err error var err error
resp, err = req.Do() resp, err = req.Do()
if err != nil { if err != nil {
return errors.Wrap(err, keycloak.MsgErrCannotObtain+"."+keycloak.Response) return errors.Wrap(err, MsgErrCannotObtain+"."+Response)
} }
if resp.StatusCode < 200 || resp.StatusCode >= 400 { if resp.StatusCode < 200 || resp.StatusCode >= 400 {
return keycloak.HTTPError{ return HTTPError{
HTTPStatus: resp.StatusCode, HTTPStatus: resp.StatusCode,
Message: string(resp.Bytes()), Message: string(resp.Bytes()),
} }
@ -207,11 +206,11 @@ func (c *Client) put(accessToken string, plugins ...plugin.Plugin) error {
var err error var err error
resp, err = req.Do() resp, err = req.Do()
if err != nil { if err != nil {
return errors.Wrap(err, keycloak.MsgErrCannotObtain+"."+keycloak.Response) return errors.Wrap(err, MsgErrCannotObtain+"."+Response)
} }
if resp.StatusCode < 200 || resp.StatusCode >= 400 { if resp.StatusCode < 200 || resp.StatusCode >= 400 {
return keycloak.HTTPError{ return HTTPError{
HTTPStatus: resp.StatusCode, HTTPStatus: resp.StatusCode,
Message: string(resp.Bytes()), Message: string(resp.Bytes()),
} }

19
api/realm.go → realm.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -15,28 +14,28 @@ const (
// GetRealms get the top level represention of all the realms. Nested information like users are // GetRealms get the top level represention of all the realms. Nested information like users are
// not included. // not included.
func (c *Client) GetRealms(accessToken string) ([]keycloak.RealmRepresentation, error) { func (c *Client) GetRealms(accessToken string) ([]RealmRepresentation, error) {
var resp = []keycloak.RealmRepresentation{} var resp = []RealmRepresentation{}
var err = c.get(accessToken, &resp, url.Path(realmRootPath)) var err = c.get(accessToken, &resp, url.Path(realmRootPath))
return resp, err return resp, err
} }
// CreateRealm creates the realm from its RealmRepresentation. // CreateRealm creates the realm from its RealmRepresentation.
func (c *Client) CreateRealm(accessToken string, realm keycloak.RealmRepresentation) (string, error) { func (c *Client) CreateRealm(accessToken string, realm RealmRepresentation) (string, error) {
return c.post(accessToken, nil, url.Path(realmRootPath), body.JSON(realm)) return c.post(accessToken, nil, url.Path(realmRootPath), body.JSON(realm))
} }
// GetRealm get the top level represention of the realm. Nested information like users are // GetRealm get the top level represention of the realm. Nested information like users are
// not included. // not included.
func (c *Client) GetRealm(accessToken string, realmName string) (keycloak.RealmRepresentation, error) { func (c *Client) GetRealm(accessToken string, realmName string) (RealmRepresentation, error) {
var resp = keycloak.RealmRepresentation{} var resp = RealmRepresentation{}
var err = c.get(accessToken, &resp, url.Path(realmPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(realmPath), url.Param("realm", realmName))
return resp, err return resp, err
} }
// UpdateRealm update the top lovel information of the realm. Any user, role or client information // UpdateRealm update the top lovel information of the realm. Any user, role or client information
// from the realm representation will be ignored. // from the realm representation will be ignored.
func (c *Client) UpdateRealm(accessToken string, realmName string, realm keycloak.RealmRepresentation) error { func (c *Client) UpdateRealm(accessToken string, realmName string, realm RealmRepresentation) error {
return c.put(accessToken, url.Path(realmPath), url.Param("realm", realmName), body.JSON(realm)) return c.put(accessToken, url.Path(realmPath), url.Param("realm", realmName), body.JSON(realm))
} }
@ -46,8 +45,8 @@ func (c *Client) DeleteRealm(accessToken string, realmName string) error {
} }
// ExportRealm recovers the full realm. // ExportRealm recovers the full realm.
func (c *Client) ExportRealm(accessToken string, realmName string) (keycloak.RealmRepresentation, error) { func (c *Client) ExportRealm(accessToken string, realmName string) (RealmRepresentation, error) {
var resp = keycloak.RealmRepresentation{} var resp = RealmRepresentation{}
var err = c.get(accessToken, &resp, url.Path(exportRealmPath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(exportRealmPath), url.Param("realm", realmName))
return resp, err return resp, err
} }

11
api/recovery_code.go → recovery_code.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/query" "gopkg.in/h2non/gentleman.v2/plugins/query"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -12,16 +11,16 @@ const (
) )
// CreateRecoveryCode creates a new recovery code authenticator and returns the code. // CreateRecoveryCode creates a new recovery code authenticator and returns the code.
func (c *Client) CreateRecoveryCode(accessToken string, realmName string, userID string) (keycloak.RecoveryCodeRepresentation, error) { func (c *Client) CreateRecoveryCode(accessToken string, realmName string, userID string) (RecoveryCodeRepresentation, error) {
var resp = keycloak.RecoveryCodeRepresentation{} var resp = RecoveryCodeRepresentation{}
_, err := c.post(accessToken, &resp, query.Add("userId", userID), url.Path(recoveryCodePath), url.Param("realm", realmName)) _, err := c.post(accessToken, &resp, query.Add("userId", userID), url.Path(recoveryCodePath), url.Param("realm", realmName))
return resp, err return resp, err
} }
// CreateActivationCode creates a new activation code authenticator and returns the code. // CreateActivationCode creates a new activation code authenticator and returns the code.
func (c *Client) CreateActivationCode(accessToken string, realmName string, userID string) (keycloak.ActivationCodeRepresentation, error) { func (c *Client) CreateActivationCode(accessToken string, realmName string, userID string) (ActivationCodeRepresentation, error) {
var resp = keycloak.ActivationCodeRepresentation{} var resp = ActivationCodeRepresentation{}
_, err := c.post(accessToken, &resp, query.Add("userId", userID), url.Path(activationCodePath), url.Param("realm", realmName)) _, err := c.post(accessToken, &resp, query.Add("userId", userID), url.Path(activationCodePath), url.Param("realm", realmName))
return resp, err return resp, err

17
api/roles.go → roles.go

@ -1,7 +1,6 @@
package api package keycloak
import ( import (
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -13,27 +12,27 @@ const (
) )
// GetClientRoles gets all roles for the realm or client // GetClientRoles gets all roles for the realm or client
func (c *Client) GetClientRoles(accessToken string, realmName, idClient string) ([]keycloak.RoleRepresentation, error) { func (c *Client) GetClientRoles(accessToken string, realmName, idClient string) ([]RoleRepresentation, error) {
var resp = []keycloak.RoleRepresentation{} var resp = []RoleRepresentation{}
var err = c.get(accessToken, &resp, url.Path(clientRolePath), url.Param("realm", realmName), url.Param("id", idClient)) var err = c.get(accessToken, &resp, url.Path(clientRolePath), url.Param("realm", realmName), url.Param("id", idClient))
return resp, err return resp, err
} }
// CreateClientRole creates a new role for the realm or client // CreateClientRole creates a new role for the realm or client
func (c *Client) CreateClientRole(accessToken string, realmName, clientID string, role keycloak.RoleRepresentation) (string, error) { func (c *Client) CreateClientRole(accessToken string, realmName, clientID string, role RoleRepresentation) (string, error) {
return c.post(accessToken, nil, url.Path(clientRolePath), url.Param("realm", realmName), url.Param("id", clientID), body.JSON(role)) return c.post(accessToken, nil, url.Path(clientRolePath), url.Param("realm", realmName), url.Param("id", clientID), body.JSON(role))
} }
// GetRoles gets all roles for the realm or client // GetRoles gets all roles for the realm or client
func (c *Client) GetRoles(accessToken string, realmName string) ([]keycloak.RoleRepresentation, error) { func (c *Client) GetRoles(accessToken string, realmName string) ([]RoleRepresentation, error) {
var resp = []keycloak.RoleRepresentation{} var resp = []RoleRepresentation{}
var err = c.get(accessToken, &resp, url.Path(rolePath), url.Param("realm", realmName)) var err = c.get(accessToken, &resp, url.Path(rolePath), url.Param("realm", realmName))
return resp, err return resp, err
} }
// GetRole gets a specific role’s representation // GetRole gets a specific role’s representation
func (c *Client) GetRole(accessToken string, realmName string, roleID string) (keycloak.RoleRepresentation, error) { func (c *Client) GetRole(accessToken string, realmName string, roleID string) (RoleRepresentation, error) {
var resp = keycloak.RoleRepresentation{} var resp = RoleRepresentation{}
var err = c.get(accessToken, &resp, url.Path(roleByIDPath), url.Param("realm", realmName), url.Param("id", roleID)) var err = c.get(accessToken, &resp, url.Path(roleByIDPath), url.Param("realm", realmName), url.Param("id", roleID))
return resp, err return resp, err
} }

33
api/users.go → users.go

@ -1,9 +1,8 @@
package api package keycloak
import ( import (
"errors" "errors"
"github.com/nmasse-itix/keycloak-client"
"gopkg.in/h2non/gentleman.v2/plugins/body" "gopkg.in/h2non/gentleman.v2/plugins/body"
"gopkg.in/h2non/gentleman.v2/plugins/url" "gopkg.in/h2non/gentleman.v2/plugins/url"
) )
@ -26,10 +25,10 @@ const (
// Parameters: email, first (paging offset, int), firstName, lastName, username, // Parameters: email, first (paging offset, int), firstName, lastName, username,
// max (maximum result size, default = 100), // max (maximum result size, default = 100),
// search (string contained in username, firstname, lastname or email) // search (string contained in username, firstname, lastname or email)
func (c *Client) GetUsers(accessToken string, targetRealmName string, paramKV ...string) ([]keycloak.UserRepresentation, error) { func (c *Client) GetUsers(accessToken string, targetRealmName string, paramKV ...string) ([]UserRepresentation, error) {
var resp []keycloak.UserRepresentation var resp []UserRepresentation
if len(paramKV)%2 != 0 { if len(paramKV)%2 != 0 {
return resp, errors.New(keycloak.MsgErrInvalidParam + "." + keycloak.EvenParams) return resp, errors.New(MsgErrInvalidParam + "." + EvenParams)
} }
var plugins = append(createQueryPlugins(paramKV...), url.Path(userPath), url.Param("realm", targetRealmName)) var plugins = append(createQueryPlugins(paramKV...), url.Path(userPath), url.Param("realm", targetRealmName))
@ -38,7 +37,7 @@ func (c *Client) GetUsers(accessToken string, targetRealmName string, paramKV ..
} }
// CreateUser creates the user from its UserRepresentation. The username must be unique. // CreateUser creates the user from its UserRepresentation. The username must be unique.
func (c *Client) CreateUser(accessToken string, targetRealmName string, user keycloak.UserRepresentation) (string, error) { func (c *Client) CreateUser(accessToken string, targetRealmName string, user UserRepresentation) (string, error) {
return c.post(accessToken, nil, url.Path(userPath), url.Param("realm", targetRealmName), body.JSON(user)) return c.post(accessToken, nil, url.Path(userPath), url.Param("realm", targetRealmName), body.JSON(user))
} }
@ -50,15 +49,15 @@ func (c *Client) CountUsers(accessToken string, realmName string) (int, error) {
} }
// GetUser gets the represention of the user. // GetUser gets the represention of the user.
func (c *Client) GetUser(accessToken string, realmName, userID string) (keycloak.UserRepresentation, error) { func (c *Client) GetUser(accessToken string, realmName, userID string) (UserRepresentation, error) {
var resp = keycloak.UserRepresentation{} var resp = UserRepresentation{}
var err = c.get(accessToken, &resp, url.Path(userIDPath), url.Param("realm", realmName), url.Param("id", userID)) var err = c.get(accessToken, &resp, url.Path(userIDPath), url.Param("realm", realmName), url.Param("id", userID))
return resp, err return resp, err
} }
// GetGroupsOfUser gets the groups of the user. // GetGroupsOfUser gets the groups of the user.
func (c *Client) GetGroupsOfUser(accessToken string, realmName, userID string) ([]keycloak.GroupRepresentation, error) { func (c *Client) GetGroupsOfUser(accessToken string, realmName, userID string) ([]GroupRepresentation, error) {
var resp = []keycloak.GroupRepresentation{} var resp = []GroupRepresentation{}
var err = c.get(accessToken, &resp, url.Path(userGroupsPath), url.Param("realm", realmName), url.Param("id", userID)) var err = c.get(accessToken, &resp, url.Path(userGroupsPath), url.Param("realm", realmName), url.Param("id", userID))
return resp, err return resp, err
} }
@ -74,7 +73,7 @@ func (c *Client) DeleteGroupFromUser(accessToken string, realmName, userID, grou
} }
// UpdateUser updates the user. // UpdateUser updates the user.
func (c *Client) UpdateUser(accessToken string, realmName, userID string, user keycloak.UserRepresentation) error { func (c *Client) UpdateUser(accessToken string, realmName, userID string, user UserRepresentation) error {
return c.put(accessToken, url.Path(userIDPath), url.Param("realm", realmName), url.Param("id", userID), body.JSON(user)) return c.put(accessToken, url.Path(userIDPath), url.Param("realm", realmName), url.Param("id", userID), body.JSON(user))
} }
@ -86,7 +85,7 @@ func (c *Client) DeleteUser(accessToken string, realmName, userID string) error
// ExecuteActionsEmail sends an update account email to the user. An email contains a link the user can click to perform a set of required actions. // ExecuteActionsEmail sends an update account email to the user. An email contains a link the user can click to perform a set of required actions.
func (c *Client) ExecuteActionsEmail(accessToken string, realmName string, userID string, actions []string, paramKV ...string) error { func (c *Client) ExecuteActionsEmail(accessToken string, realmName string, userID string, actions []string, paramKV ...string) error {
if len(paramKV)%2 != 0 { if len(paramKV)%2 != 0 {
return errors.New(keycloak.MsgErrInvalidParam + "." + keycloak.EvenParams) return errors.New(MsgErrInvalidParam + "." + EvenParams)
} }
var plugins = append(createQueryPlugins(paramKV...), url.Path(executeActionsEmailPath), url.Param("realm", realmName), url.Param("id", userID), body.JSON(actions)) var plugins = append(createQueryPlugins(paramKV...), url.Path(executeActionsEmailPath), url.Param("realm", realmName), url.Param("id", userID), body.JSON(actions))
@ -95,11 +94,11 @@ func (c *Client) ExecuteActionsEmail(accessToken string, realmName string, userI
} }
// SendSmsCode sends a SMS code and return it // SendSmsCode sends a SMS code and return it
func (c *Client) SendSmsCode(accessToken string, realmName string, userID string) (keycloak.SmsCodeRepresentation, error) { func (c *Client) SendSmsCode(accessToken string, realmName string, userID string) (SmsCodeRepresentation, error) {
var paramKV []string var paramKV []string
paramKV = append(paramKV, "userid", userID) paramKV = append(paramKV, "userid", userID)
var plugins = append(createQueryPlugins(paramKV...), url.Path(sendSmsCode), url.Param("realm", realmName)) var plugins = append(createQueryPlugins(paramKV...), url.Path(sendSmsCode), url.Param("realm", realmName))
var resp = keycloak.SmsCodeRepresentation{} var resp = SmsCodeRepresentation{}
_, err := c.post(accessToken, &resp, plugins...) _, err := c.post(accessToken, &resp, plugins...)
@ -109,7 +108,7 @@ func (c *Client) SendSmsCode(accessToken string, realmName string, userID string
// SendReminderEmail sends a reminder email to a user // SendReminderEmail sends a reminder email to a user
func (c *Client) SendReminderEmail(accessToken string, realmName string, userID string, paramKV ...string) error { func (c *Client) SendReminderEmail(accessToken string, realmName string, userID string, paramKV ...string) error {
if len(paramKV)%2 != 0 { if len(paramKV)%2 != 0 {
return errors.New(keycloak.MsgErrInvalidParam + "." + keycloak.EvenParams) return errors.New(MsgErrInvalidParam + "." + EvenParams)
} }
var newParamKV = append(paramKV, "userid", userID) var newParamKV = append(paramKV, "userid", userID)
@ -120,13 +119,13 @@ func (c *Client) SendReminderEmail(accessToken string, realmName string, userID
} }
// LinkShadowUser links shadow user to a realm in the context of brokering // LinkShadowUser links shadow user to a realm in the context of brokering
func (c *Client) LinkShadowUser(accessToken string, reqRealmName string, userID string, provider string, fedIDKC keycloak.FederatedIdentityRepresentation) error { func (c *Client) LinkShadowUser(accessToken string, reqRealmName string, userID string, provider string, fedIDKC FederatedIdentityRepresentation) error {
_, err := c.post(accessToken, nil, url.Path(shadowUser), url.Param("realm", reqRealmName), url.Param("id", userID), url.Param("provider", provider), body.JSON(fedIDKC)) _, err := c.post(accessToken, nil, url.Path(shadowUser), url.Param("realm", reqRealmName), url.Param("id", userID), url.Param("provider", provider), body.JSON(fedIDKC))
return err return err
} }
// SendSMS sends an SMS to a user // SendSMS sends an SMS to a user
func (c *Client) SendSMS(accessToken string, realmName string, smsRep keycloak.SMSRepresentation) error { func (c *Client) SendSMS(accessToken string, realmName string, smsRep SMSRepresentation) error {
_, err := c.post(accessToken, nil, url.Path(sendSMSPath), url.Param("realm", realmName), body.JSON(smsRep)) _, err := c.post(accessToken, nil, url.Path(sendSMSPath), url.Param("realm", realmName), body.JSON(smsRep))
return err return err
} }
Loading…
Cancel
Save