how to add a basic keen.io event with javascript - javascript

I am trying to set up a basic example that sends a custom keen.io event via js. At the moment I do not need any presentation, visualisation, etc.
Here is the example that I created from another one I found online. I attempted several variations, and all of them work in Google Chrome, but none of them works in Firefox (38.0 for Ubuntu canonical - 1.0).
if I add to the head the inline script (!function(a,b){a("Keen"...) as it is proposed in the manual, I do not get any errors in FF, but it seems that addEvent never gets called and it produces no response, "err" nor "res".
if I include the library from the CDN (d26b395fwzu5fz.cloudfront.net/3.2.4/keen.min.js), I get an error when the page is loaded:
ReferenceError: Keen is not defined
var keenClient = new Keen({
If I download the js file and serve it locally, after the button is clicked, I get the following error response:
Error: Request failed
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
All of these attempts work from Chrome, but I need this to work from other browsers too.

I received a response from keen.io team. It turned out that Adblock Plus is interfering with the script. After I disabled it everything works in FF as in Chrome.
After some investigation in turned out that request to http://api.keen.io was blocked by "EasyPrivacy" filter of ABP with these filter rules: keen.io^$third-party,domain=~keen.github.io|~keen.io
So, sending a request to an "in-between" server (a proxy) seems to be the only solution that I can see.
We have a bit specific use case - a need to track a static site and also an available access to a rails api server, but the solution we ended up using may come useful to someone.
error.html
<html>
<head>
<title>Error</title>
<script src="/js/vendor/jquery-1.11.2.min.js"></script>
<script src="/js/notification.js"></script>
<script type="text/javascript">
$(document).on('ready', function () {
try {
$.get(document.URL).complete(function (xhr, textStatus) {
var code = xhr.status;
if (code == 200) {
var codeFromPath = window.location.pathname.split('/').reverse()[0].split('.')[0];
if (['400', '403', '404', '405', '414', '416', '500', '501', '502', '503', '504'].indexOf(codeFromPath) > -1) {
code = codeFromPath;
}
}
Notification.send(code);
});
}
catch (error) {
Notification.send('error.html', error);
}
});
</script>
</head>
<body>
There was an error. Site Administrators were notified.
</body>
</html>
notification.js
var Notification = (function () {
var endpoint = 'http://my-rails-server-com/notice';
function send(type, jsData) {
try {
if (jsData == undefined) {
jsData = {};
}
$.post(endpoint, clientData(type, jsData));
}
catch (error) {
}
}
// private
function clientData(type, jsData) {
return {
data: {
type: type,
jsErrorData: jsData,
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
pageXOffset: window.pageXOffset,
pageYOffset: window.pageYOffset,
status: status,
navigator: {
appCodeName: navigator.appCodeName,
appName: navigator.appName,
appVersion: navigator.appVersion,
cookieEnabled: navigator.cookieEnabled,
language: navigator.language,
onLine: navigator.onLine,
platform: navigator.platform,
product: navigator.product,
userAgent: navigator.userAgent
},
history: {
length: history.length
},
document: {
documentMode: document.documentMode,
documentURI: document.documentURI,
domain: document.domain,
referrer: document.referrer,
title: document.title,
URL: document.URL
},
screen: {
width: screen.width,
height: screen.height,
availWidth: screen.availWidth,
availHeight: screen.availHeight,
colorDepth: screen.colorDepth,
pixelDepth: screen.pixelDepth
},
location: {
hash: window.location.hash,
host: window.location.host,
hostname: window.location.hostname,
href: window.location.href,
origin: window.location.origin,
pathname: window.location.pathname,
port: window.location.port,
protocol: window.location.protocol,
search: window.location.search
}
}
}
}
return {
send: send
}
}());
example of sending notification manually from js code:
try {
// some code that may produce an error
}
catch (error) {
Notification.send('name of keen collection', error);
}
rails
# gemfile
gem 'keen'
#routes
resource :notice, only: :create
#controller
class NoticesController < ApplicationController
def create
# response to Keen.publish does not include an ID of the newly added notification, so we add an identifier
# that we can use later to easily track down the exact notification on keen
data = params['data'].merge('id' => Time.now.to_i)
Keen.publish(data['type'], data) unless dev?(data)
# we send part of the payload to a company chat, channel depends on wheter the origin of exception is in dev or production
ChatNotifier.notify(data, dev?(data)) unless data['type'] == '404'
render json: nil, status: :ok
end
private
def dev?(data)
%w(site local).include?(data['location']['origin'].split('.').last)
end
end

Related

Log minified JavaScript errors in production code

I am running a back-end app with a React JS frontend on our intranet. I don't want to use services like Sentry or Rollbar to keep track of minified code in production because I don't want to upload our source-maps externally.
Are there any self-hosted solutions for tracking & logging errors in JS source-maps?
We are using a combination of JSNLog and Stacktrace. This is what goes into the <head> of your index.html:
<script src="~/js/jsnlog.min.js"></script>
<script src="~/js/stacktrace.min.js"></script>
<script src="~/js/stacktraceConfig.js"></script>
And below the contents of stacktraceConfig.js:
window.onerror = function (msg, file, line, col, error) {
var callback = function (stackframes) {
var stringifiedStack = stackframes.map(function (sf) {
return sf.toString();
}).join('\n');
JL('serverLog').fatalException({
msg: 'Exception! ' + stringifiedStack,
1: '--------------------------------------------------------------',
errorMsg: msg,
url: stackframes[0].fileName + ":" + stackframes[0].lineNumber,
functionName: stackframes[0].functionName,
lineNumber: stackframes[0].lineNumber,
column: stackframes[0].column,
x: '--------------------------------------------------------------',
}, error);
};
var errback = function (err) { console.log(err.message); };
StackTrace.fromError(error).then(callback).catch(errback);
// Tell browser to run its own error handler as well
return false;
};
You will have to configure JSNLog yourself to have it send the errors by mail.

How can I send email notifications with Parse and Mandrill?

I am trying to use Mandrill to send an event-based email notification to the users of my web app. I am using Parse with Back4App.
In this tutorial (https://docs.back4app.com/docs/integrations/parse-server-mandrill/), the hosting providers suggest using the following method to call the Mandrill cloud code from an Android application:
public class Mandrill extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("your back4app app id”)
.clientKey(“your back4app client key ")
.server("https://parseapi.back4app.com/").build()
);
Map < String, String > params = new HashMap < > ();
params.put("text", "Sample mail body");
params.put("subject", "Test Parse Push");
params.put("fromEmail", "someone#example.com");
params.put("fromName", "Source User");
params.put("toEmail", "other#example.com");
params.put("toName", "Target user");
params.put("replyTo", "reply-to#example.com");
ParseCloud.callFunctionInBackground("sendMail", params, new FunctionCallback < Object > () {
#Override
public void done(Object response, ParseException exc) {
Log.e("cloud code example", "response: " + response);
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mandrill);
}
}
How can I implement this in JavaScript with the Parse JavaScript SDK?
This is what I've done so far but it won't send an email. I have Mandrill set up, as well as a verified email domain and valid DKIM and SPF.
// Run email Cloud code
Parse.Cloud.run("sendMail", {
text: "Email Test",
subject: "Email Test",
fromEmail: "no-reply#test.ca",
fromName: "TEST",
toEmail: "test#gmail.com",
toName: "test",
replyTo: "no-reply#test.ca"
}).then(function(result) {
// make sure to set the email sent flag on the object
console.log("result :" + JSON.stringify(result));
}, function(error) {
// error
});
I don't even get a result in the console, so I figure the cloud code is not even executing.
You have to add the Mandrill Email Adapter to the initialisation of your Parse Server, as described on their Github page. Also check the Parse Server Guide for how to initialise or use their example project.
Then set up Cloud Code by following the guide. You'll want to either call a Cloud Code function using your Android app or from any Javascript app, or use beforeSave or afterSave hooks of a Parse Object directly in Cloud Code, which allow you to send Welcome Emails when a user signs up. That could come in handy if you want to implement behaviour based emails based on object updates. Plus, because it is on the server and not the client, it is easier to maintain and scale.
To make the Cloud Code function actually send an email via Mandrill, you need to add some more code to your Cloud Code function. First, add a file with these contents:
var _apiUrl = 'mandrillapp.com/api/1.0';
var _apiKey = process.env.MANDRILL_API_KEY || '';
exports.initialize = function(apiKey) {
_apiKey = apiKey;
};
exports.sendTemplate = function(request, response) {
request.key = _apiKey;
return Parse.Cloud.httpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'https://' + _apiUrl + '/messages/send-template.json',
body: request,
success: function(httpResponse) {
if (response) {
response.success(httpResponse);
}
return Parse.Promise.resolve(httpResponse);
},
error: function(httpResponse) {
if (response) {
response.error(httpResponse);
}
return Parse.Promise.reject(httpResponse);
}
});
};
Require that file in your Cloud Code file, and use it like any other Promise.
var Mandrill = require("./file");
Mandrill.sendTemplate({
template_name: "TEMPLATE_NAME",
template_content: [{}],
key: process.env.MANDRILL_API_KEY,
message: {
global_merge_vars: [{
name: "REPLACABLE_CONTENT_NAME",
content: "YOUR_CONTENT",
}],
subject: "SUBJECT",
from_email: "YOUR#EMAIL.COM",
from_name: "YOUR NAME",
to: [{
email: "RECIPIENT#EMAIL.COM",
name: "RECIPIENT NAME"
}],
important: true
},
async: false
})
.then(
function success() {
})
.catch(
function error(error) {
});
Make sure you create a template on Mailchimp, right click it and choose "Send to Mandrill", so that you can use that template's name when sending via the API.
It's a bit involved, but once set up, it works like a charm. Good luck!

Cannot read user info - Adal error cannot login

I am trying to implement authentication with ADAL (Inside a react app), so I followed the example from Azure-Samples, and this is my code:
var AuthenticationContext = require('../../node_modules/adal-angular/lib/adal.js');
var adalInstance = new AuthenticationContext({
instance: 'https://login.microsoftonline.com/',
clientId: '9897809e-XXXX-XXXX-XXXX-3e6de068af92',
postLogoutRedirectUri: window.location.origin,
endpoints: {}
});
export function enter() {
adalInstance.login();
var isCallback = adalInstance.isCallback(window.location.hash);
adalInstance.handleWindowCallback();
if (isCallback && !adalInstance.getLoginError()) {
adalInstance.acquireToken(adalInstance.config.clientId, function (error, token) {
if (error || !token) {
console.log('ADAL Error Occurred: ' + error);
return;
}
});
}
var user = adalInstance.getCachedUser();
console.log(user);
}
export function logout() {
adalInstance.logout();
}
So I have the following messages:
ADAL Error Occurred: User login is required
and for user, I get null.
Currently I can go to the microsoft login page (called from the login component), login, and return to the app. I have the sessionStorage set:
Storage { adal.state.login: "73771340-XXXX-XXXX-XXXX-858c9edcba05", adal.nonce.idtoken: "20074445-XXXX-XXXX-XXXX-9f94c9b5cc31", adal.login.error: "", adal.error: "Invalid_state", adal.login.request: "http://localhost:3000/#id_token=eyJ…", adal.error.description: "Invalid_state. state: a2f210a5-e34b…", adal.token.renew.status: "Completed", length: 7 }
What I am doing wrong?
DATA: I am using adal.js library from the adal-angular package version: AdalJS v1.0.13
EDIT:
Now I am using an specific adal.js from here
I changed my code to:
var AuthenticationContext = require('./adal.js');
When I compiled it (using webpack with babel for transpiling es6 code), but gave me an error about logging is not defined, so I added:
var Logging = {
level: 3,
log: function (message) {
console.log(message);
}
}
to the adal library.
And now, I am getting in the browser(firefox, because chromes seems to not show any log I dont know why) console:
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-VERBOSE: State: d3c2bb0d-XXXX-XXXX-XXXX-e98a460572e2 bundle.js:74558:8
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-INFO: Returned from redirect url bundle.js:74558:8
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-INFO: State status:false; Request type:UNKNOWN bundle.js:74558:8
Wed, 18 Jan 2017 11:52:51 GMT:1.0.13-WARNING: User login is required bundle.js:74558:8
ADAL Error Occurred: User login is required bundle.js:74507:10
USER null bundle.js:74513:4
During integrating with PowerBi endpoint, I got a same error. After some research got this result. So the code below does auto login. Replace the method yourLogic to use the token for api request.
import AuthenticationContext from "adal-angular/lib/adal";
window.AuthenticationContext = AuthenticationContext;
let authenticationContext = new window.AuthenticationContext({
instance: "https://login.microsoftonline.com/",
clientId: "XXXXXXX",
postLogoutRedirectUri: window.location.origin,
cacheLocation: "localStorage", // enable this for IE, as sessionStorage does not work for localhost.
}),
resource = "https://analysis.windows.net/powerbi/api",
isCallback = authenticationContext.isCallback(window.location.hash);
authenticationContext.handleWindowCallback();
let user = authenticationContext.getCachedUser(),
token = authenticationContext.getCachedToken(resource),
loginActive = isCallback && user && !token,
renewActive = isCallback && user && !!token;
if (user) {
if (!renewActive) {
authenticationContext.acquireToken(resource, (errorDesc, token, error) => {
if (!error) {
yourLogic(token);
} else {
authenticationContext.error("Error when acquiring token for resource: " + resource, error);
}
});
}
} else {
authenticationContext.login();
}
Sorry for the characters limitation of comment, I write my troubleshooting suggestion as an answer here.
Actually, your code snippet works fine on my side. For troubleshooting and arrow down the issue, you can try the following options.
Currently, it seems that the javascript syntax on browser is not support export,require key words. So you can check the bundled script, whether there is anything wrong about the global variables. You can test your AAD application with plain javascript within adal.js, as the sample you are referring.
You can try to add global variable logging to track all the info during the authentication flow. E.G. add following code in js script.
Logging = {
level: 3,
log: function (message) {
console.log(message);
}
}

Meteor: Not able to upload image to S3 using CollectionFS

I am trying to test the upload functionality using this guide with the only exception of using cfs-s3 package. This is very basic with simple code but I am getting an error on the client console - Error: Access denied. No allow validators set on restricted collection for method 'insert'. [403]
I get this error even though I have set the allow insert in every possible way.
Here is my client code:
// client/images.js
var imageStore = new FS.Store.S3("images");
Images = new FS.Collection("images", {
stores: [imageStore],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Images.deny({
insert: function(){
return false;
},
update: function(){
return false;
},
remove: function(){
return false;
},
download: function(){
return false;
}
});
Images.allow({
insert: function(){
return true;
},
update: function(){
return true;
},
remove: function(){
return true;
},
download: function(){
return true;
}
});
And there is a simple file input button on the homepage -
// client/home.js
'change .myFileInput': function(e, t) {
FS.Utility.eachFile(e, function(file) {
Images.insert(file, function (err, fileObj) {
if (err){
console.log(err) // --- THIS is the error
} else {
// handle success depending what you need to do
console.log("fileObj id: " + fileObj._id)
//Meteor.users.update(userId, {$set: imagesURL});
}
});
});
}
I have set the proper policies and everything on S3 but I don't think this error is related to S3 at all.
// server/images.js
var imageStore = new FS.Store.S3("images", {
accessKeyId: "xxxx",
secretAccessKey: "xxxx",
bucket: "www.mybucket.com"
});
Images = new FS.Collection("images", {
stores: [imageStore],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
I have also published and subscribed to the collections appropriately. I have been digging around for hours but can't seem to figure out what is happening.
EDIT: I just readded insecure package and everything now works. So basically, the problem is with allow/deny rules but I am actually doing it. I am not sure why it is not acknowledging the rules.
You need to define the FS.Collection's allow/deny rules in sever-only code. These are server-side rules applied to the underlying Mongo.Collection that FS.Collection creates.
The best approach is to export the AWS keys as the following environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, remove the accessKeyId and secretAccessKey options from the FS.Store, and then move the FS.Collection constructor calls to run on both the client and server. The convenience of using env vars is mentioned on the cfs:s3 page
In addition to this you can control the bucket name using Meteor.settings.public, which is handy when you want to use different buckets based on the environment.

#me called by anonymous error when using google plus api inside a gwt project

I'm using the google api javascript client to get information about the user profile inside a gwt project hosted in google app engine.
In localhost, the data is being retrieved correctly. I get a json with the google plus profile. When I deploy to appengine, the response is 401, "#me called by anonymous".
Here is my Code:
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
$(function() {
auth();
});
var API_KEY = "***************************************";
var CLIENT_ID = "************.apps.googleusercontent.com";
var scopes = 'https://www.googleapis.com/auth/plus.me';
function auth() {
var config = {
'client_id' : CLIENT_ID,
'scope' : scopes,
'key' : API_KEY,
};
gapi.client.load('plus', 'v1', function() {
api.client.setApiKey(API_KEY);
gapi.auth.authorize(config, function() {
var request = gapi.client.plus.people.get({
'userId' : 'me',
});
request.execute(function(resp) {
console.log(resp);
});
});
});
}
</script>
What i tried:
call to api.client.setApiKey at the begining.
create a new google api access with the google api console
update:
This is the complete response error message:
{
"error": {
"code": 401,
"message": "me called by anonymous",
"data": [
{
"domain": "global",
"reason": "authError",
"message": "me called by anonymous",
"locationType": "header",
"location": "Authorization"
}
]
},
"id": "gapiRpc"
}
There are other messages that may be related:
This is one of them:
Skipping duplicate osapi method definition chili.people.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition pos.plusones.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition chili.activities.list on transport googleapis; others may exist, but suppressing warnings cb=gapi.loaded1 (línea 119)
Skipping duplicate osapi method definition googleapis.newHttpRequest on transport googleapis; others may exist, but suppressing warnings
this is the other:
Invalid auth token. 1025***** vs 140186****
I could finally resolve the issue with the following settings or steps:
1) In the google apis console, I left the Redirect URIs section empty and completed the JavaScript origins section with the url of my site, repeating it with the https protocol:
JavaScript origins:
http://example.com
https://example.com
I put the script that loads the api before the end body tag:
<script src="https://apis.google.com/js/client.js"></script>
This script comes inside the body, before the api script:
<script type="text/javascript">
var API_KEY = "***************************************";
var CLIENT_ID = "************.apps.googleusercontent.com";
var scopes = 'https://www.googleapis.com/auth/plus.me';
function auth() {
var scopes = 'https://www.googleapis.com/auth/plus.me';
gapi.client.setApiKey(API_KEY);
window.setTimeout(checkAuth, 1000);
function checkAuth() {
gapi.auth.authorize({
client_id : CLIENT_ID,
scope : scopes,
immediate : false
}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult) {
makeApiCall();
} else {
checkAuth();
}
}
function makeApiCall() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
$("#image").attr("src", resp.image.url);
});
});
}
}
</script>
Then I call the function auth() when the user clicks to see his picture.

Categories

Resources