-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
66 lines (57 loc) · 1.26 KB
/
auth.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
package app
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
"github.com/notomo/gmailagg/pkg/gcsext"
"github.com/notomo/gmailagg/pkg/gmailext"
)
type Opener interface {
Open(ctx context.Context, url string) error
}
func Authorize(
ctx context.Context,
gmailCredentials string,
tokenFilePath string,
opener Opener,
timeout time.Duration,
port uint,
baseTransport http.RoundTripper,
dryRun bool,
) (retErr error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
tokenWriter, err := gcsext.NewWriterByPath(ctx, tokenFilePath, baseTransport, dryRun)
if err != nil {
return fmt.Errorf("new token writer: %w", err)
}
defer func() {
if err != nil {
cancel()
}
if err := tokenWriter.Close(); err != nil {
retErr = errors.Join(retErr, fmt.Errorf("close token writer: %w", err))
}
}()
ctx, cancelForTimeout := context.WithTimeout(ctx, timeout)
defer cancelForTimeout()
token, err := gmailext.Authorize(
ctx,
gmailCredentials,
opener,
port,
baseTransport,
)
if err != nil {
return fmt.Errorf("gmail authorize: %w", err)
}
encorder := json.NewEncoder(tokenWriter)
encorder.SetIndent("", " ")
if err := encorder.Encode(token); err != nil {
return fmt.Errorf("json encode token: %w", err)
}
return nil
}