(in-package :oauth)


(defparameter *oauth-client-registry*
  '((:twitter
     :app-name "" ;your oauth app name here
     :method "POST"
     :consumer-key ""; your consumer key here
     :consumer-secret "" ;your app consumer secret here
     :signature-method :hmac-sha1
     :request-token-url ("https" "api.twitter.com" 443 "/oauth/request_token")
     :access-token-url ("https" "api.twitter.com" 443 "/oauth/access_token")
     :authorize-url ("https" "api.twitter.com" 443 "/oauth/authorize"))
    (:google
     :app-name "" ;your oauth app name here
     :method "POST"; your consumer key here
     :consumer-secret "" ;your app consumer secret here
     :signature-method :hmac-sha1
     :request-token-url ("https" "www.google.com" 443 "/accounts/OAuthGetRequestToken")
     :access-token-url ("https" "www.google.com" 443 "/accounts/OAuthGetAccessToken")
     :authorize-url ("https" "www.google.com" 443 "/accounts/OAuthAuthorizeToken")
     :additional-params (("scope" "http://www.google.com/fusiontables/api/query")))))

(defparameter *oauth-user-auth-token-registry* nil)
(defparameter *oauth-user-auth-token-registry-file* "Z:/Guy/GDFT/oauth-user-credentials")

