Debian Codegraph @

examples/smugmug/main.go

raw symbols SCIP
1 // Copyright 2013 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: "http://api.smugmug.com/services/oauth/getRequestToken.mg",
39 ResourceOwnerAuthorizationURI: "http://api.smugmug.com/services/oauth/authorize.mg",
40 TokenRequestURI: "http://api.smugmug.com/services/oauth/getAccessToken.mg",
41 }
42
43 var credPath = flag.String("config", "config.json", "Path to configuration file containing the application's credentials.")
44
45 func readCredentials() error {
46 b, err := ioutil.ReadFile(*credPath)
47 if err != nil {
48 return err
49 }
50 return json.Unmarshal(b, &oauthClient.Credentials)
51 }
52
53 // serveLogin gets the OAuth temp credentials and redirects the user to the
54 // SmugMug's authorization page.
55 func serveLogin(w http.ResponseWriter, r *http.Request) {
56 callback := "http://" + r.Host + "/callback"
57 tempCred, err := oauthClient.RequestTemporaryCredentials(nil, callback, nil)
58 if err != nil {
59 http.Error(w, "Error getting temp cred, "+err.Error(), 500)
60 return
61 }
62 s := session.Get(r)
63 s[tempCredKey] = tempCred
64 if err := session.Save(w, r, s); err != nil {
65 http.Error(w, "Error saving session , "+err.Error(), 500)
66 return
67 }
68 http.Redirect(w, r, oauthClient.AuthorizationURL(tempCred, nil), 302)
69 }
70
71 // serveOAuthCallback handles callbacks from the OAuth server.
72 func serveOAuthCallback(w http.ResponseWriter, r *http.Request) {
73 s := session.Get(r)
74 tempCred, _ := s[tempCredKey].(*oauth.Credentials)
75 if tempCred == nil || tempCred.Token != r.FormValue("oauth_token") {
76 http.Error(w, "Unknown oauth_token.", 500)
77 return
78 }
79 tokenCred, _, err := oauthClient.RequestToken(nil, tempCred, r.FormValue("oauth_verifier"))
80 if err != nil {
81 http.Error(w, "Error getting request token, "+err.Error(), 500)
82 return
83 }
84 delete(s, tempCredKey)
85 s[tokenCredKey] = tokenCred
86 if err := session.Save(w, r, s); err != nil {
87 http.Error(w, "Error saving session , "+err.Error(), 500)
88 return
89 }
90 http.Redirect(w, r, "/", 302)
91 }
92
93 // serveLogout clears the authentication cookie.
94 func serveLogout(w http.ResponseWriter, r *http.Request) {
95 s := session.Get(r)
96 delete(s, tokenCredKey)
97 if err := session.Save(w, r, s); err != nil {
98 http.Error(w, "Error saving session , "+err.Error(), 500)
99 return
100 }
101 http.Redirect(w, r, "/", 302)
102 }
103
104 // authHandler reads the auth cookie and invokes a handler with the result.
105 type authHandler struct {
106 handler func(w http.ResponseWriter, r *http.Request, c *oauth.Credentials)
107 optional bool
108 }
109
110 func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
111 cred, _ := session.Get(r)[tokenCredKey].(*oauth.Credentials)
112 if cred == nil && !h.optional {
113 http.Error(w, "Not logged in.", 403)
114 return
115 }
116 h.handler(w, r, cred)
117 }
118
119 const apiURL = "https://api.smugmug.com/services/api/json/1.3.0/"
120
121 // apiGet issues a GET request to the SmugMug API and decodes the response JSON to data.
122 func apiGet(cred *oauth.Credentials, form url.Values, data interface{}) error {
123 resp, err := oauthClient.Get(nil, cred, apiURL, form)
124 if err != nil {
125 return err
126 }
127 defer resp.Body.Close()
128 return decodeResponse(resp, data)
129 }
130
131 // apiPost issues a POST request to the SmugMug API and decodes the response JSON to data.
132 func apiPost(cred *oauth.Credentials, urlStr string, form url.Values, data interface{}) error {
133 resp, err := oauthClient.Post(nil, cred, apiURL, form)
134 if err != nil {
135 return err
136 }
137 defer resp.Body.Close()
138 return decodeResponse(resp, data)
139 }
140
141 // decodeResponse decodes the JSON response from the Twitter API.
142 func decodeResponse(resp *http.Response, data interface{}) error {
143 if resp.StatusCode != 200 {
144 p, _ := ioutil.ReadAll(resp.Body)
145 return fmt.Errorf("get %s returned status %d, %s", resp.Request.URL, resp.StatusCode, p)
146 }
147 return json.NewDecoder(resp.Body).Decode(data)
148 }
149
150 // respond responds to a request by executing the html template t with data.
151 func respond(w http.ResponseWriter, t *template.Template, data interface{}) {
152 w.Header().Set("Content-Type", "text/html; charset=utf-8")
153 if err := t.Execute(w, data); err != nil {
154 log.Print(err)
155 }
156 }
157
158 func serveHome(w http.ResponseWriter, r *http.Request, cred *oauth.Credentials) {
159 if r.URL.Path != "/" {
160 http.NotFound(w, r)
161 return
162 }
163 if cred == nil {
164 respond(w, homeLoggedOutTmpl, nil)
165 } else {
166 respond(w, homeTmpl, nil)
167 }
168 }
169
170 func serveAlbums(w http.ResponseWriter, r *http.Request, cred *oauth.Credentials) {
171 var albums map[string]interface{}
172 if err := apiGet(
173 cred,
174 url.Values{"method": {"smugmug.albums.get"}},
175 &albums); err != nil {
176 http.Error(w, "Error getting albums, "+err.Error(), 500)
177 return
178 }
179 respond(w, albumsTmpl, albums)
180 }
181
182 var httpAddr = flag.String("addr", ":8080", "HTTP server address")
183
184 func main() {
185 flag.Parse()
186 if err := readCredentials(); err != nil {
187 log.Fatalf("Error reading configuration, %v", err)
188 }
189
190 http.Handle("/", &authHandler{handler: serveHome, optional: true})
191 http.Handle("/albums", &authHandler{handler: serveAlbums})
192 http.HandleFunc("/login", serveLogin)
193 http.HandleFunc("/logout", serveLogout)
194 http.HandleFunc("/callback", serveOAuthCallback)
195 if err := http.ListenAndServe(*httpAddr, nil); err != nil {
196 log.Fatalf("Error listening, %v", err)
197 }
198 }
199
200 var (
201 homeLoggedOutTmpl = template.Must(template.New("loggedout").Parse(
202 `<html>
203 <head>
204 </head>
205 <body>
206 <a href="/login">login</a>
207 </body>
208 </html>`))
209
210 homeTmpl = template.Must(template.New("home").Parse(
211 `<html>
212 <head>
213 </head>
214 <body>
215 <p><a href="/albums">albums</a>
216 <p><a href="/logout">logout</a>
217 </body></html>`))
218
219 albumsTmpl = template.Must(template.New("albums").Parse(
220 `<html>
221 <head>
222 </head>
223 <body>
224 <p><a href="/">home</a>
225 {{range .Albums}}<p>{{html .Title}}{{end}}
226 <{{.}}
227 </body></html>`))
228 )