Added Twitter example.
[cl-oauth:cl-oauth.git] / examples / consumer / twitter.lisp
1
2 (asdf:oos 'asdf:load-op 'cl-oauth)
3 (asdf:oos 'asdf:load-op 'hunchentoot)
4
5 (defpackage :cl-oauth.twitter-consumer
6   (:use :cl :cl-oauth))
7
8 (in-package :cl-oauth.twitter-consumer)
9
10 ;;; insert your credentials and auxiliary information here.
11 (defparameter *key* "")
12 (defparameter *secret* "")
13 (defparameter *callback-uri* "")
14 (defparameter *callback-port* 8090
15   "Port to listen on for the callback")
16
17
18 ;;; go
19 (defparameter *get-request-token-endpoint* "http://twitter.com/oauth/request_token")
20 (defparameter *auth-request-token-endpoint* "http://twitter.com/oauth/authorize")
21 (defparameter *get-access-token-endpoint* "http://twitter.com/oauth/access_token")
22 (defparameter *consumer-token* (make-consumer-token :key *key* :secret *secret*))
23 (defparameter *request-token* nil)
24 (defparameter *access-token* nil)
25
26 (defun get-access-token ()
27   (obtain-access-token *get-access-token-endpoint* *consumer-token* *request-token*))
28
29 ;;; get a request token
30 (defun get-request-token ()
31   (obtain-request-token
32     *get-request-token-endpoint*
33     *consumer-token*
34     :callback-uri *callback-uri*))
35
36 (setf *request-token* (get-request-token))
37
38 (let ((auth-uri (make-authorization-uri *auth-request-token-endpoint* *request-token*)))
39   (format t "Please authorize the request token at this URI: ~A~%" (puri:uri auth-uri)))
40
41
42 ;;; set up callback uri
43 (defun callback-dispatcher (request)
44   (declare (ignorable request))
45   (unless (cl-ppcre:scan  "favicon\.ico$" (hunchentoot:script-name request))
46     (lambda (&rest args)
47       (declare (ignore args))
48       (handler-case
49           (authorize-request-token-from-request
50             (lambda (rt-key)
51               (assert *request-token*)
52               (unless (equal (url-encode rt-key) (token-key *request-token*))
53                 (warn "Keys differ: ~S / ~S~%" (url-encode rt-key) (token-key *request-token*)))
54               *request-token*))
55         (error (c)
56           (warn "Couldn't verify request token authorization: ~A" c)))
57       (when (request-token-authorized-p *request-token*)
58         (format t "Successfully verified request token with key ~S~%" (token-key *request-token*))
59         (setf *access-token* (get-access-token))
60         ;; test request:
61         (babel:octets-to-string
62           (access-protected-resource "http://search.twitter.com/search.json?q=twitter"
63                                      *access-token* *consumer-token*))))))
64
65 (pushnew 'callback-dispatcher hunchentoot:*dispatch-table*)
66
67
68 (defvar *web-server* nil)
69
70 (when *web-server*
71   (hunchentoot:stop *web-server*)
72   (setf *web-server* nil))
73
74 (setf *web-server* (hunchentoot:start (make-instance 'hunchentoot:acceptor :port *callback-port*)))
75