using https://www.npmjs.com/package/slack-client
expects you to make an extra file just for the token and to get it you must do
process.env.SLACK_API_TOKEN
I don't like this approach of creating a file just for the sake of a token!
My code is server side, already in a directory that users cannot see so I would like to just write the token into the javascript as an object/string/array
I have so far failed with array
var token=[
'SLACK_TOKEN=xxxx'
, 'SLACK_CLIENT_ID=xxxx'
, 'SLACK_CLIENT_SECRET=xxxx'
];
and string
var token=
'SLACK_TOKEN=xxxx\n'
+ 'SLACK_CLIENT_ID=xxxx\n'
+ 'SLACK_CLIENT_SECRET=xxxx'
;
and object
var token={
SLACK_TOKEN:'xxxx'
, SLACK_CLIENT_ID:'xxxx'
, SLACK_CLIENT_SECRET:'xxxx'
};
Everyone else's apis just get you to put things like secret keys inside srings or objects like normal! How can I do this the normal way?
process.env.SLACK_API_TOKEN isn't a file, it's an environment variable. The advantage of keeping your API key there is that you can't accidentally commit it to version control. That said, the page you linked to makes it pretty clear that you don't have to use it:
var RtmClient = require('slack-client').RtmClient;
var token = process.env.SLACK_API_TOKEN || '';
var rtm = new RtmClient(token, {logLevel: 'debug'});
rtm.start();
Just set the token variable to your API token, then pass it as the first parameter to new RtmClient():
var RtmClient = require('slack-client').RtmClient;
var token = 'YOUR SLACK API TOKEN';
var rtm = new RtmClient(token, {logLevel: 'debug'});
rtm.start();
Related
I am a newbie in JavaScript or GatewayScript. I have a requirement where I need to convert the content of a .pem (which is in DataPower under local:///cert or can be added into a crypto object) to JWK.
Could anyone help me with the starting point on how to develop a javascript to
refer the crypto key object from DataPower (example crypto key
object JWKCryptoCertObj)
Decrypt the crypto key object (example
JWKCryptoCertObj.pem)
Convert the content of the key to JSON Web Key (jwk.readCertificate())
So far I have got to know that jwk.readCertificate() can help me to convert a key object to a JWK.
I have tried the below piece of code to fetch it:
var jwk = require('jwk');
var myJWK = jwk.readCertificate('cerjwk');
console.log(myJWK);
However, I get the below error in DataPower:
3:13:17 AM mpgw error 1277869681 error 0x00d30003 mpgw (PortTest): Rejected by filter; SOAP fault sent
3:13:17 AM multistep error 1277869681 request 0x80c00009 mpgw (PortTest): request PortTest_Policy_rule_1 #2 gatewayscript: Transforming the content of INPUT. The transformation local:///jwk.js is applied. The results are stored in testop. failed: Internal Error
3:13:17 AM gatewayscript error 1277869681 request 0x85800007 mpgw (PortTest): GatewayScript processing Error 'Error: Named certificate 'cerjwk' not found In file 'gatewayscript:///modules/jwk.js' line:428, stack:Error: Named certificate 'cerjwk' not found at Object.readCertificate (gatewayscript:///modules/jwk.js:428:18) at Object. (local:///jwk.js:5:17) at Script.execute (gatewayscript:///datapower.js:155:24) at Object. (gatewayscript:///datapower.js:582:55)'
3:13:17 AM crypto error 1277869681 request 0x8580005c mpgw (PortTest): Named certificate 'cerjwk' not found
Could anyone help me with the issue here? Thanks in advance!!
There is no need to convert the certificate. Just add it into a Crypto Key object and use the name (e.g. "crykey-my-key") of the object in the call, e.g.:
const jwk = require('jwk');
const myKeyJWK = jwk.readCertificate('crykey-my-key');
It finally worked, the thing that was needed to be changed was the cert, instead of the key.
Here is the working code:
var ctx = session.name('INPUT')|| session.createContext('INPUT');
var hm = require('header-metadata');
//var headers = hm.current;
var sm = require('service-metadata');
var uriIn=sm.getVar("var://service/URI");
var jwk = require('jwk');
var myJWK = jwk.readCertificate('qa.developer.citigroup.net');
//headers.set('X-new-header', myJWK);
//headers.set('Content-Type','application/json');
console.log(myJWK);
ctx.setVariable('yourjwk',myJWK);
session.output.write(myJWK);
Questions
How to serve javascript file dynamically? Specifically, the scripts maintain most of its body but with some variables changable (imagine HTML Jade template, but this is for pure javascript).
Scenario
When user or browser (http GET in general) visits /file.js passing parameter api, e.g. /file.js?api=123456, I would like to output pure javascript where I can take that 123456 and put in inside of my code, dynamically. Content-Type is application/javascript.
Sample:
var api = #{req.query.api}; //Pseudo
//The rest of my javascripts template
...
From my main .js file, I have set up the route:
app.get( '/file.js', function( req, res ) {
//Pseudo code that I would like to achieve
var name = req.query.name;
res.render( 'out_put_javascript_file_from_jade_file.jade', { name: name } );
});
So when a person visits /file.js, the script file will be rendered differently based on the parameter api passed in the URL. The only possible dynamic way I can think of is using Jade, but it doesn't allow pure javascript template. I believe there must be other solutions.
Please excuse my explanation. The problem is somewhat like this: How to generate a pure JavaScript file with Jade
If you want to do something quick and dirty, then you can do something like this (based on your example in the comments).
App init - read the .js template file and cache it:
// this should be async, but hey, not teaching you that part here yet
var fileJs = fs.readFileSync('file.js.template');
File.js:
(function() {
$(window).on('load', function() {
alert('Your api key is API_KEY_CONST');
});
})();
Request:
GET /api/file.js?key=123
Router:
app.get('/api/file.js', function(req, res) {
var key = req.query.key;
var key = fetchKeyFromDBSync(); // just to make it easier here, no async.
var out = fileJs.replace(API_KEY_CONST, key);
res.setHeader('content-type', 'text/javascript');
res.write(out);
res.end();
});
Now, this is really dumb and you should not try it at home, but it simply demonstrates how to do what you wanted.
Edit:
Depending on the file length, you might perform a bit better if you put the chunks of the file into an array, like:
var fileChunks = ['(function(){ blablabla;', 'var myAPIKey=', 'KEY_PLACEHOLDER', '; alert (myAPIKey);', '})()']
So later when you're resolving it with the real API key, you join the file.
fileChunks[2] = '12345';
var responseData = fileChunks.join('');
res.write(responseData);
But your last-accessed api key is then held in an array. Not quite future proof, but it shouls work if you need something quick.
I'm fairly new to Javascript, and assembled the following (part is from an example online, rest is by me):
This works reliably, I'm just wondering how many best-practices I'm violating. If someone is nice enough to provide general feedback about the latter part of this script, that would be appreciated.
The two included functions are to (1) capture the incoming website visitor's referral data on a page, including URL query strings for analytics, and store it to a cookie. (2) When the visitor completes a form, the script will read the cookie's URL value, parse this URL into segments, and write the segment data to pre-existing hidden inputs on a form.
Example URL this would capture and parse: http://example.com/page?utm_source=google&utm_medium=abc&utm_campaign=name1&utm_adgroup=name2&utm_kw=example1&kw=example2&mt=a&mkwid=xyz&pcrid=1234
function storeRef() { //this function stores document.referrer to a cookie if the cookie is not already present
var isnew = readCookie('cookiename'); //set var via read-cookie function's output
if (isnew == null) {
var loc=document.referrer;
createCookie('cookiename',loc,0,'example.com'); //create cookie via function with name, value, days, domain
}
}
function printQuery() { //function to parse cookie value into segments
var ref=readCookie('cookiename'); //write cookie value to variable
var refElement = ref.split(/[?&]/); //create array with variable data, separated by & or ?. This is for domain info primarily.
var queryString = {}; //From http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
ref.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
//write segments to form field names below.
document.getElementsByName('example1')[0].value = refElement[0]; //exampleX is a form hidden input's name. I can not use getElementById here.
//need to be able to manually define these, which is why they aren't in a loop, though I'm not sure how to loop an array referenced in this way
document.getElementsByName('example2')[0].value = queryString['utm_source'];
document.getElementsByName('example3')[0].value = queryString['utm_medium'];
document.getElementsByName('example4')[0].value = queryString['utm_term'];
document.getElementsByName('example5')[0].value = queryString['utm_content'];
document.getElementsByName('example6')[0].value = queryString['utm_campaign'];
document.getElementsByName('example7')[0].value = queryString['utm_adgroup'];
document.getElementsByName('example8')[0].value = queryString['utm_kw'];
document.getElementsByName('example9')[0].value = queryString['kw'];
document.getElementsByName('example10')[0].value = queryString['mt'];
document.getElementsByName('example11')[0].value = queryString['mkwid'];
document.getElementsByName('example12')[0].value = queryString['pcrid'];
}
Thank you!
why would you need to use a cookie to store the data for that, if unless you wanna keep track of the visitors visiting to your site?
My company hosts user created surveys on our server. When they are uploaded, they are given a key number as an identifier. I am trying to create a facebook app that people can post a simple survey to and distribute. I can set the canvas URL to the default URL of our server, but I need to pass that key to the query string at the end of the app URL.
<input type="hidden" id="SurveyKey" name="SurveyKey" value="130633791306">
so, the end link needs to be apps.facebook.com/myappname/130633791306
or apps.facebook.com/myappname/SurveyKey value
I am very new to JavaScript and didn't know if there was some get function that could just pull that from the source code and pass it into a new URL. I'm sure this is something easy, but as I am not sure how to word my question, my search result is coming up with a lot of unrelated material.
The URLs for our surveys look like this:
http://www.snapsurveys.com/swh/surveylogin.asp?k=130633791306
where k is a unique value for every survey. I want to be able to pull that value from the source code and pass it into the URL of my facebook app (which has the canvas URL set as our URL). So, it would look like apps.facebook.com/appname/k=VALUE_HERE
To get the query string in JavaScript you could use a code snipet like this:
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
Then you just define a variable to store the key, ie
var surveyKey = querySt("k");
Now you can use the surveyKey anywhere, so for example:
var url = "http://apps.facebook.com/appname/k=" + surveyKey;
http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml
I'm trying to implement a REST interface under IIS5.1/ASP-classic (XP-Pro development box). So far, I cannot find the incantation required to retrieve request content variables under the PUT HTTP method.
With a request like:
PUT http://localhost/rest/default.asp?/record/1336
Department=Sales&Name=Jonathan%20Doe%203548
how do I read Department and Name values into my ASP code?
Request.Form appears to only support POST requests. Request.ServerVariables only gets me to header information. Request.QueryString doesn't get me to the content either...
Based on the replies from AnthonyWJones and ars I went down the BinaryRead path and came up with the first attempt below:
var byteCount = Request.TotalBytes;
var binContent = Request.BinaryRead(byteCount);
var myBinary = '';
var rst = Server.CreateObject('ADODB.Recordset');
rst.Fields.Append('myBinary', 201, byteCount);
rst.Open();
rst.AddNew();
rst('myBinary').AppendChunk(binContent);
rst.update();
var binaryString = rst('myBinary');
var contentString = binaryString.Value;
var parameters = {};
var pairs = HtmlDecode(contentString).split(/&/);
for(var pair in pairs) {
var param = pairs[pair].split(/=/);
parameters[param[0]] = decodeURI(param[1]);
}
This blog post by David Wang, and an HtmlDecode() function taken from Andy Oakley at blogs.msdn.com, also helped a lot.
Doing this splitting and escaping by hand, I'm sure there are a 1001 bugs in here but at least I'm moving again. Thanks.
Unfortunately ASP predates the REST concept by quite some years.
If you are going RESTFull then I would consider not using url encoded form data. Use XML instead. You will be able to accept an XML entity body with:-
Dim xml : Set xml = CreateObject("MSXML2.DOMDocument.3.0")
xml.async = false
xml.Load Request
Otherwise you will need to use BinaryRead on the Request object and then laboriously convert the byte array to text then parse the url encoding yourself along with decoding the escape sequences.
Try using the BinaryRead method in the Request object:
http://www.w3schools.com/ASP/met_binaryread.asp
Other options are to write an ASP server component or ISAPI filter:
http://www.codeproject.com/KB/asp/cookie.aspx