In cloud code seems impossible to use Parse.Config.get() with express is it correct? - express

Is there any way to use Parse.Config.get() inside an expressjs app hosted in cloud code?
Looks very easy to use Parse.Object and Parse.User but with Parse.Config.get() the code is not deployed using "parse deploy"
We manage to use it adding the jssdk in html and using "frontend js" but haven't find any way to use in directly in express controllers.
Thanks

It seem to be related with some kind of permissions issues...
var Parse = require('parse-cloud-express').Parse;
var Util = require('util')
Parse.Cloud.define("currentConfig", function(request, response) {
console.log('Ran currentConfig cloud function.');
// why do I have to do this?
Parse.initialize(xxx, yyy);
Parse.Config.get().then(function(config) {
// never called
// ...
console.log(config.get('xxx'))
}, function(error) {
console.log(Util.inspect(error))
});
});
Output
Ran currentConfig cloud function.
{ code: undefined, message: 'unauthorized' }
Edited code which work for me:
var Parse = require('parse-cloud-express').Parse;
var Util = require('util')
Parse.initialize("appId", "restApiKey", "masterKey");
Parse.Cloud.define("currentConfig", function(request, response) {
console.log('Ran currentConfig cloud function.');
Parse.Cloud.useMasterKey();
Parse.Config.get().then(function(config) {
// never called
// ...
console.log(config.get('xxx'))
}, function(error) {
console.log(Util.inspect(error))
});
});
EDIT: Add solution :)

Related

Protect api routes with middleware in nextJS?

I'm new to next.js and I wanted to know if I could protect a whole API route via middleware. So for example if i wanted to protect /api/users Could I create /api/users/_middleware.ts and handle authentication in the middleware and not have to worry about authentication in the actual api endpoints? If so, how would I go about doing that? The library i'm using right now is #auth0\nextjs-auth0 so I guess it would look something like this? (Also please forgive me if I code this wrong, I am doing this in the stackoverflow editor)
export default authMiddleware(req,res)=>{
const {user,error,isLoading} = whateverTheNameOfTheAuth0HookIs()
if(user)
{
// Allow the request to the api route
}
else
{
// Deny the request with HTTP 401
}
}
Do I have the general idea correct?
next-auth v4 introduced middleware for this purpose. The basic use case is pretty simple.
You can add a middleware.js file with the following:
export { default } from "next-auth/middleware"
export const config = { matcher: ["/dashboard"] }
Other use cases can be found in the documentation
You can use middleware for that, something similar to this example from the documentation.
For a sub-directory inside pages, you can create a _middleware.ts file. It will run for all pages in this directory. It looks something like this:
import { NextRequest, NextResponse } from 'next/server'
export function middleware(req: NextRequest) {
const basicAuth = req.headers.get('authorization')
if (basicAuth) {
// do whatever checks you need here
const hasAccess = ...
if (hasAccess) {
// will render the specified page
return NextResponse.next()
}
}
// will not allow access
return new Response('No access', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"',
},
})
}
You can find more info in the documentation.

Input form provides File - how to I upload it to Azure Blob storage using Vue?

I'm clearly missing something here so forgive me - all examples seem to involve express and I don't have express in my setup. I am using Vue.js.
Ultimately, want my client-side Vue app to be able to upload any file to azure blob storage.
I have the file(File api) from my Vue form. However, it does not provide a path (I believe this is for security reasons). The Azure docs have this snippet example:
const uploadLocalFile = async (containerName, filePath) => {
return new Promise((resolve, reject) => {
const fullPath = path.resolve(filePath);
const blobName = path.basename(filePath);
blobService.createBlockBlobFromLocalFile(containerName, blobName, fullPath, err => {
if (err) {
reject(err);
} else {
resolve({ message: `Local file "${filePath}" is uploaded` });
}
});
});
};
Is this not the api I should be using? What should I be doing to upload any type of blob to blob storage?
UPDATE
Following #Adam Smith-MSFT comments below I have tried the vue-azure-storage-upload but can't seem to get the files up to azure.
startUpload () {
if (!this.files || !this.baseUrl) {
window.alert('Provide proper data first!')
} else {
this.files.forEach((file:File) => {
this.$azureUpload({
baseUrl: this.baseUrl + file.name,
sasToken: this.sasToken,
file: file,
progress: this.onProgress,
complete: this.onComplete,
error: this.onError
// blockSize
})
})
}
},
According to the console the response.data is undefined and when the onError method fires, that too gives me an undefined event.
I'd highly recommend checking the following tutorial: https://www.npmjs.com/package/vue-azure-blob-upload
The author used a specific npm package to upload blobs(you can using file service) to upload objects:
npm i --save vue-azure-blob-upload
I'd also recommend checking the Storage JS documentation: https://github.com/Azure/azure-storage-js/tree/master/file , it provides specific examples related to Azure File Storage as well.

