Debian Codegraph @

examples/twitter/main.go

raw symbols SCIP
1 // Copyright 2011 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 "html/template"
22 "io/ioutil"
23 "log"
24 "net/http"
25 "net/url"
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.twitter.com/oauth/request_token",
39 ResourceOwnerAuthorizationURI: "https://api.twitter.com/oauth/authorize",
40 TokenRequestURI: "https://api.twitter.com/oauth/access_token",
41 }
42
43 var signinOAuthClient oauth.Client
44
45 var credPath = flag.String("config", "config.json", "Path to configuration file containing the application's credentials.")
46
47 func readCredentials() error {
48 b, err := ioutil.ReadFile(*credPath)
49 if err != nil {
50 return err
51 }
52 return json.Unmarshal(b, &oauthClient.Credentials)
53 }
54
55 // serveSignin gets the OAuth temp credentials and redirects the user to the
56 // Twitter's authentication page.
57 func serveSignin(w http.ResponseWriter, r *http.Request) {
58 callback := "http://" + r.Host + "/callback"
59 tempCred, err := signinOAuthClient.RequestTemporaryCredentials(nil, callback, nil)
60 if err != nil {
61 http.Error(w, "Error getting temp cred, "+err.Error(), 500)
62 return
63 }
64 s := session.Get(r)
65 s[tempCredKey] = tempCred
66 if err := session.Save(w, r, s); err != nil {
67 http.Error(w, "Error saving session , "+err.Error(), 500)
68 return
69 }
70 http.Redirect(w, r, signinOAuthClient.AuthorizationURL(tempCred, nil), 302)
71 }
72
73 // serveAuthorize gets the OAuth temp credentials and redirects the user to the
74 // Twitter's authorization page.
75 func serveAuthorize(w http.ResponseWriter, r *http.Request) {
76 callback := "http://" + r.Host + "/callback"
77 tempCred, err := oauthClient.RequestTemporaryCredentials(nil, callback, nil)
78 if err != nil {
79 http.Error(w, "Error getting temp cred, "+err.Error(), 500)
80 return
81 }
82 s := session.Get(r)
83 s[tempCredKey] = tempCred
84 if err := session.Save(w, r, s); err != nil {
85 http.Error(w, "Error saving session , "+err.Error(), 500)
86 return
87 }
88 http.Redirect(w, r, oauthClient.AuthorizationURL(tempCred, nil), 302)
89 }
90
91 // serveOAuthCallback handles callbacks from the OAuth server.
92 func serveOAuthCallback(w http.ResponseWriter, r *http.Request) {
93 s := session.Get(r)
94 tempCred, _ := s[tempCredKey].(*oauth.Credentials)
95 if tempCred == nil || tempCred.Token != r.FormValue("oauth_token") {
96 http.Error(w, "Unknown oauth_token.", 500)
97 return
98 }
99 tokenCred, _, err := oauthClient.RequestToken(nil, tempCred, r.FormValue("oauth_verifier"))
100 if err != nil {
101 http.Error(w, "Error getting request token, "+err.Error(), 500)
102 return
103 }
104 delete(s, tempCredKey)
105 s[tokenCredKey] = tokenCred
106 if err := session.Save(w, r, s); err != nil {
107 http.Error(w, "Error saving session , "+err.Error(), 500)
108 return
109 }
110 http.Redirect(w, r, "/", 302)
111 }
112
113 // serveLogout clears the authentication cookie.
114 func serveLogout(w http.ResponseWriter, r *http.Request) {
115 s := session.Get(r)
116 delete(s, tokenCredKey)
117 if err := session.Save(w, r, s); err != nil {
118 http.Error(w, "Error saving session , "+err.Error(), 500)
119 return
120 }
121 http.Redirect(w, r, "/", 302)
122 }
123
124 // authHandler reads the auth cookie and invokes a handler with the result.
125 type authHandler struct {
126 handler func(w http.ResponseWriter, r *http.Request, c *oauth.Credentials)
127 optional bool
128 }
129
130 func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
131 cred, _ := session.Get(r)[tokenCredKey].(*oauth.Credentials)
132 if cred == nil && !h.optional {
133 http.Error(w, "Not logged in.", 403)
134 return
135 }
136 h.handler(w, r, cred)
137 }
138
139 // apiGet issues a GET request to the Twitter API and decodes the response JSON to data.
140 func apiGet(cred *oauth.Credentials, urlStr string, form url.Values, data interface{}) error {
141 resp, err := oauthClient.Get(nil, cred, urlStr, form)
142 if err != nil {
143 return err
144 }
145 defer resp.Body.Close()
146 return decodeResponse(resp, data)
147 }
148
149 // apiPost issues a POST request to the Twitter API and decodes the response JSON to data.
150 func apiPost(cred *oauth.Credentials, urlStr string, form url.Values, data interface{}) error {
151 resp, err := oauthClient.Post(nil, cred, urlStr, form)
152 if err != nil {
153 return err
154 }
155 defer resp.Body.Close()
156 return decodeResponse(resp, data)
157 }
158
159 // decodeResponse decodes the JSON response from the Twitter API.
160 func decodeResponse(resp *http.Response, data interface{}) error {
161 if resp.StatusCode != 200 {
162 p, _ := ioutil.ReadAll(resp.Body)
163 return fmt.Errorf("get %s returned status %d, %s", resp.Request.URL, resp.StatusCode, p)
164 }
165 return json.NewDecoder(resp.Body).Decode(data)
166 }
167
168 // respond responds to a request by executing the html template t with data.
169 func respond(w http.ResponseWriter, t *template.Template, data interface{}) {
170 w.Header().Set("Content-Type", "text/html; charset=utf-8")
171 if err := t.Execute(w, data); err != nil {
172 log.Print(err)
173 }
174 }
175
176 func serveHome(w http.ResponseWriter, r *http.Request, cred *oauth.Credentials) {
177 if r.URL.Path != "/" {
178 http.NotFound(w, r)
179 return
180 }
181 if cred == nil {
182 respond(w, homeLoggedOutTmpl, nil)
183 } else {
184 respond(w, homeTmpl, nil)
185 }
186 }
187
188 func serveTimeline(w http.ResponseWriter, r *http.Request, cred *oauth.Credentials) {
189 var timeline []map[string]interface{}
190 if err := apiGet(
191 cred,
192 "https://api.twitter.com/1.1/statuses/home_timeline.json",
193 url.Values{"include_entities": {"true"}},
194 &timeline); err != nil {
195 http.Error(w, "Error getting timeline, "+err.Error(), 500)
196 return
197 }
198 respond(w, timelineTmpl, timeline)
199 }
200
201 func serveMessages(w http.ResponseWriter, r *http.Request, cred *oauth.Credentials) {
202 var dms []map[string]interface{}
203 if err := apiGet(
204 cred,
205 "https://api.twitter.com/1.1/direct_messages.json",
206 nil,
207 &dms); err != nil {
208 http.Error(w, "Error getting timeline, "+err.Error(), 500)
209 return
210 }
211 respond(w, messagesTmpl, dms)
212 }
213
214 func serveFollow(w http.ResponseWriter, r *http.Request, cred *oauth.Credentials) {
215 var profile map[string]interface{}
216 if err := apiPost(
217 cred,
218 "https://api.twitter.com/1.1/friendships/create.json",
219 url.Values{"screen_name": {"gburd"}, "follow": {"true"}},
220 &profile); err != nil {
221 http.Error(w, "Error following, "+err.Error(), 500)
222 return
223 }
224 respond(w, followTmpl, profile)
225 }
226
227 var httpAddr = flag.String("addr", ":8080", "HTTP server address")
228
229 func main() {
230 flag.Parse()
231 if err := readCredentials(); err != nil {
232 log.Fatalf("Error reading configuration, %v", err)
233 }
234
235 // Use a different auth URL for "Sign in with Twitter."
236 signinOAuthClient = oauthClient
237 signinOAuthClient.ResourceOwnerAuthorizationURI = "https://api.twitter.com/oauth/authenticate"
238
239 http.Handle("/", &authHandler{handler: serveHome, optional: true})
240 http.Handle("/timeline", &authHandler{handler: serveTimeline})
241 http.Handle("/messages", &authHandler{handler: serveMessages})
242 http.Handle("/follow", &authHandler{handler: serveFollow})
243 http.HandleFunc("/signin", serveSignin)
244 http.HandleFunc("/authorize", serveAuthorize)
245 http.HandleFunc("/logout", serveLogout)
246 http.HandleFunc("/callback", serveOAuthCallback)
247 if err := http.ListenAndServe(*httpAddr, nil); err != nil {
248 log.Fatalf("Error listening, %v", err)
249 }
250 }
251
252 var (
253 homeLoggedOutTmpl = template.Must(template.New("loggedout").Parse(
254 `<html>
255 <head>
256 </head>
257 <body>
258 <a href="/authorize">Authorize</a> or
259 <a href="/signin"><img src="http://g.twimg.com/dev/sites/default/files/images_documentation/sign-in-with-twitter-gray.png"></a>
260 </body>
261 </html>`))
262
263 homeTmpl = template.Must(template.New("home").Parse(
264 `<html>
265 <head>
266 </head>
267 <body>
268 <p><a href="/timeline">timeline</a>
269 <p><a href="/messages">direct messages</a>
270 <p><a href="/follow">follow @gburd</a>
271 <p><a href="/logout">logout</a>
272 </body></html>`))
273
274 messagesTmpl = template.Must(template.New("messages").Parse(
275 `<html>
276 <head>
277 </head>
278 <body>
279 <p><a href="/">home</a>
280 {{range .}}
281 <p><b>{{.sender.name}}</b> {{.text}}
282 {{end}}
283 </body></html>`))
284
285 timelineTmpl = template.Must(template.New("timeline").Parse(
286 `<html>
287 <head>
288 </head>
289 <body>
290 <p><a href="/">home</a>
291 {{range .}}
292 <p><b>{{.user.name}}</b> {{.text}}
293 {{with .entities}}
294 {{with .urls}}<br><i>urls:</i> {{range .}}{{.expanded_url}}{{end}}{{end}}
295 {{with .hashtags}}<br><i>hashtags:</i> {{range .}}{{.text}}{{end}}{{end}}
296 {{with .user_mentions}}<br><i>user_mentions:</i> {{range .}}{{.screen_name}}{{end}}{{end}}
297 {{end}}
298 {{end}}
299 </body></html>`))
300
301 followTmpl = template.Must(template.New("follow").Parse(
302 `<html>
303 <head>
304 </head>
305 <body>
306 <p><a href="/">home</a>
307 <p>You are now following <a href="https://twitter.com/{{.screen_name}}">{{.name}}</a>
308 </body></html>`))
309 )