about summary refs log tree commit diff stats
path: root/lib/oauthbearer.go
blob: 1030696e3e9dd6690b4ee8614f92f2b4f56374b1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package lib

import (
	"context"
	"fmt"
	"github.com/emersion/go-imap/client"
	"github.com/emersion/go-sasl"
	"golang.org/x/oauth2"
)

type OAuthBearer struct {
	OAuth2  *oauth2.Config
	Enabled bool
}

func (c *OAuthBearer) ExchangeRefreshToken(refreshToken string) (*oauth2.Token, error) {
	token := new(oauth2.Token)
	token.RefreshToken = refreshToken
	token.TokenType = "Bearer"
	return c.OAuth2.TokenSource(context.TODO(), token).Token()
}

func (c *OAuthBearer) Authenticate(username string, password string, client *client.Client) error {
	if ok, err := client.SupportAuth(sasl.OAuthBearer); err != nil || !ok {
		return fmt.Errorf("OAuthBearer not supported %v", err)
	}

	if c.OAuth2.Endpoint.TokenURL != "" {
		token, err := c.ExchangeRefreshToken(password)
		if err != nil {
			return err
		}
		password = token.AccessToken
	}

	saslClient := sasl.NewOAuthBearerClient(&sasl.OAuthBearerOptions{
		Username: username,
		Token:    password,
	})

	return client.Authenticate(saslClient)
}