Search code examples
javascripthtmlhttpgithubgithub-api

How can I get user access token with the code github provided under CORS?


I applied the oauth2 of github to my website and get the temporary code. But I don't know how to push it to the github and get the access token and how to use the token to get user's info.

For now, I tried

https://github.com/login/oauth/access_token?client_id="+ClientID+"&client_secret="+ClientSecret+"&code="+code

and get a none-extention file with access token in it. And I would like to drag that token from this file without leaving the page. I have checked the guide, but I don't know how the PUT and GET is supposed to be used in pure HTML and JAVASCRIPT code.

var GET = {};
var queryString = window.location.search.replace(/^\?/, '');
queryString.split(/\&/).forEach(function(keyValuePair) {
    var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
    var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
    GET[paramName] = paramValue;
});
var code = GET["code"];
var auth = GET["auth"];
const ClientID = "ed2326bbcc88ed66ac15";
const ClientSecret = "ecc0ed28ea801bbe5ccdeb006f10374f0f0642dd";
$(function() {
    console.log(code);
    console.log(auth);
    if(auth === "github"){
        var target = "https://github.com/login/oauth/access_token?client_id="+ClientID+"&client_secret="+ClientSecret+"&code="+code;
        console.log(target);

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = process;
        xhr.open("GET", target, true);
        xhr.send();

        console.log(xhr);

        function process()
        {
            if (xhr.readyState == 4) {
                var resp = JSON.parse(xhr.responseText);

                // resp now has the text and you can process it.
                alert(resp);
            }
        }

                // window.onload = function() {
                //     /**
                //      * 上传函数
                //      * @param fileInput DOM对象
                //      * @param callback 回调函数
                //      */
                //     var getFileContent = function (fileInput, callback) {
                //         console.log(target.files);
                //         var reader = new FileReader();
                //         console.log(reader.readAsText(target, 'UTF-8'));
                //         console.log("fileInput.files", fileInput.files);
                //         if (
                //             fileInput.files && fileInput.files.length > 0 && fileInput.files[0].size > 0
                //             // target.files
                //         ) {
                //             //下面这一句相当于JQuery的:var file =$("#upload").prop('files')[0];
                //             var file = fileInput.files[0];
                //             if (window.FileReader) {
                //                 var reader = new FileReader();
                //                 reader.onloadend = function (evt) {
                //                     if (evt.target.readyState == FileReader.DONE) {
                //                         callback(evt.target.result);
                //                     }
                //                 };
                //                 // 包含中文内容用gbk编码
                //                 reader.readAsText(file, 'gbk');
                //             }
                //         }
                //     };
                //
                //     /**
                //      * upload内容变化时载入内容
                //      */
                //         document.getElementById('upload').onchange = function () {
                //             var content = document.getElementById('content');
                //
                //             getFileContent(this, function (str) {
                //                 content.value = str;
                //             });
                //         };
                // };

        $("#my-github-projects").loadRepositories("jashkenas", code);
        // jQuery.getJSON(target,function(data) {
        //     var repos = data.data;
        // });
    }
});

jQuery.githubUser = function(username, callback) {
    console.log('https://api.github.com/users/'+username+'/repos?callback=?',callback);
   jQuery.getJSON('https://api.github.com/users/'+username+'/repos?callback=?',callback)
};

jQuery.fn.loadRepositories = function(username) {
    this.html("<span>Querying GitHub for " + username +"'s repositories...</span>");

    var target = this;
    $.githubUser(username, function(data) {
        var repos = data.data; // JSON Parsing
        sortByName(repos);    

        var list = $('<dl/>');
        target.empty().append(list);
        $(repos).each(function() {
            if (this.name != (username.toLowerCase()+'.github.com')) {
                list.append('<dt><a href="'+ (this.homepage?this.homepage:this.html_url) +'">' + this.name + '</a> <em>'+(this.language?('('+this.language+')'):'')+'</em></dt>');
                list.append('<dd>' + this.description +'</dd>');
                list.append('<dd><em>Size: '+(this.size<1000?(this.size+' kB'):(Math.round((this.size/1000)*100)/100+' MB'))+' - Watchers: '+this.watchers+' - Forks: '+this.forks+' - Stars: '+this.stargazers_count+' </em></dd>');
                list.append('<dd><em>Updated At: '+ this.updated_at +'</em>');
                list.append('<dd><br/></dd>');
            }
        });      
      });

    function sortByName(repos) {
        repos.sort(function(a,b) {
        return a.name - b.name;
       });
    }
};

UPDATE: By using the code above and an extent on Chrome to avoid CORS, now I can get the information inside the file. But I cannot do it at the client side as it claims the "requested resource", which should be the github's access token, does not have the heading CORS needs and refuses me to access.


Solution

  • I just found a way in another question to get around the CORS.

    No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

    Hope this helps anyone who may be facing the same problem like this.