Aurelia HttpClient cancel requests

I am trying to build an auto complete component and want to make it cancel unresolved requests to the server while they type.
I can find no documentation around this in the documentation for HttpClient. It mentions it IS cancellable (unlike fetch) but not how. https://aurelia.io/docs/plugins/http-services
Currently I have this which I cobbled together quite blindly, unsurprisingly it doesn't even abort the requests:
async searchTermChanged(newValue, oldValue) {
if (newValue.length < 3)
return;
if (this.promises.length) {
this.promises.forEach(x => x.abort());
//should probably remove too
}
var promise = this.httpClient.post(this.endpoint, { SearchTerm: newValue });
this.promises.push(promise);
var data = await promise;
var response = JSON.parse(data.response);
this.results = response;
}
}
Where can I find out more information on how to make cancellable requests? My google-fu is failing me.
Looks like you can do this:
this.client["pendingRequests"].forEach(request => {
request.abort();
});
I am having to do ["pendingRequests"] as I'm using TypeScript and the array does not seem to be within the definition.
Note: I am also using a scoped HttpClient per autocomplete, so that when it cancels all previous requests it will not accidentally cancel something else that the app is requesting.

Need advice about testing using Chimp.js/Mocha in Meteor.js

I'm trying to teach myself testing with Meteor but there is so much conflicting and outdated info online it's really difficult to work out what I need to do.
My current situation it that I have an application using the latest Meteor version (and the imports folder structure).
I've installed chimp globally and have created a /tests directory.
My first test is using chimp/mocha to fill in a form and try to insert something to the database. I'm also using the xolvio/backdoor package and running chimp like so
chimp --ddp=http://localhost:3000 --mocha --path=tests
Here's my test code:
describe('Chimp Mocha', function() {
describe( 'Create a Client', function() {
it( 'should fill in add client form', function() {
browser.setValue('#clientName', 'Test')
.setValue('#clientEmail', 'test#test.com')
.selectByValue('#numberTeamMembers', '25')
.submitForm('#createClient')
});
it( 'should check the collections for new client data', function() {
let getClient = server.execute( function() {
return Clients.findOne({ name: 'Test' });
});
expect( getClient.name ).to.equal( 'Test' );
});
after( function() {
server.execute( function() {
let client = Clients.findOne( { name: 'Test' } );
if ( client ) {
Clients.remove( client._id );
}
});
});
});
});
This is throwing an error that Clients is undefined
However, if I add
import { Clients } from '/imports/api/clients/clients.js';
I get this error Error: Cannot find module '/imports/api/clients/clients.js'
What am I doing wrong? Should I be using chimp? Any help would really be appreciated because I don't find the Meteor guide very clear about this!
Thanks
You need to use require like this:
require('/imports/api/clients/clients').Clients
See here for an example.

Testing Ember Data

Anyone have any good examples of testing Ember data in your own app?
I'm starting to build an app using the Fixtures adapter, which is great. But I want to test my models and make sure everything works properly as I build.
I have QUnit setup and running, but I don't want to write the server side in order to verify that the Data Model makes a call. I'd like to mock out the Adapter and just see if the find method is called and return a new object from it. I'll worry about the server side implementation later.
Any ideas?
This is what I have so far (that doesn't work):
test('MyModel should call find', 1, function(){
App.TestAdapter = DS.Adapter.extend({
find: function(store, type, id){
ok(true, 'calls the find method');
console.log('find: ', type, id);
}
});
App.Store = DS.Store.extend({
adapter: 'App.TestAdapater'
});
myModel = App.MyModel.createRecord({
name: 'Test',
period: 0
});
// method that should call .find
myModel.currentObject();
});
I ended up going with Konacha.
The biggest part was:
before(function() {
Ember.run(function() {
App.initialize();
});
});
afterEach(function() {
Ember.run(function() {
App.reset();
});
});