| 1 |
// |
| 2 |
// This code is derived from the go-sasl library. |
| 3 |
// |
| 4 |
// Copyright (c) 2016 emersion |
| 5 |
// Copyright (c) 2022, Oracle and/or its affiliates. |
| 6 |
// |
| 7 |
// SPDX-License-Identifier: MIT |
| 8 |
|
| 9 |
package auth |
| 10 |
|
| 11 |
import ( |
| 12 |
"encoding/json" |
| 13 |
"fmt" |
| 14 |
|
| 15 |
"github.com/emersion/go-sasl" |
| 16 |
) |
| 17 |
|
| 18 |
// An XOAUTH2 error. |
| 19 |
type Xoauth2Error struct { |
| 20 |
Status string `json:"status"` |
| 21 |
Schemes string `json:"schemes"` |
| 22 |
Scope string `json:"scope"` |
| 23 |
} |
| 24 |
|
| 25 |
// Implements error. |
| 26 |
func (err *Xoauth2Error) Error() string { |
| 27 |
return fmt.Sprintf("XOAUTH2 authentication error (%v)", err.Status) |
| 28 |
} |
| 29 |
|
| 30 |
const XoauthMechanism string = "XOAUTH2" |
| 31 |
|
| 32 |
type xoauth2Client struct { |
| 33 |
Username string |
| 34 |
Token string |
| 35 |
} |
| 36 |
|
| 37 |
func (a *xoauth2Client) Start() (mech string, ir []byte, err error) { |
| 38 |
mech = XoauthMechanism |
| 39 |
ir = []byte("user=" + a.Username + "\x01auth=Bearer " + a.Token + "\x01\x01") |
| 40 |
return |
| 41 |
} |
| 42 |
|
| 43 |
func (a *xoauth2Client) Next(challenge []byte) ([]byte, error) { |
| 44 |
// Server sent an error response |
| 45 |
xoauth2Err := &Xoauth2Error{} |
| 46 |
if err := json.Unmarshal(challenge, xoauth2Err); err != nil { |
| 47 |
return nil, err |
| 48 |
} else { |
| 49 |
return nil, xoauth2Err |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
// An implementation of the XOAUTH2 authentication mechanism, as |
| 54 |
// described in https://developers.google.com/gmail/xoauth2_protocol. |
| 55 |
func NewXoauth2Client(username, token string) sasl.Client { |
| 56 |
return &xoauth2Client{username, token} |
| 57 |
} |