Google picker authentication issue - google-api-js-client

The google picker dialog keeps asking to authenticate even after authenticating.
This is what it shows:
https://i.stack.imgur.com/PC4xD.png
When the sign-in button is clicked the authentication popup disappears immediately after showing for like a millisecond.
The First thing I tried was following the Google Picker API documentation at https://developers.google.com/drive/picker/guides/overview
Though I ran into a problem with that example.
tokenClient = google.accounts.oauth2.initTokenClient({
          client_id: 'YOUR_CLIENT_ID',
          scope: 'YOUR_SCOPES',
          callback: '', // defined later
        });
        gisInited = true;
the snippet above won't work because the property "accounts" no longer exists on the object "google". For some reason, the documentation is not up to date.
My second idea was to use the "gapi" library to handle the authentication process but then I ran in into the current issue.
Is there something I am missing?
(Current Code)
` gapi.load('client:auth2', () => {
initClient();
});
const initClient = () => {
try {
gapi.client.init({
apiKey: google_devkey,
clientId: google_client_id,
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
scope: 'https://www.googleapis.com/auth/drive.metadata.readonly',
}).then(() => {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
})
} catch (e) {
console.error("Auth Init ERROR:", e)
}
};
const updateSigninStatus = (isSignedIn) => {
console.error("isSignedIn::", isSignedIn)
if (isSignedIn) {
console.error("init Create Picker")
createPicker();
} else {
// prompt user to sign in
handleAuth();
}
};
const handleAuth = (event) => {
gapi.auth2.authorize({
client_id: settings.google_client_id,
scope: 'https://www.googleapis.com/auth/drive.metadata.readonly',
}, () => { })
};
function createPicker() {
let accessToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token || null
console.error("TOKEN:", accessToken)
if (accessToken) {
const picker = new window.google.picker.PickerBuilder()
.addView(window.google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
.setOAuthToken(accessToken)
.setDeveloperKey(google_devkey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
}
`

Related

I do a request to a protected route and it throws 401 unauthorized

I am using laravel 9 sanctum token, the authentication part is all right.
But when I'm inside and I do a request to a protected route, it throws 401 Unauthorized because when it went through the boot it didn't take the token but if I load the page again the data appears.
Part of the code below:
const api = axios.create({ baseURL: "http://localhost:8000/api/" });
api.defaults.headers["Authorization"] = `Bearer ${localStorage.getItem("token")}`;
// ...
setup() {
    const posts = ref([])
    onMounted(() => {
      getPosts()
    })
    const getPosts = async () => {
      try {
        const response = await api.get("/blogs")
        posts.value = response.data.data
      } catch (error) {
        alert(error)
      }
    }

How to open & display a file in ionic react

Trying to open a file from ionic react code, but couldn't do it as it throws an error with fileOpener.open is not recognized or undefined.
import { FileOpener } from '#awesome-cordova-plugins/file-opener/ngx';
const callFileOpen = () => {
    fileOpener.open("file:///C:/Users/seedapps.shankar/Downloads/sample.xlsx",'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
       .then(() => console.log('File is opened'))
       .catch(e => console.log('Error opening file', e));
  }

Netty channelRead is not getting invoked while waiting response from Oracle DB server over SSL

In my project, a Java client program tries to connect an Oracle DB server over SSL with Netty.
the client simply sends the connection string to DB server and waits the response (TCPS packets).
my code snippets are given below:
....
SSLContext sslContext = SSLContextFactory.getSslClient();
SSLEngine engine = sslContext.createSSLEngine();
engine.setEnabledProtocols(new String[]{"TLSv1"});
engine.setUseClientMode(true);
socketChannel.pipeline().addFirst("ssl",new SslHandler(engine));
....
In my handler class that extends ChannelInboundHandlerAdapter, I see that ssl handshake and peer authentication is completed successfully.
In addition to this,
ctx.channel().read();
line has been reached in the following method:
#Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.read();
        if (message != null) {
            ctx.writeAndFlush(Unpooled.copiedBuffer((byte[]) message)).addListener((ChannelFutureListener) (channelFuture) -> {
                if (channelFuture.isSuccess()) {
                    ctx.channel().read();
                } else {
                    channelFuture.cause().printStackTrace();
                    channelFuture.channel().close();
                }
            });
            message = null;
        }
    }
however, channelRead method is never called and DB server doesn't send any data.
I will be happy if You have any suggestions.
thanks in advance.

Elastic Search Querying - how to group the results and perform operations on results

I am very much new to Elastic Search. So need help in writing queries for use cases in Elastic Search.
We have a scenario where we need to perform operation on results of query and also do some grouping on data.
For example, Consider below sample use case.
Document has fields and values like below :
documentId : 1284che3t3bdf2
playerName : John
playerId : 123456
timestamp : X milliseconds (long value)
status : START_SPRINT
documentId : 45645bf6cxf3674
playerName : John
playerId : 123456
timestamp : Y milliseconds (long value)
status : END_SPRINT
Now we have to retrieve the time taken by player John to complete the sprint.
ie., we need to get time difference (Y-X) for
playerName:John
We also need average time taken for all players to complete sprint.
Looking at documentation, looks like using aggregations and filters we can achieve this.
Appreciate if any help with queries or any pointers to write these queries.
Could write below query so far using scripted metric aggregations :
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-scripted-metric-aggregation.html
{
    "query" : {
        "match_all" : {}
    },
    "aggs": {
        "average": {
            "scripted_metric": {
                "init_script" : "_agg['timestamps'] = []",
                "map_script" : "if (doc['status'].value == \"END\") {
_agg.timestamps.add(doc.timestamp.value)
} else {
_agg.timestamps.add(-1 * doc.timestamp.value) }",
                "combine_script" : "total = 0;
average = 0;
for (t in _agg.timestamps) { total += t };
average = total/_agg.timestamps.length;
return average",
                "reduce_script" : "average = 0;
for (a in _aggs) { average += a };
return average"
            }
        }
    }
}

infinite scrolling using jQuery

The script is working fine, but when the content ends, the page never reaches to the end. I need to make it stop infinite scrolling when the loaded content is end.
Another question, i dont want to load all the divs right away, i need to load it every five in five, how can i do that?
js:
if($(window).scrollTop() == $(document).height() - $(window).height())
    {
        $('div#loadmoreajaxloader').show();
        $.ajax({
        url: "loadmore.php",
        success: function(html)
        {
            if(html)
            {
                $("#postswrapper").append(html);
                $('div#loadmoreajaxloader').hide();
            }else
            {
                $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
            }
        }
        });
    }
html:
<div id="postswrapper">
<div class="item">content</div>
...
<div id="loadmoreajaxloader" style="display:none;"><center><img src="bigLoader.gif" /></center></div>
</div>
and the loadmore.php contains many <div class="item">content</div>
Ok I'm making 2 assumptions here first that you're calling the code you provided using the scroll listener. Second you might want to call the same code later.
To stop it you need to create a flag so it stop making the calls (or unbind the scroll if you dont want to use the same later), to paginate your results you need to create a variable that count the page you're actually showing but also you need to modify the code processing the ajax request so it uses the page data we're sending.
flag = true; //Flag to identify if the code should request more results
page = 1; //Current page
$(document).scroll(function(){
if(flag && ($(window).scrollTop() == $(document).height() - $(window).height()))
{
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php",
data: {page:page}
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
page++;
}else
{
flag = false;
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
});
}
});

Resources