情報アイランド

「情報を制する者は世界を制す」をモットーに様々な情報を提供することを目指すブログです。現在はプログラミング関連情報が多めですが、投資関連情報も取り扱っていきたいです。

Oauth認証(Dropbox)その3

2017/04/18

前回の認証コードで認証した後、APIを呼び出すことができるか確認してみました。/account/info/metadataを呼び出せるようにしました。

ライブラリとしてjQuery、Query String Object、oauth.js、sha1.js、json2.js、JSONP2(一部改変)、uuStorage.jsを使用しています。

<!DOCTYPE html>
<html>
<head>
    <title>Dropbox</title>
    <script type="text/javascript" src="jquery-1.6.2.js"></script>
    <script type="text/javascript" src="jquery.query-2.1.7.js"></script>
    <script type="text/javascript" src="oauth.js"></script>
    <script type="text/javascript" src="sha1.js"></script>
    <script type="text/javascript" src="json2.js"></script>
    <script type="text/javascript" src="jsonp2.js"></script>
    <script type="text/javascript" src="uuStorage-0.11.js/uuStorage.js/uuStorage.js"></script>
    <script type="text/javascript">
        var accessor = { consumerKey: "xxxxxxxxxxxxxxx", consumerSecret: "xxxxxxxxxxxxxxx", serviceProvider: { signatureMethod: "HMAC-SHA1", requestTokenURL: "https://api.dropbox.com/0/oauth/request_token", userAuthorizationURL: "https://www.dropbox.com/0/oauth/authorize", accessTokenURL: "https://api.dropbox.com/0/oauth/access_token"} };
        var apiaccessor = { accountInfo: "https://api.dropbox.com/0/account/info", metadataDropbox: "https://api.dropbox.com/0/metadata/dropbox", metadataSandbox: "", metadataSandbox: "https://api.dropbox.com/0/metadata/sandbox" };

        function getTokens() {
            var message = { method: "get", action: accessor.serviceProvider.requestTokenURL };
            OAuth.completeRequest(message, accessor);
            var url = OAuth.addToURL(message.action, message.parameters) + "&callback=?";

            $.ajax({
                url: url,
                dataType: "jsonp",
                type: "GET",
                success: function (data, status) {
                    var results = OAuth.decodeForm(data);

                    accessor.oauth_token = OAuth.getParameter(results, "oauth_token");
                    accessor.oauth_token_secret = OAuth.getParameter(results, "oauth_token_secret");

                    document.location = accessor.serviceProvider.userAuthorizationURL + "?oauth_token=" + accessor.oauth_token + "&oauth_token_secret=" + accessor.oauth_token_secret + "&oauth_callback=" + document.URL;
                },
                error: function (XHR, textStatus, errorThrown) {
                }
            });
        };

        function getTokens2(callback) {
            message = { method: "get", action: accessor.serviceProvider.accessTokenURL };
            OAuth.completeRequest(message, { consumerKey: accessor.consumerKey, consumerSecret: accessor.consumerSecret, token: accessor.oauth_token, tokenSecret: accessor.oauth_token_secret });
            url = OAuth.addToURL(message.action, message.parameters) + "&callback=?";

            $.ajax({
                url: url,
                dataType: "jsonp",
                type: "GET",
                success: function (data, status) {
                    var results = OAuth.decodeForm(data);

                    accessor.oauth_token = OAuth.getParameter(results, "oauth_token");
                    accessor.oauth_token_secret = OAuth.getParameter(results, "oauth_token_secret");

                    if (callback)
                        callback();
                },
                error: function (XHR, textStatus, errorThrown) {
                }
            });
        };

        function account_info(handler) {
            message = { method: "get", action: apiaccessor.accountInfo, parameters: [["callback", handler]] };
            OAuth.completeRequest(message, { consumerKey: accessor.consumerKey, consumerSecret: accessor.consumerSecret, token: accessor.oauth_token, tokenSecret: accessor.oauth_token_secret });
            url = OAuth.addToURL(message.action, message.parameters);

            new JSONP2(url);
        };

        function metadata_sandbox(handler, path) {
            message = { method: "get", action: apiaccessor.metadataSandbox + path, parameters: [["callback", handler]] };
            OAuth.completeRequest(message, { consumerKey: accessor.consumerKey, consumerSecret: accessor.consumerSecret, token: accessor.oauth_token, tokenSecret: accessor.oauth_token_secret });
            url = OAuth.addToURL(message.action, message.parameters);

            new JSONP2(url);
        };

        function metadata_dropbox(handler, path) {
            message = { method: "get", action: apiaccessor.metadataDropbox + path, parameters: [["callback", handler]] };
            OAuth.completeRequest(message, { consumerKey: accessor.consumerKey, consumerSecret: accessor.consumerSecret, token: accessor.oauth_token, tokenSecret: accessor.oauth_token_secret });
            url = OAuth.addToURL(message.action, message.parameters);

            new JSONP2(url);
        };

        var handler = function (json) {
            alert(JSON.stringify(json));
        };

        window.xstorage = function (uu, storage) {
            accessor.oauth_token = storage.get("oauth_token");
            accessor.oauth_token_secret = storage.get("oauth_token_secret");
            if (accessor.oauth_token == "" && accessor.oauth_token_secret == "") {
                accessor.oauth_token = $.query.get("oauth_token");
                accessor.oauth_token_secret = $.query.get("oauth_token");

                if (accessor.oauth_token == "" && accessor.oauth_token_secret == "") {
                    getTokens();
                }
                else {
                    getTokens2(function () {
                        storage.set("oauth_token", accessor.oauth_token);
                        storage.set("oauth_token_secret", accessor.oauth_token_secret);

                        $(document.body).append("<div>oauth_token: " + accessor.oauth_token + "<br/>oauth_token_secret: " + accessor.consumerSecret + "</div>");
                    });
                }
            }
            else {
                $(document.body).append("<div>oauth_token: " + accessor.oauth_token + "<br/>oauth_token_secret: " + accessor.consumerSecret + "</div>");
            }
        }

        jQuery(document).ready(function ($) {
            $("#a").click(function () {
                account_info("handler");
            });
            $("#m").click(function () {
                metadata_dropbox("handler", "/");
            });
        });

    </script>
