-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth_listener.go
113 lines (96 loc) · 2.31 KB
/
oauth_listener.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
package gdrive
import (
"context"
"net"
"net/http"
"sync"
"github.com/KJHJason/Cultured-Downloader-Logic/logger"
"golang.org/x/oauth2"
)
// Example OAuth callback URL:
// http://localhost:8080/?state=state-token&code=<code>&scope=https://www.googleapis.com/auth/drive.readonly%20https://www.googleapis.com/auth/drive.metadata.readonly
func getOAuthCode(w http.ResponseWriter, r *http.Request) {
// get the code from the URL
code := r.FormValue("code")
if code == "" {
http.Error(w, "Code not found", http.StatusBadRequest)
return
}
updateOauthCode(code)
w.WriteHeader(http.StatusOK)
w.Write([]byte("The authentication flow has completed. You may close this window."))
}
func startOAuthServer(ctx context.Context) error {
childCtx, cancel := context.WithCancel(ctx)
defer cancel()
mux := http.NewServeMux()
mux.HandleFunc("/", getOAuthCode)
server := &http.Server{
Addr: ":8080",
BaseContext: func(listener net.Listener) context.Context {
return childCtx
},
Handler: mux,
}
var startUpErr error
go func() {
logger.MainLogger.Info("Starting OAuth listener server...")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
// start up error
startUpErr = err
logger.MainLogger.Error("OAuth listener server error: " + err.Error())
cancel()
}
}()
<-childCtx.Done()
if startUpErr != nil {
return startUpErr
}
logger.MainLogger.Info("Shutting down OAuth listener server...")
return server.Shutdown(ctx)
}
var (
oauthCode string
oauthMu sync.RWMutex
)
func updateOauthCode(code string) {
oauthMu.Lock()
oauthCode = code
oauthMu.Unlock()
}
func getOauthCode() string {
oauthMu.RLock()
defer oauthMu.RUnlock()
return oauthCode
}
func StartOAuthListener(ctx context.Context, config *oauth2.Config) (*oauth2.Token, error) {
updateOauthCode("")
srvCtx, cancel := context.WithCancel(ctx)
defer cancel()
defer updateOauthCode("")
var srvErr error
go func() {
srvErr = startOAuthServer(srvCtx)
}()
codeLoop:
for {
select {
case <-ctx.Done():
return nil, context.Canceled
case <-srvCtx.Done():
if srvErr != nil {
return nil, srvErr
}
default:
if getOauthCode() != "" {
break codeLoop
}
}
}
// process the code
token, err := ProcessAuthCode(ctx, getOauthCode(), config)
if err != nil {
return nil, err
}
return token, nil
}