Repository navigation
Expand file tree
/
Copy pathapp.go
More file actions
91 lines (79 loc) · 2.17 KB
/
Copy pathapp.go
File metadata and controls
91 lines (79 loc) · 2.17 KB
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
package main
import (
"fmt"
"net/http"
"net/url"
"encoding/base64"
"crypto/rand"
"encoding/json"
)
const APP_KEY = "<YOUR APP KEY>"
const APP_SECRET = "<YOUR APP SECRET>"
func getCallbackURL(r *http.Request) string {
scheme := "http"
forwarded := r.Header.Get("X-Forwarded-Proto")
if len(forwarded) > 0 {
scheme = forwarded
}
return (&url.URL{
Scheme: scheme,
Host: r.Host,
Path: "/callback",
}).String()
}
func index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
b := make([]byte, 18)
rand.Read(b)
csrf := base64.StdEncoding.EncodeToString(b)
http.SetCookie(w, &http.Cookie{Name: "csrf", Value: csrf})
http.Redirect(w, r, "https://www.dropbox.com/1/oauth2/authorize?" +
url.Values{
"client_id": {APP_KEY},
"redirect_uri": {getCallbackURL(r)},
"response_type": {"code"},
"state": {csrf},
}.Encode(), 302)
}
func decodeResponse(r *http.Response, m interface{}) {
defer r.Body.Close()
json.NewDecoder(r.Body).Decode(m)
}
func callback(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: "csrf", MaxAge: -1})
state := r.FormValue("state");
cookie, _ := r.Cookie("csrf")
if cookie == nil || cookie.Value != state {
http.Error(w, "Possible CSRF attack.", http.StatusUnauthorized);
return
}
resp, err := http.PostForm(fmt.Sprintf("https://%s:%s@api.dropbox.com/1/oauth2/token", APP_KEY, APP_SECRET),
url.Values{
"redirect_uri": {getCallbackURL(r)},
"code": {r.FormValue("code")},
"grant_type": {"authorization_code"},
})
if err != nil {
panic(err);
}
tokenMessage := struct { Access_token string }{}
decodeResponse(resp, &tokenMessage)
token := tokenMessage.Access_token
req, _ := http.NewRequest("GET", "https://api.dropbox.com/1/account/info", nil)
req.Header.Set("Authorization", "Bearer " + token)
resp, err = http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
nameMessage := struct { Display_name string }{}
decodeResponse(resp, &nameMessage)
fmt.Fprintf(w, "Successfully authenticated as %s.", nameMessage.Display_name)
}
func main() {
http.HandleFunc("/callback", callback)
http.HandleFunc("/", index)
http.ListenAndServe(":5000", nil)
}