-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
101 lines (81 loc) · 1.93 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
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
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/mitchellh/go-homedir"
)
const (
baseAuthURL = "https://stackoverflow.com/oauth/dialog"
authClientId = "26062"
authKey = "w1BFZmzoMKahE3t5WYlEBA(("
scope = "no_expiry"
redirectUri = "http://localhost:6789/sotui-callback"
)
var token string
func GetToken() string {
if token != "" {
return token
}
dir, err := homedir.Dir()
if err != nil {
panic("Unable to get home directory")
}
filePath := dir + "/.sotui/token"
access_token, err := ioutil.ReadFile(filePath)
if err != nil {
return ""
} else {
token = string(access_token)
}
return token
}
func SetToken(access_token string) {
dir, err := homedir.Dir()
if err != nil {
panic("Unable to get home directory")
}
filePath := dir + "/.sotui/token"
if _, err := os.Stat(filePath); os.IsNotExist(err) {
os.Mkdir(dir+"/.sotui", 0777)
} //TODO: More restrictive permissions
err = os.WriteFile(filePath, []byte(access_token), 0777)
if err != nil {
panic(err)
}
token = access_token
}
func Oauth2() {
m := http.NewServeMux()
s := http.Server{Addr: ":6789", Handler: m}
m.HandleFunc("/sotui-callback", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
html := `
<div>
<p>Authenticating... , make sure javascript is enabled</p>
<script>
window.location.href = window.location.href.replace("#", "?")
</script>
</div>
`
if r.URL.RawQuery == "" {
w.Write([]byte(html))
} else {
token := r.URL.Query().Get("access_token")
if token == "" {
w.Write([]byte("Authentication failed!"))
panic("Unable to get token")
} else {
w.Write([]byte("Authentication successful!"))
SetToken(token)
go s.Shutdown(context.Background())
}
}
})
s.ListenAndServe()
}
func GetAuthURL() string {
return fmt.Sprintf("%s?client_id=%s&scope=%s&redirect_uri=%s", baseAuthURL, authClientId, scope, redirectUri)
}