1
0
mirror of https://git.sr.ht/~sircmpwn/aerc synced 2024-11-23 08:32:12 +01:00
aerc/lib/oauthbearer.go
R Chowdhury f4dc7e1f74 Add oauthbearer support for SMTP
This piggybacks on the existing IMAP support, and uses the same
configuration format (my local testing example has the IMAP and SMTP
lines almost copy-pasted from one another).

It's a little clumsy in that a new token is negotiated for every
`Send()` command, but it's a start...
2020-08-13 07:44:43 +02:00

43 lines
996 B
Go

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)
}