YouTube Analytics API for content owners - api

I implemented the Youtube Analytics API in js and everything is ok with that. I am the content owner and I want to get analytics for all channels and to allow login users to use their analytic.
For example, when some users make login to my dashboard I pass their channel ids to YouTube and it is ok, they get their data. They have to authenticate to YouTube with popup every time they log in.
I want to know is there any way to avoid that and to allow them like content owner to see their data.
I am using
window.onload = function () {
setInitialDates();
authenticate().then(loadClient).then(getDataFromAPI);
}
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/yt-analytics-monetary.readonly https://www.googleapis.com/auth/yt-analytics.readonly" })
.then(function () {console.log("Sign-in successful"); },
function (err) {console.error("Error signing in", err); });
}
function loadClient() {
return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")
.then(function () {console.log("GAPI client loaded for API"); userLoaded = true; },
function (err) {console.error("Error loading GAPI client for API", err); userLoaded = false; });
}

For your question about not having to log-in each time, you would need do the 'server-side flow' method of authentication.
User clicks button in your app to authenticate with YouTube.
YouTube log-in opens, user logs in with google account.
User approves any permission scopes you enabled.
User redirected back to your app with tokens, you can save the 'refresh_token' in your database.
With the refresh_token, you can then generate an authentication token to make API calls.
https://developers.google.com/youtube/reporting/guides/authorization
https://developers.google.com/youtube/reporting/guides/authorization/server-side-web-apps

Related

Is there a way to call the google books api from firebase auth to get a logged in users bookshelves in "My Library"?

I have the firebase auth set up and can log in, get the consent screen to access google books account, get the token, and log out.
Google will be deprecating the gapi.auth2 module and using Google Identity Services so I'm trying to find a solution that doesn't involve using the gapi.auth2 module.
The following website has an example of how to use the Google Identity Services:
https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#gis-only
In this example they use the Google Identity Services library to get the access_token to then pass it along in the The XMLHttpRequest object to request data from a logged in users account. Seeing as I can already get the access_token I'm trying to make the request without using the Google Identity Service or Google API Client Library for JavaScript and just use a XMLHttpRequest.
The below code returns a response of the index.html page and not the response from the google books API.
function getData(access_token){
if(access_token !== undefined){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText);
}
};
xhttp.open("GET", "books/v1/mylibrary/bookshelves/4/volumes?fields=totalItems, items(id)");
xhttp.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhttp.send();
}
}
function Login(){
useEffect(()=>{
signInWithGoogle();
});
provider.addScope("https://www.googleapis.com/auth/books");
const signInWithGoogle = () =>{
signInWithPopup(auth, provider).then((result)=>{
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
if(result.user){
getData(token);
}
}).catch((error)=>{
if(error.code === 'auth/popup-closed-by-user'){
}
});
}
return (
<p>Logging in...</p>
)
}
export default Login;
I know that "books/v1/mylibrary/bookshelves/4/volumes?fields=totalItems, items(id)" works because I've used it in a working version that doesn't use firebase as it's just a plain html version that uses the Google Services Identity library with the Google API Client Library for JavaScript. The network request look the same and have the same access_token with my adapted version and the plain html version that works.
Is there a way to call the google books API from firebase auth to get a logged in users bookshelves in "My Library"?

What is the simplest way to restrict access to a static website using social auth

I have a static website composed of html/css/javascript files. The website is automatically generated and updated frequently.
Instead of authorizing access to the website with a username/password (basic auth), I would like to have users authenticate using Google Sign-in/openID Connect, and then control access via a whitelist of gmail addresses.
What is the simplest way to set this up?
I ended up using oauth2_proxy which is exactly what I was looking for.
I configured to do the following:
oauth2_proxy listens on 0.0.0.0:443
When a user connects, the Google sign-in flow is initiated
After sign-in, it validates the user's email address against a whitelist
After successful validation, oauth2_proxy proxies the request to an upstream nginx server listening on 127.0.0.1:8080
Another way to add authentication or gated content to any static site:
1) First load a static container page (header, footer) and implement user Authentication js code using Auth0, firebase, okta etc.
2) When user successfully logs in then make an ajax api call passing that auth access_token to retrieve the sensitive content.
3) Load/append that sensitive content in the site using js.
Of Course, there has to be one server/serverless function which would listen to that ajax api call, authenticate it and sends the content back to the browser.
This is called client side authentication.
More on this: https://auth0.com/blog/ultimate-guide-nextjs-authentication-auth0/
Best way would be to use Firebase Auth!
Check it out at https://firebase.google.com/docs/auth/
You could check if the user is authenticated or not in this way.
<script type="text/javascript">
function initApp() {
// Listening for auth state changes.
// [START authstatelistener]
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
//User is signed in.
if (!emailVerified) {
//Additional check for email verification
}
} else {
// User is signed out.
}
});
// [END authstatelistener]
}
window.onload = function () {
initApp();
};
</script>
Check out https://authorizer.dev/. It's free and open source.
This tutorial explains how to get started for static sites (follow the UMD section): https://docs.authorizer.dev/authorizer-js
<script src="https://unpkg.com/#authorizerdev/authorizer-js/lib/authorizer.min.js"></script>
<script type="text/javascript">
const authorizerRef = new authorizerdev.Authorizer({
authorizerURL: `YOUR_AUTHORIZER_INSTANCE_URL`,
redirectURL: window.location.origin,
clientID: 'YOUR_CLIENT_ID', // obtain your client id from authorizer dashboard
});
// use the button selector as per your application
const logoutBtn = document.getElementById('logout');
logoutBtn.addEventListener('click', async function () {
await authorizerRef.logout();
window.location.href = '/';
});
async function onLoad() {
const res = await authorizerRef.authorize({
response_type: 'code',
use_refresh_token: false,
});
if (res && res.access_token) {
// you can use user information here, eg:
const user = await authorizerRef.getProfile({
Authorization: `Bearer ${res.access_token}`,
});
const userSection = document.getElementById('user');
const logoutSection = document.getElementById('logout-section');
logoutSection.classList.toggle('hide');
userSection.innerHTML = `Welcome, ${user.email}`;
}
}
onLoad();
</script>
Here is a video demo: https://youtu.be/uQka5O2RwpU?t=97