(defvar *oauth-debug-stream* nil) 
(defmacro with-oauth-debugging ((stream) &body body)
  `(let ((*oauth-debug-stream* ,stream))
     ,@body))

;;; the timestamp is expressed in the number of seconds since January 1, 1970 00:00:00 GMT.
(defun make-oauth-timestamp ()
  (format nil "~D" (- (get-universal-time) #.(encode-universal-time 0 0 0 1 1 1970 0))))

;;; The Consumer SHALL then generate a Nonce value that is unique for all requests with that timestamp. 
;;; A nonce is a random string, uniquely generated for each request. The nonce allows the Service Provider 
;;; to verify that a request has never been made before and helps prevent replay attacks when requests are
;;; made over a non-secure channel (such as HTTP). 
(defun make-oauth-nonce (app-name)
  (format nil "GDFT/~A~d" app-name (random 999999999999999)))

(defun create-oauth-signature (private-key method protocol port host url oauth-parameters)
  (let* ((sorted-oauth-parameters (stable-sort (sort (remove "realm" (copy-list oauth-parameters) :test #'string-equal :key #'first) 
                                                     #'string<
                                                     :key #'second) 
                                               #'string< 
                                               :key #'first))
         (uri (format nil "~A://~A~@[:~A~]~A" 
                      (string-downcase protocol)                     
                      (string-downcase host)
                      (and port (cond ((and (string-equal protocol "http")
                                            (= port 80))
                                       nil)
                                      ((and (string-equal protocol "https")
                                            (= port 443))
                                       nil)
                                      (t port)))
                      (subseq url 0 (position #\? url :test #'char=))))
         (param-string (format nil "~{~A~^&~}" (loop for (key value) in sorted-oauth-parameters
                                                       collect (format nil "~A=~A" (url-encode key) (url-encode value)))))
         (base-string (format nil "~A&~A&~A" (string-upcase method) (url-encode uri) (url-encode param-string))))
    (when *oauth-debug-stream*
      (format *oauth-debug-stream* "Base string: ~s~%" base-string))
    (multiple-value-bind (sig-string sig-words)
        (hmac-sha1:create-hmac-sha1-signature private-key base-string)
      (declare (ignore sig-string))
      (destructuring-bind (w1 w2 w3 w4 w5)
          sig-words
        (let ((sig-bytes (make-array 20 :element-type '(unsigned-byte 8))))
          (setf (aref sig-bytes 0)  (ldb (byte 8 24) w1)
                (aref sig-bytes 1)  (ldb (byte 8 16) w1)
                (aref sig-bytes 2)  (ldb (byte 8  8) w1)
                (aref sig-bytes 3)  (ldb (byte 8  0) w1)
                (aref sig-bytes 4)  (ldb (byte 8 24) w2)
                (aref sig-bytes 5)  (ldb (byte 8 16) w2)
                (aref sig-bytes 6)  (ldb (byte 8  8) w2)
                (aref sig-bytes 7)  (ldb (byte 8  0) w2)
                (aref sig-bytes 8)  (ldb (byte 8 24) w3)
                (aref sig-bytes 9)  (ldb (byte 8 16) w3)
                (aref sig-bytes 10) (ldb (byte 8  8) w3)
                (aref sig-bytes 11) (ldb (byte 8  0) w3)
                (aref sig-bytes 12) (ldb (byte 8 24) w4)
                (aref sig-bytes 13) (ldb (byte 8 16) w4)
                (aref sig-bytes 14) (ldb (byte 8  8) w4)
                (aref sig-bytes 15) (ldb (byte 8  0) w4)
                (aref sig-bytes 16) (ldb (byte 8 24) w5)
                (aref sig-bytes 17) (ldb (byte 8 16) w5)
                (aref sig-bytes 18) (ldb (byte 8  8) w5)
                (aref sig-bytes 19) (ldb (byte 8  0) w5))
          (base64-encode sig-bytes))))))


(defun parse-oauth-response (http-stream)
  ;; Google doesn't terminate the line, just uses content length indicator
  (let* ((content-length (http-utils:skip-http-headers http-stream))
         (response-line (http-utils:read-line-from-http http-stream content-length)))
    (when *oauth-debug-stream*
      (print response-line *oauth-debug-stream*))
    (when (string= response-line "oauth_" :end1 (min 6 (length response-line)))
      (loop for (key value) on (lw:split-sequence "=&" response-line :test #'char=) by #'cddr
            ;; might need key and/or value to be url-decoded
            collect (list key value)))))

(defun oauth-send-request (http-stream protocol host port url method consumer-secret token-secret oauth-parameters keep-params result-parser)
  (let ((new-stream (not http-stream)))
    (unwind-protect
        (progn
          (unless http-stream
            (setq http-stream (apply #'COMM:OPEN-TCP-STREAM host port (when (string= protocol "https") (list :ssl-ctx :v23)))))
          (let ((signature (create-oauth-signature (format nil "~A&~@[~A~]" (url-encode consumer-secret) (url-encode token-secret)) method protocol port host url oauth-parameters)))
            (http-utils:format-to-http http-stream
                                       "~A ~A://~A~A HTTP/1.1~A"
                                       (string-upcase method)
                                       protocol
                                       host
                                       url
                                       +crlf+)
            (http-utils:format-to-http http-stream
                                       "Host: ~A~A" host +crlf+)
            (http-utils:format-to-http http-stream "User-Agent: ~A~A" *gdft-user-agent* +crlf+)
            (http-utils:format-to-http http-stream
                                       "Authorization: OAuth ~{~{~A=~S, ~}~}oauth_signature=~S~A"
                                       (loop for (param-name param-value) in oauth-parameters
                                             when (or (member param-name keep-params :test #'string=)
                                                      (string= param-name "oauth_" :end1 (min (length param-name) 6)))
                                             collect (list param-name (url-encode param-value)))
                                       (url-encode signature) +crlf+)
            (format-to-http http-stream "Content-length: 0~A" +crlf+)
            (format-to-http http-stream +crlf+)
            (force-output http-stream))
          (funcall result-parser http-stream))
      (when (and new-stream http-stream)
        (close http-stream)))))


(defun oauth-request-token (app &optional http-stream)
  (let ((app-details (cdr (assoc app *oauth-client-registry*))))
    (if (not app-details)
        (error "Unknown OAUTH provider ~A" app)
      (let ((method (getf app-details :method))
            (consumer-secret (getf app-details :consumer-secret))
            (consumer-key (getf app-details :consumer-key))
            (request-token-url (getf app-details :request-token-url))
            (signature-method (getf app-details :signature-method))
            (additional-params (getf app-details :additional-params)))
        (destructuring-bind (protocol host port path)
            request-token-url
          (let ((oauth-parameters `(("oauth_callback" "oob")
                                    ("oauth_consumer_key" ,consumer-key)
                                    ("oauth_nonce" ,(make-oauth-nonce app))
                                    ("oauth_signature_method" ,(symbol-name signature-method))
                                    ("oauth_timestamp" ,(make-oauth-timestamp))
                                    ("oauth_version" "1.0")
                                    ,@additional-params)))
            (let* ((response (oauth-send-request http-stream protocol host port path method consumer-secret nil oauth-parameters (mapcar #'first additional-params) #'parse-oauth-response))
                   (confirmed (assoc "oauth_callback_confirmed" response :test #'string=)))
              (when confirmed
                (values response 
                        (destructuring-bind (protocol host port path)
                            (getf app-details :authorize-url)
                          (format nil "~A://~A:~D~A?oauth_token=~A"
                                  protocol host port path
                                  (second (assoc "oauth_token" response :test #'string=)))))))))))))


(defun oauth-request-access-token (app oauth-token oauth-token-secret oauth-verifier &optional http-stream)
  (let ((app-details (cdr (assoc app *oauth-client-registry*))))
    (if (not app-details)
        (error "Unknown OAUTH provider ~A" app)
      (let ((method (getf app-details :method))
            (consumer-secret (getf app-details :consumer-secret))
            (consumer-key (getf app-details :consumer-key))
            (access-token-url (getf app-details :access-token-url))
            (signature-method (getf app-details :signature-method))
            (additional-params (getf app-details :additional-params)))
        (destructuring-bind (protocol host port path)
            access-token-url
          (let ((oauth-parameters `(("oauth_consumer_key" ,consumer-key)
                                    ("oauth_token" ,oauth-token)
                                    ("oauth_nonce" ,(make-oauth-nonce app))
                                    ("oauth_signature_method" ,(symbol-name signature-method))
                                    ("oauth_timestamp" ,(make-oauth-timestamp))
                                    ("oauth_verifier",oauth-verifier)
                                    ("oauth_version" "1.0")
                                    ,@additional-params)))
            (oauth-send-request http-stream protocol host port path method consumer-secret oauth-token-secret oauth-parameters  (mapcar #'first additional-params) #'parse-oauth-response)))))))


(defun get-oauth-credentials (app userid)
  (let* ((app-credentials (getf *oauth-user-auth-token-registry* app))
         (known-credentials (assoc userid app-credentials :test #'string=)))
    (if known-credentials
        known-credentials
      (multiple-value-bind (response authorize-url)
          (oauth-request-token app nil)
        (when response
          (let ((token (second (assoc "oauth_token" response :test #'string=)))
                (token-secret (second (assoc "oauth_token_secret" response :test #'string=)))
                (verifier))
            (format t "Please paste the following URL into your browser and login to get an authorization code:  ~A~%" authorize-url)
            (format t "Authorizaton code: ")
            (setq verifier (read-line))
            (loop until (or (string-equal verifier "ABORT") (y-or-n-p "You entered ~A, is that correct?" verifier))
                  do (progn
                       (format t "Authorizaton code: ")
                       (setq verifier (read-line))))
            (if (string-equal verifier "ABORT")
                (error "Aborting whilst getting oauth credentials")
              (let ((access-token (oauth-request-access-token app token token-secret verifier nil)))
                (let ((username (url-decode (second (assoc "screen_name" access-token :test #'string=))))
                      (userid (url-decode (second (assoc "user_id" access-token :test #'string=))))
                      (token (url-decode (second (assoc "oauth_token" access-token :test #'string=))))
                      (token-secret (url-decode (second (assoc "oauth_token_secret" access-token :test #'string=))))
                      user-credentials)
                  (setq user-credentials (list (or username userid) :user-id userid :oauth-token token :oauth-token-secret token-secret))
                  (if app-credentials
                      (push user-credentials app-credentials)
                    (setq *oauth-user-auth-token-registry*
                          (list* app (list user-credentials)
                                *oauth-user-auth-token-registry*)))
                  (save-oauth-credentials)
                  user-credentials)))))))))


(defun save-oauth-credentials ()
  (hcl:dump-forms-to-file
   (compile-file-pathname *oauth-user-auth-token-registry-file*)
   (list `(setq *oauth-user-auth-token-registry* ',*oauth-user-auth-token-registry*))))

(defun load-oauth-credentials ()
  (sys:load-data-file
   (compile-file-pathname *oauth-user-auth-token-registry-file*)))

(defun access-oauth-protected-resource (http-stream app username method protocol host port url method-parameters 
                                                    &optional (parser #'(lambda (stream) 
                                                                          (skip-http-headers stream)
                                                                          (let ((response (read-line-from-http stream)))
                                                                            (if (html-response-p response)
                                                                                (error "Expected JSON object, got HTML:~%~A~%~{~A~%~}" response 
                                                                                       (loop for more = (read-line-from-http stream)
                                                                                             while more
                                                                                             collect more))
                                                                              (json:parse-json response))))))
  (let ((app-details (cdr (assoc app *oauth-client-registry*))))
    (if (not app-details)
        (error "Unknown OAUTH provider ~A" app)
      (let* ((consumer-secret (getf app-details :consumer-secret))
             (consumer-key (getf app-details :consumer-key))
             (signature-method (getf app-details :signature-method))
             (user-credentials (rest (get-oauth-credentials app username)))
             (oauth-token-secret (getf user-credentials :oauth-token-secret))
             (oauth-token (getf user-credentials :oauth-token))
             (oauth-parameters `(("oauth_consumer_key" ,consumer-key)
                                 ("oauth_token" ,oauth-token)
                                 ("oauth_nonce" ,(make-oauth-nonce app))
                                 ("oauth_signature_method" ,(symbol-name signature-method))
                                 ("oauth_timestamp" ,(make-oauth-timestamp))
                                 ("oauth_version" "1.0")
                                 ,@method-parameters)))
        (oauth-send-request http-stream protocol host port url method consumer-secret oauth-token-secret oauth-parameters nil
                            parser)))))