Debian Codegraph @

examples/discogs/main.go

raw symbols SCIP
1 // Copyright 2014 Gary Burd
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"): you may
4 // not use this file except in compliance with the License. You may obtain
5 // a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations
13 // under the License.
14
15 package main
16
17 import (
18 "encoding/json"
19 "flag"
20 "fmt"
21 "io/ioutil"
22 "log"
23 "net/http"
24 "net/url"
25 "text/template"
26
27 "github.com/gomodule/oauth1/examples/session"
28 "github.com/gomodule/oauth1/oauth"
29 )
30
31 // Session state keys.
32 const (
33 tempCredKey = "tempCred"
34 tokenCredKey = "tokenCred"
35 )
36
37 var oauthClient = oauth.Client{
38 TemporaryCredentialRequestURI: "https://api.discogs.com/oauth/request_token",
39 ResourceOwnerAuthorizationURI: "https://www.discogs.com/oauth/authorize",
40 TokenRequestURI: "https://api.discogs.com/oauth/access_token",
41 Header: http.Header{"User-Agent": {"ExampleDiscogsClient/1.0"}},
42 }
43
44 var credPath = flag.String("config", "config.json", "Path to configuration file containing the application's credentials.")
45
46 func readCredentials() error {
47 b, err := ioutil.ReadFile(*credPath)
48 if err != nil {
49 return err
50 }
51 return json.Unmarshal(b, &oauthClient.Credentials)
52 }
53
54 // serveLogin gets the OAuth temp credentials and redirects the user to the
55 // Discogs' authorization page.
56 func serveLogin(w http.ResponseWriter, r *http.Request) {
57 callback := "http://" + r.Host + "/callback"
58 tempCred, err := oauthClient.RequestTemporaryCredentials(nil, callback, nil)
59 if err != nil {
60 http.Error(w, "Error getting temp cred, "+err.Error(), 500)
61 return
62 }
63 s := session.Get(r)
64 s[tempCredKey] = tempCred
65 if err := session.Save(w, r, s); err != nil {
66 http.Error(w, "Error saving session , "+err.Error(), 500)
67 return
68 }
69 http.Redirect(w, r, oauthClient.AuthorizationURL(tempCred, nil), 302)
70 }
71
72 // serveOAuthCallback handles callbacks from the OAuth server.
73 func serveOAuthCallback(w http.ResponseWriter, r *http.Request) {
74 s := session.Get(r)
75 tempCred, _ := s[tempCredKey].(*oauth.Credentials)
76 if tempCred == nil || tempCred.Token != r.FormValue("oauth_token") {
77 http.Error(w, "Unknown oauth_token.", 500)
78 return
79 }
80 tokenCred, _, err := oauthClient.RequestToken(nil, tempCred, r.FormValue("oauth_verifier"))
81 if err != nil {
82 http.Error(w, "Error getting request token, "+err.Error(), 500)
83 return
84 }
85 delete(s, tempCredKey)
86 s[tokenCredKey] = tokenCred
87 if err := session.Save(w, r, s); err != nil {
88 http.Error(w, "Error saving session , "+err.Error(), 500)
89 return
90 }
91 http.Redirect(w, r, "/", 302)
92 }
93
94 // serveLogout clears the token credentials
95 func serveLogout(w http.ResponseWriter, r *http.Request) {
96 s := session.Get(r)
97 delete(s, tokenCredKey)
98 if err := session.Save(w, r, s); err != nil {
99 http.Error(w, "Error saving session , "+err.Error(), 500)
100 return
101 }
102 http.Redirect(w, r, "/", 302)
103 }
104
105 // authHandler reads the auth cookie and invokes a handler with the result.
106 type authHandler struct {
107 handler func(w http.ResponseWriter, r *http.Request, c *oauth.Credentials)
108 optional bool
109 }
110
111 func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
112 cred, _ := session.Get(r)[tokenCredKey].(*oauth.Credentials)
113 if cred == nil && !h.optional {
114 http.Error(w, "Not logged in.", 403)
115 return
116 }
117 h.handler(w, r, cred)
118 }
119
120 // getJSON gets a resource from the Discogs API server and decodes the result as JSON.
121 func getJSON(cred *oauth.Credentials, endpoint string, form url.Values, v interface{}) error {
122 resp, err := oauthClient.Get(nil, cred, "https://api.discogs.com"+endpoint, form)
123 if err != nil {
124 return err
125 }
126 defer resp.Body.Close()
127 if resp.StatusCode != 200 {
128 return fmt.Errorf("server returned status %d", resp.StatusCode)
129 }
130 return json.NewDecoder(resp.Body).Decode(v)
131 }
132
133 // respond responds to a request by executing the html template t with data.
134 func respond(w http.ResponseWriter, t *template.Template, data interface{}) {
135 w.Header().Set("Content-Type", "text/html; charset=utf-8")
136 if err := t.Execute(w, data); err != nil {
137 log.Print(err)
138 }
139 }
140
141 func serveHome(w http.ResponseWriter, r *http.Request, cred *oauth.Credentials) {
142 if r.URL.Path != "/" {
143 http.NotFound(w, r)
144 return
145 }
146 if cred == nil {
147 data := struct{ Host string }{r.Host}
148 respond(w, homeLoggedOutTmpl, &data)
149 } else {
150 var data struct {
151 Username string
152 }
153 if err := getJSON(cred, "/oauth/identity", nil, &data); err != nil {
154 http.Error(w, err.Error(), 500)
155 return
156 }
157 respond(w, homeTmpl, &data)
158 }
159 }
160
161 var httpAddr = flag.String("addr", ":8080", "HTTP server address")
162
163 func main() {
164 flag.Parse()
165 if err := readCredentials(); err != nil {
166 log.Fatalf("Error reading configuration, %v", err)
167 }
168
169 http.Handle("/", &authHandler{handler: serveHome, optional: true})
170 http.HandleFunc("/login", serveLogin)
171 http.HandleFunc("/logout", serveLogout)
172 http.HandleFunc("/callback", serveOAuthCallback)
173 if err := http.ListenAndServe(*httpAddr, nil); err != nil {
174 log.Fatalf("Error listening, %v", err)
175 }
176 }
177
178 var (
179 homeLoggedOutTmpl = template.Must(template.New("loggedout").Parse(
180 `<html>
181 <body>
182 <a href="/login">login</a>
183 </body>
184 </html>`))
185
186 homeTmpl = template.Must(template.New("home").Parse(
187 `<html>
188 <body>
189 <p>Welcome {{.Username}}!
190 </body></html>`))
191 )