How do you solve Auth0's URL Mismatch error

I'm trying to implement Auth0 with lock (version 10.11.0) inside my Angular2 app. Auth0 works if I list every possible route in Auth0's client's Allowed Callback URLs setting. It seems Auth0 picks up the callback URL from whatever URL the user happens to be on when they decide to login. This is not a scalable approach. How do you solve this?
I've tried entering a redirectUrl value in auth options. This gets me a little further in that the app does redirect to the URL supplied, however, Auth0 lock's authenticated callback never fires so I cannot retrieve authenticated user's profile.
So, I'm stuck. It seems my only course of action is to list every conceivable route in Auth0's client's Allowed Callback URLs setting and pray the guys from marketing do not come up with more routes.
Here's my code:
let options =
{
auth:
{
//redirectUrl: 'http://localhost:4200',
//redirect: true,
responseType: 'token',
params:
{
scope: 'openid user_id name nickname email picture'
}
}
};
this.lock = new Auth0Lock('xxx', 'yyy', options);
this.lock.on("authenticated", (authResult) =>
{
console.log('#### AUTH RESULTS:', authResult);
localStorage.setItem('id_token', authResult.idToken);
this.lock.getProfile(authResult.idToken, (error, profile) =>
{
if (error)
{
return;
}
console.log('#### AUTHENTICATED USER PROFILE:', profile);
});
}
Any ideas on how to make Auth0 work so you do not have to list every possible route a user can be on before deciding to authenticate?

react-native: notify server that user logged into Facebook oAuth

So this is probably a thing I am missing.... I am building a react-native app for IOS, using facebook SDK for Facebook login (react-native-fbsdk).
it all works fine.... but, I want the app to access my server, and my server needs to know that the user is logged in (and who the user is).
I know how to do it with the standard oAuth server flow, but how do I do it in this case? how do I even get the code or access token?
In the FB documentation all I see is how to make requests from the app to FB API, I didn't find where to have a callback on the server, so that I can setup the session cookie with user info.
Thanks!
Use the LoginButton and set the required permissions. It will return you the access token, that you can send to your server. The server gets the username, email etc. via this access token from the facebook oauth service. Then the server can open the session and send the session id back to your react native app.
<LoginButton
readPermissions={["email", "public_profile"]}
onLoginFinished={
(error, result) => {
if (error) {
//alert("login has error: " + result.error);
} else if (result.isCancelled) {
// cancelled
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log("acces token:", data);
const token = data.accessToken.toString();
// call your server
// server can get user info from facebook
// returns back the session id
}
)
}
}
}
onLogoutFinished={() => true}/>

Facebook PHP SDK 3.0 (check if user is logged in)

I'm trying to use the Facebook PHP SDK 3.0 to be able to know if a user is currently logged on into his facebook account to display his information.
This is the flow:
User comes to my site and connects his account with my facebook app.
User is now logged in on my site, my site can access his information.
User logs out of facebook.com.
User refreshes my page.
User is logged out of my site.
User logs in on facebook.com.
User refreshes my page.
USER SHOULD BE LOGGED IN ON MY SITE BUT ISN'T.
When you use the Javascript SDK, you can check if user is logged in and everything works fine with the steps. What needs to be done with the PHP SDK 3.0? I don't want to give access_offline permissions, I just want to be able to access the user when he's logged in on facebook.com.
Thanks a lot,
Jeremie
Add this javascript in all pages(core js).
login() and logout() are functions for your system login and logout.
By this it will check every time fb is logged in or not and call function for login.
And will satisfy condition -
USER SHOULD BE LOGGED IN ON MY SITE BUT ISN'T.
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '113700398662301', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
</script>
based on the signed request, u should be able to know if the user has authorized your app before.
This should give u some status about the user.
to check if he is logged in to fb, for authorized user, u can try to query "/me" and see if you can query it successfully