</head>
<body>
    <input type="button" value="account_info" id="a" />
    <input type="button" value="metadata" id="m" />
</body>
</html>

改変したjsonp2.jsです。

JSONP2.counter = 1;
function JSONP2(src) {
    this.initialize.apply(this, arguments);
}
JSONP2.prototype = {
    scriptTag: '',
    headTag: '',
    initialize: function (src, callback, scope) {
        this.scriptTag = document.createElement("script");
        this.headTag = document.getElementsByTagName("head").item(0);

        this.scriptTag.id = "jsonp" + JSONP2.counter++;
        this.scriptTag.setAttribute('type', 'text/javascript');
        this.scriptTag.setAttribute('charset', 'UTF-8');
        var noCache = ''; // '&_noCache=' + new Date().getTime();
        var url = src + noCache;

        switch (typeof callback) {
            case 'string':
                url += '&callback=' + callback;
                break;
            case 'function':
                var callbackName = 'callback' + this.scriptTag.id;
                var self = this;
                scope = scope || window;
                window[callbackName] = function (json) {
                    return function () {
                        callback.apply(scope, arguments);
                        window[callbackName] = undefined;
                        try { delete window[callbackName]; } catch (e) { }
                        if (self.headTag) self.remove();
                    } (json);
                }
                url += '&callback=' + callbackName;
                break;
            default:
                break;
        }

        this.scriptTag.setAttribute('src', url);
        this.headTag.appendChild(this.scriptTag);
    },
    remove: function () {
        this.headTag.removeChild(this.scriptTag);
    }
}
pizyumi
プログラミング歴19年のベテランプログラマー。業務システム全般何でも作れます。現在はWeb系の技術を勉強中。
スポンサーリンク

-web