Can't use cache:true with OAuth.initialize - eclipse

I am trying to use OAuth according to https://oauth.io/docs/api in an android eclipse app.
import io.oauth.*;
.....
final OAuth o = new OAuth(this);
o.initialize(KEY);
works fine.
However, I want to use the cache functionality in order not to log on every time, so I try
o.initialize(KEY, {cache: true});
Unfortunately this won't compile. I get
"Multiple markers at this line
-Syntax error on tokens, delete these tokens
-Syntax error on token(s), misplaced construct(s)"
As you can tell I am an android and Eclipse newbie, any help appreciated.

The public key is the only argument used for the initialize method.
The correct method that accepts the cache object as an argument is popup.
Example:
OAuth.initialize('x9x9x9x9x9'); //OAuth.io public key
var promise = OAuth.popup('google_mail', {cache: true});
promise.done(function (result) {
    // make API calls
});
promise.fail(function (error) {
    // handle errors
});

Related

Mistake in using DOMPurify on the backend to sanitize form data?

I was wondering if it was possible to use DOMPurify to sanitize user input on a form before it is saved to database. Here's what I've got in my routes.js folder for my form post:
.post('/questionForm', (req, res, next) =>{
console.log(req.body);
/*console.log(req.headers);*/
const questions = new QuestionForm({
_id: mongoose.Types.ObjectId(),
price: req.body.price,
seats: req.body.seats,
body_style: req.body.body_style,
personality: req.body.personality,
activity: req.body.activity,
driving: req.body.driving,
priority: req.body.priority
});
var qClean = DOMPurify.sanitize(questions);
//res.redirect(200, path)({
// res: "Message recieved. Check for a response later."
//});
qClean.save()
.then(result => {
//res.redirect(200, '/path')({
// //res: "Message recieved. Check for a response later."
//});
res.status(200).json({
docs:[questions]
});
})
.catch(err => {
console.log(err);
});
});
I also imported the package at the top of the page with
import DOMPurify from 'dompurify';
When I run the server and submit a post request, it throws a 500 error and claims that dompurify.sanitize is not a function. Am I using it in the wrong place, and/or is it even correct to use it in the back end at all?
This might be a bit late, but for others like me happening to run into this use case I found an npm package that seems well suited so far. It's called isomorphic-dompurify.
isomorphic-dompurify
DOMPurify needs a DOM to interact with; usually supplied by the browser. Isomorphic-dompurify feeds DOMPurify another package, "jsdom", as a dependency that acts like a supplementary virtual DOM so DOMPurify knows how to sanitize your input server-side.
In the packages' own words "DOMPurify needs a DOM tree to base on, which is not available in Node by default. To work on the server side, we need a fake DOM to be created and supplied to DOMPurify. It means that DOMPurify initialization logic on server is not the same as on client".
Building on #Seth Lyness's excellent answer --
If you'd rather not add another dependency, you can just use this code before you require DOMPurify. Basically what isometric-dompurify is doing is just creating a jsdom object and putting it in global.window.
const jsdom = require('jsdom');
const {JSDOM} = jsdom;
const {window} = new JSDOM('<!DOCTYPE html>');
global.window = window;

Loopback Operation hook receives options as empty

I'll try to explain this weird situation as simple as I can.
I've created an operation hook "before save" and make it in a mixin to add it to some models.
this mixin uses context.options to get current userId to do something.
this mixin is working perfectly if I call the operation directly (like POST /Accounts for example).
But if I call it inside a remote method, the context.options is empty, for example, if we have a method called POST /Accounts/Signup, and inside it, we call Account.create(...), the "before save" hook receives the options as empty object {}
A sandbox project has been hosted here
https://github.com/mustafamagdy/loopback-sandbox-issue
the mixin code snippet is as follows:
module.exports = function(Model, options) {
Model.observe("before save", async function(ctx) {
if (ctx.instance.id) return;
const userId = ctx.options && ctx.options.accessToken && ctx.options.accessToken.userId;
if (userId) {
//... do stuff
}
else
{
console.error("Failed to scope " + Model.name + " to user (null)");
}
});
};
After the investigation, I found this issue that talks about similar behaviour, however, the comments are very destractive. So I thoughlt to write the conclusion here for anyone who are facing the same issue.
Loopback require you to pass the options you declared from the remote method to the model method(s) if you want to receive it on operation hook, so I ended up doing so.
module.exports = function(Note) {
Note.makeNew = makeNew;
async function makeNew(options) {
await Note.create(obj, options);
}
};

HttpClient append parameter object to GET request

