/
auth_callback.go
98 lines (79 loc) · 1.72 KB
/
auth_callback.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
package doitserver
import (
"fmt"
"html/template"
"net/http"
"github.com/markbates/goth/gothic"
)
type AuthCallback struct {
consumers *Consumers
key string
}
var _ http.Handler = &AuthCallback{}
func NewAuthCallback(consumers *Consumers, key string) *AuthCallback {
return &AuthCallback{
consumers: consumers,
key: key,
}
}
func (ac *AuthCallback) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session, err := gothic.Store.Get(r, "doit-server")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var isCLIAuth bool
id := session.Values["current-auth"].(string)
if _, ok := session.Values["cli-auth"]; ok {
isCLIAuth = true
}
user, err := gothic.CompleteUserAuth(w, r)
if !isCLIAuth {
c := ac.consumers.Get(id)
if err != nil {
c <- Consumer{
ID: id,
Err: err.Error(),
Message: "unble to complete authorization",
}
return
}
c <- Consumer{
ID: id,
AccessToken: user.AccessToken,
}
fmt.Fprintf(w, updateTemplate)
return
}
if err != nil {
fmt.Fprintln(w, "Unable to retrieve access token")
delete(session.Values, "cli-auth")
_ = session.Save(r, w)
return
}
delete(session.Values, "cli-auth")
_ = session.Save(r, w)
t, _ := template.New("cliTemplate").Parse(cliTemplate)
t.Execute(w, user)
}
var updateTemplate = `
<!doctype html>
<html lang="en">
<body>
<script>
window.location = "https://github.com/digitalocean/doctl/blob/master/README.md";
</script>
</body>
</html>`
var cliTemplate = `
<!doctype html>
<html lang="en">
<body>
<p>
Please copy the access token, switch back to doit cli and it paste the following token:
</p>
<p>
<strong>{{ .AccessToken }}</strong>
</p>
</body>
</html>`