2019-07-10 21:00:28 +02:00
|
|
|
package lib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2022-07-31 22:16:40 +02:00
|
|
|
|
2019-07-10 21:00:28 +02:00
|
|
|
"github.com/emersion/go-imap/client"
|
|
|
|
"github.com/emersion/go-sasl"
|
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
|
|
|
type OAuthBearer struct {
|
|
|
|
OAuth2 *oauth2.Config
|
|
|
|
Enabled bool
|
|
|
|
}
|
|
|
|
|
2020-05-26 13:29:58 +02:00
|
|
|
func (c *OAuthBearer) ExchangeRefreshToken(refreshToken string) (*oauth2.Token, error) {
|
2019-07-10 21:00:28 +02:00
|
|
|
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 {
|
2022-07-31 15:15:27 +02:00
|
|
|
return fmt.Errorf("OAuthBearer not supported %w", err)
|
2019-07-10 21:00:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if c.OAuth2.Endpoint.TokenURL != "" {
|
2020-05-26 13:29:58 +02:00
|
|
|
token, err := c.ExchangeRefreshToken(password)
|
2019-07-10 21:00:28 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
password = token.AccessToken
|
|
|
|
}
|
|
|
|
|
|
|
|
saslClient := sasl.NewOAuthBearerClient(&sasl.OAuthBearerOptions{
|
|
|
|
Username: username,
|
|
|
|
Token: password,
|
|
|
|
})
|
|
|
|
|
|
|
|
return client.Authenticate(saslClient)
|
|
|
|
}
|