oauth

package
v0.0.0-...-3aef210 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2024 License: MPL-2.0 Imports: 6 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNoTokenSources = errors.New("no token sources")

Functions

This section is empty.

Types

type CombinedTokenSources

type CombinedTokenSources []oauth2.TokenSource

func (CombinedTokenSources) Token

func (ts CombinedTokenSources) Token() (*oauth2.Token, error)

type TokenSource

type TokenSource struct {
	// LoginMethod is the login method to use to get the token.
	LoginMethod login.Method

	// Credentials are the credentials to use to get the token.
	Credentials *login.Credentials

	// Listener is the listener to call when the token is updated.
	// It is called with the new token and the cookies.
	// If the listener is nil, it is not called.
	Listener func(token *oauth2.Token, cookies []*http.Cookie)
}

TokenSource is a token source that uses a login method to get the oauth token. It logins to Digiposte on every .Token() call. To avoid this, wrap it with oauth2.ReuseTokenSource.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	"golang.org/x/oauth2"

	"github.com/holyhope/digiposte-go-sdk/internal/utils"
	"github.com/holyhope/digiposte-go-sdk/login"
	"github.com/holyhope/digiposte-go-sdk/login/chrome"
	"github.com/holyhope/digiposte-go-sdk/login/oauth"
)

func main() {
	path, err := utils.GetChrome(context.Background())
	if err != nil {
		panic(fmt.Errorf("get chrome: %w", err))
	}

	loginMethod, err := chrome.New(
		chrome.WithURL(os.Getenv("DIGIPOSTE_URL")),
		chrome.WithRefreshFrequency(500*time.Millisecond),
		chrome.WithScreenShortOnError(),
		chrome.WithTimeout(3*time.Minute),
		chrome.WithBinary(path),
	)
	if err != nil {
		panic(fmt.Errorf("new chrome login method: %w", err))
	}

	oauthTokenSource := oauth2.ReuseTokenSource(nil, &oauth.TokenSource{
		LoginMethod: loginMethod,
		Credentials: &login.Credentials{
			Username:  os.Getenv("DIGIPOSTE_USERNAME"),
			Password:  os.Getenv("DIGIPOSTE_PASSWORD"),
			OTPSecret: os.Getenv("DIGIPOSTE_OTP_SECRET"),
		},
		Listener: func(token *oauth2.Token, _ []*http.Cookie) {
			fmt.Printf("Token updated: %s\n", token.Type())
		},
	})

	token, err := oauthTokenSource.Token()
	if err != nil {
		panic(fmt.Errorf("get token: %w", err))
	}

	fmt.Printf("Token valid: %v\n", token.Valid())

}
Output:

Token updated: Bearer
Token valid: true

func (*TokenSource) Token

func (ts *TokenSource) Token() (*oauth2.Token, error)

Token returns a new token. It waits for the listener to be called before returning the token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL