meteor collection fs forbid upload - javascript

i want to forbid the upload / storage of files under special circumstances.
I tried in the collectionfs before hook:
Attachments.files.before.insert((userId, doc) => {
if(!Meteor.isServer){
if (!isUploadAllowed()) {
throw new Meteor.Error('Upload not allowed');
}
}
}
Unfortunately this is not working.
Is there a better way to achieve this? Or can someone help me?
(An ugly solution would be to remove the uploaded document in the after.insert hook, i hope there is a better way)

You can set the deny for this collection for all client operations to false:
const Attachments.files = new Mongo.Collection('fs.files')
Attachments.files.deny({
insert () { return true },
update () { return true },
remove () { return true }
})
This defaults to deny any client operation to sync with the server.

Related

Trigger won't return the proper user object in Realm/MongoDB

With Realm sync of MongoDB, I'm trying to launch a trigger when a realm user is created to insert his newly created ID into my cluster. Here's the javascript function I made that is being called by the trigger :
exports = async function createNewUserDocument({ user }) {
const users = context.services
.get("mongodb-atlas")
.db("BD")
.collection("patients");
const query = { email: context.user.data.email };
const update = {
$set: {
patientId: context.user.id
}
};
// Return the updated document instead of the original document
const options = { returnNewDocument: true };
console.log(context.user.data.email);
return users.findOneAndUpdate(query, update, options)
.then(updatedDocument => {
if(updatedDocument) {
console.log(`Successfully updated document: ${updatedDocument}.`)
} else {
console.log("No document matches the provided query.")
}
return updatedDocument
})
.catch(err => console.error(`Failed to find and update document: ${err}`))
};
When running from the embed editor, while specifying the proper user manually, it's working perfectly. However, when launched by the trigger, it looks like the user is the system user and not the created user, because the error I get in the logs is the same I get when I run from the editor by specifying System user, which is Failed to find and update document: FunctionError: cannot compare to undefined. This makes sense because the System user is not a user per se, so the context.user is undefined.
I find it weird since I specify in the function settings that it should be executed with the permissions of the user calling the function. So my question is, is it possible to access the user.context of a user on his creation, and if so, how would I do it ?

How to hit/consume post and get api in React Native with Ignite Bowser 2 Boilerplate. (Mobx state stree, type script)

I am new to React Native, please provide some Github link or your own code for reference. Consider me as a beginner in RN.
I found very less open support for RN, Mobx State tree, Ignite and all, so not just post and get API reference, if you find anything helpful related to these above-mentioned topics, Feel free to share.
Thanks in advance.
Mobx State Tree, With Ignite Bowler you would have api.ts file where you can specify API calls.
async getUser(userToken: string): Promise<Types.GetUserResult> {
// make the api call
const response: ApiResponse<any> = await this.apisauce.post(`api/v1/sales/login?authCode=${userToken}`)
if (!response.ok) {
const problem = getGeneralApiProblem(response)
if (problem) return problem
}
// transform the data into the format we are expecting
try {
try {
const rawUser = response.data
console.log('rawUser'+ rawUser)
const user: UserSnapshot = convertRawUserToUserStore(rawUser)
return { kind: "ok", user }
console.log({ user })
} catch (e) {
__DEV__ && console.tron.log(e.message)
return { kind: "bad-data" }
}
} catch {
return { kind: "bad-data" }
}
}
Consider, we will be getting user data from this API call,
you can notice that there is UserSnapshot which belongs to User Model, Snapshot will save the data automatically, you don't need Aysnc storage to save or retrieve data.

Feathers-mongoose : Get by custom attribute in feathers-mongoose

I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.

Angular web bluetooth write and notify example

Currently i'm working with this module for angular: Angular web bluetooth
I can find an example how to read characteristics and got it working. But there are no samples to write (or notify). I am pretty sure that this module is capable of this tasks, see here, but my knowledge of Angular (or even JS?) isnt enough.
Did someone have any idea where to find examples or/and can provide them?
Snippet to read battery level:
getBatteryLevel() {
console.log('Getting Battery Service...');
try {
return this.ble
.discover$({
acceptAllDevices: true,
optionalServices: [BatteryLevelService.GATT_PRIMARY_SERVICE]
})
.mergeMap((gatt: BluetoothRemoteGATTServer) => {
return this.ble.getPrimaryService$(
gatt,
BatteryLevelService.GATT_PRIMARY_SERVICE
);
})
.mergeMap((primaryService: BluetoothRemoteGATTService) => {
return this.ble.getCharacteristic$(
primaryService,
BatteryLevelService.GATT_CHARACTERISTIC_BATTERY_LEVEL
);
})
.mergeMap((characteristic: BluetoothRemoteGATTCharacteristic) => {
return this.ble.readValue$(characteristic);
})
.map((value: DataView) => value.getUint8(0));
} catch (e) {
console.error('Oops! can not read value from %s');
}
}
Thank you.
Edit: thanks to the assistance of Aluan Haddad i was able to perform a write request, with the right Service and Characteristic UUID
.mergeMap((characteristic: BluetoothRemoteGATTCharacteristic) => {
let value = new Uint8Array(1);
value[0] = 2;
return this.ble.writeValue$(characteristic, value);
}).subscribe();

Meteor routing with a session id

I'm trying to build a cart system without the user having to login.
I'm using ironrouter
Router.route('/cart', {
template: 'cart',
data: {
cart: function () {
return Carts.find({uid: Meteor.default_connection._lastSessionId}).fetch();
//return Carts.find({uid: "97gxA35vEAS63qsCR"}).fetch();
}
}
})
In my router I've got a cart method, which returns results based on the current session id... Well thats what Im trying to do anyways :)
It doesn't look like
Meteor.default_connection._lastSessionId
Is returning anything, can't think of a reason why though, it works in a client side file.
My routers are located within /lib/routers.js (typo correction)
If you need anymore information please do let me know, thanks in advanced!
I don't think you need to rely on undocumented features like Meteor.default_connection._lastSessionId for that. You can just use a session variable for that to which you assign a random id if it is not yet set:
Meteor.startup(function() {
if (!Session.get('id')) {
Session.set('id', new Mongo.ObjectID()._str);
}
});
Router.route('/cart', {
template: 'cart',
data: {
cart: function () {
if (Session.get('id')) {
return Carts.find({uid: Session.get('id')}).fetch();
}
}
}
});

Categories