I'm quite the noob using Ionic or Angular for that matter. So as a cheat sheet I'm using the ionic-super-starter template (link below).
I am trying to make a get request to my API and it works just find if I'm doing it like this:
this.api.get('user/'+this.user.userId+'/entries?include=stuff&access_token=TOKEN');
but when I put the url params into an object it stops working:
let options = {
'include':'stuff',
'access_token':'TOKEN'
}
this.api.get('user/'+this.user.userId+'/entries', options);
The only error I get is "Unauthorized Request" since the options object including the access token was not appended to the url.
In the ionic-super-starter template the providers/api/api.ts calls .set() for each key in my params object:
if (params) {
reqOpts.params = new HttpParams();
for (let k in params) {
reqOpts.params.set(k, params[k]);
}
}
but according to Angular University this is not possible since "HTTPParams is immutable".
If it really was wrong to do this, I don't believe it would be in the ionic template. Nor would I believe that I would be the first person to come across this issue.
However, I am stuck here so any help would be appreciated.
Link to Angular University:
https://blog.angular-university.io/angular-http/#httprequestparameters
Link to ionic-super-starter:
https://github.com/ionic-team/starters/tree/master/ionic-angular/official/super
I think I figured it out myself:
if I write (in my src/providers/api/api.ts)
reqOpts.params = reqOpts.params.append(k, params[k]);
instead of
reqOpts.params.set(k, params[k]);
it works.
if you are using a loopback API as I am you might have nested objects like:
let options = {
"filter": {
"order": "date DESC"
},
"access_token":this.user._accessToken
};
this won’t work. try instead:
let options = {
"filter": '{"order":"date DESC"}',
"access_token":this.user._accessToken
};

Visualize.js authentication error after second login

I have a website—utilizing Visualize.js—that has a simple login/logout feature. Everytime I login I call the authenicateUser() function and logout destroySession(). When I try login and then logout and then login again, when I try to render my existing reports I get this thrown error:
HTTP Status 401 - Full authentication is required to access this resource
The functions authenicateUser() and destroySession() are shown below:
function authenticateUser () {
var myConfig = {
auth : {
name : "superuser",
password : "superuser"
}
};
visualize.config( myConfig );
}
function destroySession() {
visualize( function ( v ) {
// Logout form JRS and finish the session.
v.logout().done( function () {
} );
} )
}
I would like to point out that when I first login my account this error is not thrown and renders the reports perfectly.
Why is this happening after logout and then login again?
This seemed to have worked for me. So I called visualize.config( config ) first so that I can store common configuration, to share them between visualize calls and then called the login method so that I can perform authentification with provided auth object. My reference: http://community.jaspersoft.com/wiki/visualizejs-api-notes-and-samples-v56
visualize.config( config );
visualize( function ( v ) {
v.login( config );
} );
This solution was not in their documentation though, but I put them piece by piece to finally solve the problem.
The documentation contained solution to this problem although it is not very explicit. See sample code and sample link from documentation link
visualize.config({
auth: {
name: "superuser",
password: "superuser"
}
});
Share common config between 'visualize' calls
Just a note:
Actually when you login you need to logout at some appropriate event. This depends on your application requirement e.g. if you are embedding reports within an existing web application, it seems more appropriate to link it existing application login/lougut

how to retrieve response.error and response.success messages in c# (Unity3D)?

I had the exactly same problem with this thread
https://www.parse.com/questions/how-to-retrieve-responseerror-and-responsesuccess-messages-in-c-unity3d
which is archived without any comment or question.
On the cloud code
Parse.Cloud.beforeSave("GameScore", function(request, response) {
response.error("MY_ERROR_CODE");});
In Unity C# code:
ParseCloud.CallFunctionAsync<string>("Function", paramsDict)
.ContinueWith(t => {
if(t.IsFaulted){
foreach(Exception e in t.Exception.InnerExceptions){
ParseException ex = (ParseException)e;
Debug.Log (ex.Message);
}
}
Debug.Log ("HERE1");
string result = t.Result
Debug.Log ("HERE2");
});
The output is always "400 Bad Request", or something not my own error code "MY_RRROR_CODE".
I want to make my app know the different errors exactly to have corresponding result.
Questions:
How can I get "MY_ERROR_CODE" in Unity?
Why "HERE1" is printed in the console but not "HERE2"? Every code after "string result = t.Result" is not called. Am I missing some important features of the ContinueWith function?
In your Cloud Code you aren't creating a Cloud Function called Function, you are only creating a beforeSave() handler.
In your Unity C# code your string result = t.Result doesn't have a ; at the end, otherwise it should work.
According to Christine Abernathy here: https://www.parse.com/questions/unity-sdk-handling-errors ... it's not possible to get more information about errors from Parse in Unity because of Unity's limited HTTP stack.