-
Notifications
You must be signed in to change notification settings - Fork 0
/
authorize.go
104 lines (98 loc) · 2.96 KB
/
authorize.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
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"net"
"net/http"
"os"
"time"
"github.com/smlx/jiratime/internal/client"
"github.com/smlx/jiratime/internal/config"
"golang.org/x/oauth2"
)
// AuthorizeCmd represents the `authorize` or `auth` command.
type AuthorizeCmd struct{}
func startRedirectServer(ctx context.Context, state string, c chan<- string) {
mux := http.NewServeMux()
// Create a new redirect route
mux.HandleFunc("/oauth/redirect", func(w http.ResponseWriter, r *http.Request) {
// First, we need to get the value of the `code` query param
err := r.ParseForm()
if err != nil {
fmt.Fprintf(os.Stdout, "could not parse query: %v", err)
w.WriteHeader(http.StatusBadRequest)
}
c <- r.FormValue("code")
_, _ = w.Write([]byte("Authorization successful. You may now close this page."))
})
s := &http.Server{
Addr: ":8080",
Handler: mux,
BaseContext: func(_ net.Listener) context.Context { return ctx },
}
log.Println(s.ListenAndServe())
}
// randomHex returns a string consisting of n hex-encoded random bytes. Because
// the string is hex encoded its length will be 2*n.
func randomHex(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", fmt.Errorf("couldn't read random bytes: %v", err)
}
return hex.EncodeToString(bytes), nil
}
// Run the Authorize command.
func (cmd *AuthorizeCmd) Run() error {
ctx, cancel := getContext(30 * time.Second)
defer cancel()
// read the config file to get the oauth2 clientID and secret
auth, err := config.ReadAuth()
if err != nil {
return fmt.Errorf("couldn't load config: %v", err)
}
// sanity check configuration
if auth == nil {
return fmt.Errorf("couldn't find oauth2 configuration")
}
if auth.ClientID == "" || auth.Secret == "" {
return fmt.Errorf("missing ClientID or Secret in oauth2 configuration")
}
// generate a random state
state, err := randomHex(16)
if err != nil {
return fmt.Errorf("couldn't generate state: %v", err)
}
// get the OAuth2 config object
conf := client.GetOAuth2Config(auth)
// Redirect user to consent page to ask for permission
// for the scopes specified above.
url := conf.AuthCodeURL(state,
oauth2.SetAuthURLParam("audience", "api.atlassian.com"),
oauth2.SetAuthURLParam("prompt", "consent"))
fmt.Printf("Visit this URL to authorize jiratime: %s\n", url)
// start the server to handle the redirect after authorization
c := make(chan string, 1)
go startRedirectServer(ctx, state, c)
var code string
select {
case code = <-c:
// received code
case <-ctx.Done():
return fmt.Errorf("timed out waiting for code")
}
// use a custom HTTP client with a reasonable timeout
tok, err := conf.Exchange(
context.WithValue(ctx, oauth2.HTTPClient,
&http.Client{Timeout: 4 * time.Second}), code)
if err != nil {
log.Fatal(err)
}
auth.Token = tok
if err = config.WriteAuth(auth); err != nil {
return fmt.Errorf("couldn't write config: %v", err)
}
return nil
}