Accessing Azure Application Settings with JavaScript - javascript

I am hosting my website with Microsoft Azure. I have set up a few Application Settings (which should act as Environment Variables) for a secret key and ClientID for some GET requests I am doing. I have spent the last 3 hours googling trying to find a solution. According to Azure's Docs, I need to use process.env.KEY, but that is not working. When that is done I get this error in the console of my website jQuery.Deferred exception: process is not defined ReferenceError: process is not defined
Everything that I have so found is Node.js, but I do not use that. My website is purely HTML, CSS and the occational JavaScript script. Anyone that has any answers for me that can either put me on the correct path or helps me solve the issue completely?
Edit: This is the code for my script.js
$(document).ready(function() {
// $(window).scroll(function(){
// if(this.scrollY > 20){
// $(".menu").addClass("sticky");
// }
// else {
// $(".menu").removeClass("sticky");
// }
// });
$('.menu-toggler').click(function() {
$(this).toggleClass("active");
$(".menu-menu").toggleClass("active");
});
// Check if streamer is live on twitch
const Url = 'https://api.twitch.tv/helix/streams?user_login=pokimane';
$.ajax({
url: Url,
type: "GET",
success: function(result) {
var json = JSON.stringify(result);
if (json.includes('"type":')) {
$(".twitch").addClass("live");
};
},
error: function(error) {
console.log(`Error ${error}`)
},
isLocal: true,
jsonp: true,
headers: {
'Client-ID': process.env.CLIENT_ID,
'Authorization': `Bearer ${process.env.CLIENT_AUTH}`,
'accept': 'application/vnd.twitchtv.v5+json',
}
});
});

NEWEST
This api need add bear token to request.
According to your description, your project is only html+js, which is originally a static resource, hard coding will definitely cause security issues. But you will be much safer using rest api now.
Because you first need to obtain the bear token, you need to refer to the official documentation for details.
Microsoft identity platform and OAuth 2.0 authorization code flow
If you want to make minimal changes to the project, you may need to use ROPC flow. You can refer my another in another post.
PRIVIOUS
You can use rest api to get application settings.
The JavaScript script in Html does not support node usage. The syntax of process.env.CLIENT_ID is suitable for use in complete nodejs projects. It is recommended to use restapi to get the value of the application settings you want.
My custom settings in portal.
You can access this site. Web Apps - List Application Settings.

Related

How to consume Notion API with React

