Skip to content

Commit

Permalink
Improve sdk (#18)
Browse files Browse the repository at this point in the history
* Restructuring

* Moved servererror package

* Moved all service packages to services sub directory

* Moved all service packages to services sub directory

* Moved generated OpenAPI code to generated/ sub directory

* Renamed email link service to email magic link service and email code service to email OTP service

* Renamed SDK getter methods for email magic links and email OTPs

* Renamed integration tests

* Added SmsOTP service!

* New README

* Added error handling section to README

* Fixed code examples in README

* Tabs vs. spaces

* Tabs vs. spaces

* Run GitHub action on every branch push

* Set version to 1.0.0

* Updated test email and test phone number, added more Go versions to GitHub matrix

* Some cleanup, added email OTP and SMS OTP validate integration tests

* Bugfix in GitHub workflow

* Renamed some GitHub workflow jobs

* More renames

* Implemented user delete method, added more integration tests to user API

* Added error stacks

* Update ci_unittests.yml

* Update ci_integrationtests.yml

* Update ci_unittests.yml

* Update ci_integrationtests.yml

* Update ci_integrationtests.yml

* Update ci_unittests.yml

* Bugfix

* PR feedback

* Update README.md

* Changed SDK header (added more infos)

* Refactoring config handling and added validation, added session stdlib example, some other minor changes

* Removed unused config variable

* Renamed NewConfigEnv() to NewConfigFromEnv()

* Polished session stdlib example

* Extended session stdlib example

* Moved internal packages to internal/

* Added missing directory

* Moved entities to pkg/

* move logger from internal to pkg

* Update README.md

* Update README.md

* Update README.md

---------

Co-authored-by: Corbadovych <[email protected]>
  • Loading branch information
corbadoman and corbadovych authored Jan 14, 2024
1 parent 0793136 commit 93655ad
Show file tree
Hide file tree
Showing 60 changed files with 1,393 additions and 538 deletions.
14 changes: 5 additions & 9 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,19 @@ name: tests

on:
push:
branches:
- 'main'
pull_request:
branches:
- 'main'
branches: '*'

concurrency:
group: ${{ github.ref }}
cancel-in-progress: true

jobs:
unit-test:
uses: "./.github/workflows/ci_unit_test.yml"
unittests:
uses: "./.github/workflows/ci_unittests.yml"
secrets: inherit

integration-test:
uses: "./.github/workflows/ci_integration_test.yml"
integrationtests:
uses: "./.github/workflows/ci_integrationtests.yml"
secrets: inherit

lint:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
name: integration-test
name: integrationtests

on:
workflow_call:

jobs:
test:
integrationtests:
runs-on: ubuntu-latest

strategy:
fail-fast: false
matrix:
go:
- '1.18'
- '1.19'
- '1.20'
- '1.21'

steps:
- uses: actions/checkout@v3
Expand All @@ -21,8 +24,9 @@ jobs:
go-version: ${{ matrix.go }}
cache: true

- env:
- name: Run integration tests
env:
CORBADO_BACKEND_API: ${{ secrets.CORBADO_BACKEND_API }}
CORBADO_PROJECT_ID: ${{ secrets.CORBADO_PROJECT_ID }}
CORBADO_API_SECRET: ${{ secrets.CORBADO_API_SECRET }}
run: go test -tags=integration ./tests/integration/...
run: go test -tags=integration ./tests/integration/...
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
name: unit-test
name: unittests

on:
workflow_call:

jobs:
test:
unittests:
runs-on: ubuntu-latest

strategy:
fail-fast: false
matrix:
go:
- '1.18'
- '1.19'
- '1.20'
- '1.21'

steps:
- uses: actions/checkout@v3
Expand All @@ -20,5 +23,6 @@ jobs:
with:
go-version: ${{ matrix.go }}
cache: true

- run: go test ./...

- name: Run unit tests
run: go test ./...
156 changes: 134 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,44 +1,156 @@
# Corbado Go SDK
<img width="1070" alt="GitHub Repo Cover" src="https://github.com/corbado/corbado-php/assets/18458907/aa4f9df6-980b-4b24-bb2f-d71c0f480971">

Go SDK for Corbado Backend API
# Corbado Go SDK

[![Go Reference](https://pkg.go.dev/badge/github.com/corbado/corbado-go.svg)](https://pkg.go.dev/github.com/corbado/corbado-go)
[![License](https://poser.pugx.org/corbado/php-sdk/license.svg)](https://packagist.org/packages/corbado/php-sdk)
[![Test Status](https://github.com/corbado/corbado-go/workflows/tests/badge.svg)](https://github.com/corbado/corbado-go/actions?query=workflow%3Atests)
[![documentation](https://img.shields.io/badge/documentation-Corbado_Backend_API_Reference-blue.svg)](https://api.corbado.com/docs/api/)
[![Go Report Card](https://goreportcard.com/badge/github.com/corbado/corbado-go)](https://goreportcard.com/report/github.com/corbado/corbado-go)
[![documentation](https://img.shields.io/badge/documentation-Corbado_Backend_API_Reference-blue.svg)](https://api.corbado.com/docs/api/)
[![Slack](https://img.shields.io/badge/slack-join%20chat-brightgreen.svg)](https://join.slack.com/t/corbado/shared_invite/zt-1b7867yz8-V~Xr~ngmSGbt7IA~g16ZsQ)

## Requirements
The [Corbado](https://www.corbado.com) Go SDK provides convenient access to the [Corbado Backend API](https://api.corbado.com/docs/api/) from applications written in the Go language.

The SDK supports Go version 1.18 and above.
:warning: The Corbado Go SDK is commonly referred to as a private client, specifically designed for usage within closed backend applications. This particular SDK should exclusively be utilized in such environments, as it is crucial to ensure that the API secret remains strictly confidential and is never shared.

## Usage
:rocket: [Getting started](#rocket-getting-started) | :hammer_and_wrench: [Services](#hammer_and_wrench-services) | :books: [Advanced](#books-advanced) | :speech_balloon: [Support & Feedback](#speech_balloon-support--feedback)

## :rocket: Getting started

### Requirements

- Go 1.18 or later

### Installation

Use the following command to install the Corbado Go SDK:

```bash
go get github.com/corbado/[email protected]
```
$ go get github.com/corbado/[email protected]
```

Import SDK in your Go files:
### Usage

To create a Corbado Go SDK instance you need to provide your `Project ID` and `API secret` which can be found at the [Developer Panel](https://app.corbado.com).

```Go
package main

```go
import "github.com/corbado/corbado-go"
import (
"github.com/corbado/corbado-go"
)

func main() {
config, err := corbado.NewConfig("<Project ID>", "<API secret>")
if err != nil {
panic(err)
}

sdk, err := corbado.NewSDK(config)
if err != nil {
panic(err)
}
}
```

Now create a new SDK client:
### Examples

A list of examples can be found in the [examples](/examples) directory. [Integration tests](tests/integration) are good examples as well.

```go
config := corbado.MustNewConfig("pro-12345678", "yoursecret")
sdk, err := corbado.NewSDK(config)
## :hammer_and_wrench: Services

The Corbado Go SDK provides the following services:

- `AuthTokens` for managing authentication tokens needed for own session management ([examples](tests/integration/authtoken))
- `EmailMagicLinks` for managing email magic links ([examples](tests/integration/emailmagiclink))
- `EmailOTPs` for managing email OTPs ([examples](tests/integration/emailotp))
- `Sessions` for managing sessions ([examples](examples/sessionstdlib))
- `SmsOTPs` for managing SMS OTPs ([examples](tests/integration/smsotp))
- `Users` for managing users ([examples](tests/integration/user))
- `Validations` for validating email addresses and phone numbers ([examples](tests/integration/validation))

To use a specific service, such as `Users`, invoke it as shown below:

```Go
users, err := sdk.Users().List(context.Background(), nil)
if err != nil {
// handle error
panic(err)
}
```

// list all users
users, err := sdk.Users().List(context.TODO(), nil)
if err != nil {
if serverErr := corbado.AsServerError(err); serverErr != nil {
// handle server error
## :books: Advanced

### Error handling

The Corbado Go SDK uses Go standard error handling (error interface). If the Backend API returns a HTTP status code other than 200, the Corbado Go SDK returns a `ServerError` error (which implements the error interface):

```Go
package main

import (
"context"
"fmt"

"github.com/corbado/corbado-go"
)

func main() {
config, err := corbado.NewConfig("<Project ID>", "<API secret>")
if err != nil {
panic(err)
}

sdk, err := corbado.NewSDK(config)
if err != nil {
panic(err)
}

// Try to get non-existing user with ID 'usr-123456789'
user, err := sdk.Users().Get(context.Background(), "usr-123456789", nil)
if err != nil {
if serverErr := corbado.AsServerError(err); serverErr != nil {
// Show HTTP status code (404 in this case)
fmt.Println(serverErr.HTTPStatusCode)

// Show request ID (can be used in developer panel to look up the full request
// and response, see https://app.corbado.com/app/logs/requests)
fmt.Println(serverErr.RequestData.RequestID)

// Show runtime of request in seconds (server side)
fmt.Println(serverErr.Runtime)

// Show validation error messages (server side validation in case of HTTP
// status code 400 (Bad Request))
fmt.Printf("%+v\n", serverErr.Validation)
} else {
// Handle other errors
panic(err)
}

return
}

fmt.Println(user.Data.ID)
}

```

See [examples](https://github.com/corbado/corbado-go/tree/main/examples) for some real example code
## :speech_balloon: Support & Feedback

### Report an issue

If you encounter any bugs or have suggestions, please [open an issue](https://github.com/corbado/corbado-go/issues/new).

### Slack channel

Join our Slack channel to discuss questions or ideas with the Corbado team and other developers.

[![Slack](https://img.shields.io/badge/slack-join%20chat-brightgreen.svg)](https://join.slack.com/t/corbado/shared_invite/zt-1b7867yz8-V~Xr~ngmSGbt7IA~g16ZsQ)

### Email

You can also reach out to us via email at [email protected].

### Vulnerability reporting

Please report suspected security vulnerabilities in private to [email protected]. Please do NOT create publicly viewable issues for suspected security vulnerabilities.
12 changes: 6 additions & 6 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@ version: '3'

tasks:
lint:
desc: Runs Golang linters
desc: Runs linters
cmds:
- GOFLAGS="-buildvcs=false" golangci-lint run --timeout=5m
sources:
- ./**/*.go
- ./.golangci.yml
method: checksum

unit-test:
desc: Runs Golang unit tests
unittests:
desc: Runs unit tests
cmds:
- go test -v ./...

integration-test:
desc: Runs Golang integration tests
integrationtests:
desc: Runs integration tests
cmds:
- go test -tags=integration ./tests/integration/...
- go test -tags=integration -count=1 ./tests/integration/...

docker-build:
desc: Builds Docker image
Expand Down
32 changes: 24 additions & 8 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@ package corbado
import (
"bytes"
"context"
"fmt"
"encoding/json"
"io"
"net/http"
"runtime"

"github.com/corbado/corbado-go/pkg/logger"
"github.com/corbado/corbado-go/pkg/sdk/assert"
"github.com/corbado/corbado-go/pkg/sdk/config"
"github.com/corbado/corbado-go/pkg/sdk/entity/api"
"github.com/deepmap/oapi-codegen/pkg/securityprovider"
"github.com/pkg/errors"

"github.com/corbado/corbado-go/internal/assert"
"github.com/corbado/corbado-go/pkg/generated/api"
)

func newClient(config *config.Config) (*api.ClientWithResponses, error) {
func newClient(config *Config) (*api.ClientWithResponses, error) {
if err := assert.NotNil(config); err != nil {
return nil, err
}
Expand All @@ -26,7 +27,7 @@ func newClient(config *config.Config) (*api.ClientWithResponses, error) {
}

extraOptions := []api.ClientOption{
api.WithRequestEditorFn(newSDKVersionHeaderEditorFn),
api.WithRequestEditorFn(newSDKHeaderEditorFn),
api.WithRequestEditorFn(basicAuth.Intercept),
}

Expand Down Expand Up @@ -113,8 +114,23 @@ func NewLoggingClientOption() api.ClientOption {
}
}

func newSDKVersionHeaderEditorFn(_ context.Context, req *http.Request) error {
req.Header.Set("X-Corbado-SDK-Version", fmt.Sprintf("Go SDK %s", Version))
func newSDKHeaderEditorFn(_ context.Context, req *http.Request) error {
sdk := struct {
Name string `json:"name"`
SdkVersion string `json:"sdkVersion"`
LanguageVersion string `json:"languageVersion"`
}{
Name: "Go SDK",
SdkVersion: Version,
LanguageVersion: runtime.Version(),
}

marshaled, err := json.Marshal(sdk)
if err != nil {
return errors.WithStack(err)
}

req.Header.Set("X-Corbado-SDK", string(marshaled))

return nil
}
Loading

0 comments on commit 93655ad

Please sign in to comment.