-
Notifications
You must be signed in to change notification settings - Fork 0
/
xoauth2.go
78 lines (70 loc) · 2.11 KB
/
xoauth2.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"context"
"fmt"
"net/smtp"
"golang.org/x/oauth2"
)
type xOAuth2 struct {
useremail string
config *oauth2.Config
token *oauth2.Token
}
func XOAuth2(useremail string, config *oauth2.Config, token *oauth2.Token) smtp.Auth {
return &xOAuth2{useremail, config, token}
}
func (a *xOAuth2) Start(server *smtp.ServerInfo) (string, []byte, error) {
if !server.TLS {
return "", nil, fmt.Errorf("unencrypted connection")
}
tsrc := (a.config).TokenSource(context.Background(), a.token)
if t, err := tsrc.Token(); err == nil {
str := fmt.Sprintf("user=%sauth=Bearer %s", a.useremail, t.AccessToken)
resp := []byte(str)
return "XOAUTH2", resp, nil
} else {
return "", []byte{}, err
}
}
func (a *xOAuth2) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
// We've already sent everything.
return nil, fmt.Errorf("unexpected server challenge")
}
return nil, nil
}
func Gmail_Generate_Token(client_id, client_secret, refresh_token string) (*oauth2.Config, *oauth2.Token) {
config := &oauth2.Config{
ClientID: client_id,
ClientSecret: client_secret,
Endpoint: oauth2.Endpoint{
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://oauth2.googleapis.com/token",
AuthStyle: 0,
},
RedirectURL: "https://localhost",
Scopes: []string{"https://mail.google.com/"},
}
token := &oauth2.Token{
TokenType: "Bearer",
RefreshToken: refresh_token,
}
return config, token
}
func Outlook_Generate_Token(client_id, refresh_token string) (*oauth2.Config, *oauth2.Token) {
config := &oauth2.Config{
ClientID: client_id,
Endpoint: oauth2.Endpoint{
AuthURL: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
TokenURL: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
AuthStyle: oauth2.AuthStyleAutoDetect,
},
RedirectURL: "https://localhost:8080",
Scopes: []string{"offline_access", "https://outlook.office365.com/IMAP.AccessAsUser.All", "https://outlook.office365.com/SMTP.Send"},
}
token := &oauth2.Token{
TokenType: "Bearer",
RefreshToken: refresh_token,
}
return config, token
}