I'm trying to use the new Notion API as a CMS for my personnal website.
As a way to improve, i tried to use it with React. But it seems that it does not allow CORS (i use Axios).
What is the best way to consume this API ? Use an Express.JS Back-end ? I would think it's overkill for my use (I just want to read pages & blocks, not edit).
Here is my actual API Call, but from React :
const getPages = (apiCmsPage) => {
var config = {
method: 'get',
url: 'https://api.notion.com/v1/blocks/'+ apiCmsPage +'/children?page_size=100',
headers: {
'Authorization': KEY,
'User-Agent' : 'PostmanRuntime/7.26.8'
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
In fact, I never really experienced back-end, so I don't know if it's really obligated to use the API.
Thanks.
I solved this problem by Next.js.
I tried the official notion-sdk-js, but still can’t solve this problem, because it may be aimed at the server instead of the client.
By using the getServerSideProps of Next.js, Notion data can be obtained through fetch before each client request, and then the rendered page is directly returned to the client. Because the request is completed on the server side, there is no CORS problem. But the price is that you have to keep a Next.js process in the background for rendering the page.
Would you consider using a react framework like NextJS? You can use its SSG feature to generate the pages during build time, in which your credentials will not be visible on client side.
https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
Notion also has an official js sdk, so you don't have to do all the API call hard work:
https://github.com/makenotion/notion-sdk-js

Downloading a slack file just returns login page?

I'm trying to download a file from slack, using Node. I'm think what I've got should work in theory - but I just seem to keep getting the login page as a response and I can't work out why. I've also tested via postman too and get the same result.
I believe I've followed the correct steps according to https://api.slack.com/tutorials/working-with-files with the bearer token. I'm using my own token trying to download an image that I posted - so I should have permission to do so. I've used this same token with the node-sdk without any problems.
// file.url_private = https://files.slack.com/files-pri/TDGL0NYUE-FHQN2HRQQ/download/brian.jpg
// token = xoxp-4586..........
const options = {
url: file.url_private,
method: "GET",
headers: {
"Authorization": `Bearer ${this.token}`,
}
};
request(options).pipe(fs.createWriteStream(`c:/temp/test/${file.title}`));
The pipe etc is working correctly, but saving a login html page instead. I'm wondering if anyone can point me in the right direction?
So having set up my scopes a while ago, I forgot about them. Turns out the scope of the token I created didn't have the files.read permission required to download a file!

How to Call a Firebase Authenticated Cloud Endpoint from Javascript?

I've written several Google Cloud Endpoints in Python and have followed the directions to require that calls to them come from users authenticated using Firebase. I need to call my Endpoints from a web app using JavaScript, but I can't seem to get the authentication working.
I'd like to use the Google APIs client (gapi) which comes with the added benefit of dynamically generating the client library from a provided discovery document. When I try using the gapi client, I can make the call to my API just fine, but I get an HTTP 401 as a response, along with the HTTP unauthorized message that my python source returns.
Google's documentation on the subject is rather sparse. I gather from one tutorial on the subject that a standard Ajax call can be used, but I don't see any documentation on how to call a Firebase authenticated endpoint from Gapi. My current concern is that the gapi client may not be set up (yet) to allow for the use of a discovery doc and also allow for the Authorization header to be set as Firebase Auth requires.
Is what I'm attempting even possible?
Any suggestions would be appreciated. Perhaps calling a Firebase Authenticated endpoint isn't possible using the gapi client.
Here's a rough outline of my gapi js code:
function(token) {
gapi.client.init({
apiKey: 'MY_API_KEY',
discoveryDocs: [MY_DISCOVERY_DOC_URL'],
clientId: 'MY_WEB_CLIENT_ID',
scope: 'profile'
}).then(function(){
return gapi.client.my.server.api.call();
}).then(function(response){
console.log(response.result.data)
}, function(reason){
console.log('Error: ' + reason.result.error.message)
});
}
I have been struggling with this for a while now and finally made it work. I found two options:
Option 1) If you want to use the gapi.client library:
There is a method called gapi.client.setToken(tokenObject) - documentation
However, it seems to be new (July '17) and little documentation or examples are available. I made it work doing the following (this is in angularJS with angular-fire but I hope you get what I am doing, basically ignore the "$scope")
// any time auth state changes, add the user data to scope
$scope.auth.$onAuthStateChanged(function (firebaseUser) {
$scope.firebaseUser = firebaseUser;
$scope.idToken = null;
// get the token from the firebase User Object
// Note that getToken() is deprecated and for me it did not work as desired
// use getIdToken() instead
firebaseUser.getIdToken().then(function (idToken) {
$scope.idToken = idToken;
});
});
// Now you can use setToken
// If from the docs you were thinking firebase's getIdToken() gives me TokenObject and gapi's setToken()
// expects a TokenObject so I'll just pass it - you'd be wrong! (at least for me - if it works for you please give me a heads up)
// You'll need to build your own token:
var homemadeToken = {
access_token: $scope.idToken.toString() // This feels so wrong
};
gapi.client.setToken(homemadeToken);
gapi.client.yourapi.getSomething().execute(function (resp) {
// Do stuff with the response
}
);
Option 2) Use jQuery's Ajax request - documentation
$.ajax(backendHostUrl + '/_ah/api/yourapi/v1/someendpoint', {
headers: {
'Authorization': 'Bearer ' + $scope.idToken // Here it worked without making a string first but I did not check why
},
method: 'GET',
success: function (resp) {
// Do stuff with the response
}
});
If after all of that your backend is still not accepting the tokens and you have migrated from endpoints v1 to v2, it might help migrating again as described here. Esp. make sure the lib folder is created again.
Even after SDK updates, I noticed that if and once you migrated from v1 to v2 the "lib" folder is never updated regardless of whether or not it hase been updated.
Still not working?
This github page fixes the issue on the BACKEND side for an earlier version - the backend did not accept firebase tokens and needed to be hacked. If you want to apply the changes as described there and you are using the latest "lib" folder's (writing in July '17) users_id_token.py as per migration guide, note that the file has changed and you need to go against the explicit commentary in that file's _verify_signed_jwt_with_certs method:
# Formerly we would parse the token body here.
# However, it's not safe to do that without first checking the signature.
and parse the token before checking the signature. From that file's comments it can be inferred however, that Google plans to put the entire logic elsewhere - hopefully firebase friendly and safely.

How to make Android Java code call Node.js code?

I have some code that I have and I want to invoke some Node.js code and I'm not sure how to go about this. I want to implement these Firebase notifications as described in this blog post:
https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html
But there is some Node.js code that will listen on my Firebase Database and will detect if there is something being inserted into my database. Is there any way I can "deploy" this code somewhere on my Android application and have it so that this code will be invoked? Below is the Node.js code I woudl want to get invoked from my Android application:
var firebase = require('firebase');
var request = require('request');
var API_KEY = "..."; // Your Firebase Cloud Server API key
firebase.initializeApp({
serviceAccount: ".json",
databaseURL: "https://.firebaseio.com/"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notificationRequests');
ref.on('child_added', function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
request.ref().remove();
}
);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/user_'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
I would imagine I would need to host the code somewhere, but I feel like if all I need is to host one file somewhere it wouldn't be necessarily to deploy something like Google App Engine or Heroku unless I am mistaken. I guess I am just confused on how I can communicate between this file and the Java Android code I've written so far. If anyone could point me in the right direction, that'd be great. Thanks!
You can install something like Termux on the android and install node.js on it, and host your code locally on the device, but I must say that it seems like a strange way to use a node.js server (but it sure does sound fun!)
Take a look at this guide for installing Termux and node.js on your Android:
https://medium.freecodecamp.com/building-a-node-js-application-on-android-part-1-termux-vim-and-node-js-dfa90c28958f#.z9zjw5o8w
I am not sure how well the network traffic will flow from your node.js server to the database and back considering it is being hosted from inside a sort of emulator on the Android, but it's worth a shot.
Is there any way I can "deploy" this code somewhere on my Android application and have it so that this code will be invoked?
No. You don't run node.js code inside you Android application. That would defeat the purpose of separating the code.
The Node.js code runs on a so-called app server. Such an app server is a trusted place where you can run code. Since you control such a server (after all, nobody else has access to it), you can trust that the code that runs on the server is the code that you put there.
On your users' Android device, you can run code. But you can never trust that the code running on the device is the code that you sent there. After all the user can make changes to the app.
You should never mix application code with code that runs on a trusted server. The Node.js script from my article requires the Firebase Cloud Messaging server key to be able to send messages to devices. Since having access to this key allows you to send messages on your project's behalf, it should only be present on trusted serves - such as your app server.

How do you integrate the Parse Javascript API with Appcelerator and not use undocumented calls?

I would like to create a user from his/her Facebook credentials without using undocumented calls. I do not believe it is possible based on the current implementation of Parse Javascript Library for two known reasons:
1. The current implementation of the library does not support the Appcelerator HTTP client so it fails immediately. I have addressed this issue by extending the existing Parse Javascript library's ajax method to utilize the Appcelerator HTTP client.
http://www.clearlyinnovative.com/blog/post/34758524107/parse-appcelerator-titanium-the-easy-way
There has been approximately 2K views on the slide deck I created and about the same on the blog post, so it is pretty clear to me people want this to work.
2. The current implementation of the library assumes you are integrating with the Facebook Javascript library and that library does not work with Appcelerator either. In fact Appcelerator has integrated Facebook directly into the framework so there is no need for the javascript library. All of the information required to link a user account to Facebook can be easily gotten using the API calls that Appcelerator developers are already familiar with.
The original question was removed from the Parse Support forum so I am looking for a solution from a wider community.
Hi Aaron,
It's not helpful to other developers to promote using undocumented
APIs in the Parse library as a workaround, so I make the decision to
unlist it. I understand it might help in your particular case with
Titanium, and you're well aware of the implications of using private
APIs, but other users might overlook that warning. I hope you
understand.
Héctor Ramos Solutions Architect, Parse https://parse.com/help
This is the code that was too dangerous to be left visible on the forum:
// setting auth data retrieved from Ti.Facebook login
authData = {
"facebook" : {
"id" : Ti.Facebook.uid,
"access_token" : Ti.Facebook.accessToken,
"expiration_date" : expDate, // "format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
}
};
// Either way I resolved the problem, calling _handleSaveResult(true) on the returned user object,
// I just dont think it should have been as difficult as it was
// attempt to log the user in using the FB information
var user = new Parse.User();
user.save({
"authData" : authData
}).then(function(_user) {
// force the user to become current
_user._handleSaveResult(true); //<-- this is the evil method I called
if (!_user.existed()) {
// add additional user information
var userInfo = {
"acct_email" : "bryce#xxxxxx.com",
"acct_fname" : "Bryce",
"acct_lname" : "Saunders"
};
return _user.save(userInfo);
}
}).then(function(_user) {
alert('Hooray! Let them use the app now.');
}, function(error) {
alert(' ERROR: ' + JSON.stringify(error, null, 2));
});
Question on Appcelerator Forum
http://developer.appcelerator.com/question/152146/facebook-appcelerator-and-parse-integration-need-help
Question on Parse Forum
https://parse.com/questions/how-do-you-integrate-the-parse-javascript-api-with-appcelerator-and-not-use-undocumented-calls
Maybe this part of a newer SDK, but can't you just call:
Parse.FacebookUtils.logIn({
"facebook": {
"id": "user's Facebook id number as a string",
"access_token": "an authorized Facebook access token for the user",
"expiration_date": "token expiration date of the format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
},
{
success : function(_user) {},
error : function(_user, error) {}
}
};
It's not documented in the Javascript guide, but it is documented in the unminified version of the code visa vie:
#param {String, Object} permissions The permissions required for Facebook
log in. This is a comma-separated string of permissions.
Alternatively, supply a Facebook authData object as described in our
REST API docs if you want to handle getting facebook auth tokens
yourself.
I made some updates to your original code to support the lastest SDK which I'm going to publish on Github.
Thanks so much for spearheading this effort. Your original post saved me hours.

Categories

Resources