-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.go
176 lines (135 loc) · 4.12 KB
/
token.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package token
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"path"
"strings"
"github.com/CyCoreSystems/azure-auth/pkg/config"
"golang.org/x/oauth2"
)
func tokenFileName() string {
cfgDir, err := os.UserConfigDir()
if err != nil {
log.Fatalln("failed to determine configuration directory:", err)
}
return path.Join(cfgDir, "azure", "token.json")
}
// Get returns a Token, delegating the to browser, if needed.
func Get(pCtx context.Context, cfg *config.Config) (*oauth2.Token,error) {
ctx, cancel := context.WithCancel(pCtx)
defer cancel()
ts := oauth2.ReuseTokenSource(loadFileToken(), &BrowserTokenSource{
ctx: ctx,
cancel: cancel,
cfg: cfg,
})
return ts.Token()
}
// XOAuth2Token returns an XOAuth2 token formatted for use in SMTP and IMAP settings.
func XOAuth2Token(ctx context.Context, cfg *config.Config) (string, error) {
tok, err := Get(ctx, cfg)
if err != nil {
return "", fmt.Errorf("failed to retrieve token: %w", err)
}
return fmt.Sprintf("user=%s\x01auth=Bearer %s\x01\x01", cfg.Username, tok.AccessToken), nil
}
func exporter(cfg *config.Config) {
var ts oauth2.TokenSource
token, err := ts.Token()
if err != nil {
log.Fatalln("failed to retrieve token:", err)
}
xoauth2 := fmt.Sprintf("user=%s\x01auth=Bearer %s\x01\x01", cfg.Username, token.AccessToken)
out := struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
XOAuth2 string `json:"xoauth2"`
}{
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
XOAuth2: base64.StdEncoding.EncodeToString([]byte(xoauth2)),
}
if err := json.NewEncoder(os.Stdout).Encode(&out); err != nil {
log.Fatalln("failed to encode output:", err)
}
return
}
func loadFileToken() *oauth2.Token {
tokenFileData, err := os.ReadFile(tokenFileName())
if err != nil {
return nil
}
token := new(oauth2.Token)
if err := json.Unmarshal(tokenFileData, token); err != nil {
log.Printf("failed to parse token from file %q: %s", tokenFileName(), err.Error())
return nil
}
return token
}
type BrowserTokenSource struct {
ctx context.Context
cancel context.CancelFunc
cfg *config.Config
token *oauth2.Token
}
// Token retrieves a token from a browser interaction.
func (s *BrowserTokenSource) Token() (*oauth2.Token, error) {
srv := &http.Server{
Addr: fmt.Sprintf(":%d", s.cfg.Redirect.Port),
}
go func() {
http.HandleFunc(fmt.Sprintf("/%s", strings.Trim(s.cfg.Redirect.Path,"/")), s.redirectHandler())
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalln("HTTP server died unexpectedly:", err)
}
}()
if err := exec.Command("xdg-open", s.cfg.OAuth2().AuthCodeURL("state", oauth2.AccessTypeOffline)).Run(); err != nil {
fmt.Println("failed to launch browser automatically:", err)
fmt.Println()
fmt.Println("1. Ensure that you are logged in as your user in your browser.")
fmt.Println()
fmt.Println("2. Open the following link and authorise XOAUTH2 token:")
fmt.Println(s.cfg.OAuth2().AuthCodeURL("state", oauth2.AccessTypeOffline))
fmt.Println()
}
<-s.ctx.Done()
srv.Shutdown(s.ctx)
return s.token, nil
}
func (s *BrowserTokenSource) redirectHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
token, err := s.cfg.OAuth2().Exchange(s.ctx, code)
if err != nil {
log.Fatalf("Failed to exchange authorisation code for token: %v.", err)
}
s.token = token
// Store new token to file
if err := s.storeToken(); err != nil {
log.Println("failed to store updated token:", err)
}
defer s.cancel()
if _, err := w.Write([]byte("OK")); err != nil {
log.Println("failed to write response:", err)
}
}
}
func (s *BrowserTokenSource) storeToken() error {
if s.token == nil {
return fmt.Errorf("no token")
}
data, err := json.Marshal(s.token)
if err != nil {
return fmt.Errorf("failed to encode token to JSON: %w", err)
}
if err := os.WriteFile(tokenFileName(), data, os.FileMode(0600)); err != nil {
return fmt.Errorf("failed to write token file %q: %w", tokenFileName(), err)
}
return nil
}