How to use encryption in ydn-db database library? - client-side

I am trying to implement setSecret to encrypt the values in indexeddb but get the error:
"unable to call method setSecret of undefined"
Code Below:
$(window).load(function () {
//Database Schema
var db_schema = {
stores: [
{
name: "Employees",
}
]
}
var secret = "Test";
db.setSecret(secret);
db = new ydn.db.Storage('Database', db_schema);
});
Following the link, but not sure where I'm going wrong any ideas:
Anyone encrpyted there indexddb values before?
Thanks

Sorry for documentation behind. I have updated the documentation. Now you have to put encryption key in database options.
var schema = {
version: 1,
stores: [{
name: 'encrypt-store',
encrypted: true
}]
};
var options = {
Encryption: {
expiration: 1000*15, // optional data expiration in ms.
secrets: [{
name: 'aaaa',
key: 'aYHF6vfuGHpfWSeRLrPQxZjS5c6HjCscqDqRtZaspJWSMGaW'
}]
}
};
var db = new ydn.db.Storage('encrypted-db-name', schema, options);
You have to use "-crypt" module to get that feature. It supports transparent data encryption using sha256 crypto, per record salting and key rotation. You still need server to generate encryption key and send to the client securely. There is also a demo app.

//Database Creation
//Database Schema
var db_schema = {
stores: [{
name: "DataTable",
encrypted: true
}
]
};
var options = {
Encryption: {
//expiration: 1000 * 15, // optional data expiration in ms.
secrets: [{
name: 'aaaa',
key: 'aYHF6vfuGHpfWS*eRLrPQxZjSó~É5c6HjCscqDqRtZasp¡JWSMGaW'
}]
}
};
//Create the database with the relevant tables using the schema above
db = new ydn.db.Storage('Database', db_schema,options);
$.ajax({
type: "POST",
url: "/home/DownloadData",
data: { File: file },
success: function (result) {
var Key = result.Data.Key;
var DownloadedData= {
Data: result.Data,
Data1: result.Data1,
Data2: result.Data2,
Data3: result.Data3
};
db.put('DataTable', DownloadedData, Key);
return false;
},
error: function (error) {
alert("fail");
}
});

Related

How do I write an item to a DynamoDb with the AWS DynamoDB DocumentClient?

I'm having trouble with the AWS DynamoDb JS SDK v2.4.9. I want to use the DocumentClient class as opposed to the lower level DynamoDb class, but can't get it working.
This works:
function testPutItem( callback ) {
var tableName = 'todos';
var params = {
TableName: tableName,
Item: {
user_id: { S : userId },
id: { N : msFromEpoch }, // ms from epoch
title: { S : makeRandomStringWithLength(16) },
completed: { BOOL: false }
}
};
var dynamodb = new AWS.DynamoDB();
dynamodb.putItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data); // successful response
if (callback) callback(data);
}
});
}
This does not work and gives the error InvalidParameterType: Expected params.Item[attribute] to be a structure for each attribute--as if DocumentClient is expecting the same input as DynamoDb:
function testPutItem( callback ) {
var tableName = 'todos';
var params = {
TableName: tableName,
Item: {
user_id: userId,
id: msFromEpoch,
title: makeRandomStringWithLength(16),
completed: false
}
};
console.log(params);
var docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
docClient.put(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data); // successful response
if (callback) callback(data);
}
});
}
Does anyone have any idea what I am doing wrong?
I used to have the same issue,
please try with a simple object first, cause it's due to some special characters in your attributes, see my example :
this generates the error
InvalidParameterType: Expected params.Item[attribute] to be a structure
var Item = {
domain: "knewtone.com",
categorie: "<some HTML Object stuff>",
title: "<some HTML stuff>",
html: "<some HTML stuff>""
};
but when i replace the HTML stuff with a formated Html, simple characters , it works
var Item = {
domain: "knewtone.com",
categorie: $(categorie).html(),
title: $(title).html(),
html: $(html).html()
};

How to validate an update against SimpleSchema before updating a document in collection

I'm trying to validate my data against a SimpleSchema before it gets submitted to the collection but for some reason I'm not able to do so with this error.
Exception while invoking method 'createVendorCategory' { stack: 'TypeError: Cannot call method \'simpleSchema\' of undefined
I have one collections with two SimpleSchemas as follows.
Vendors = new Mongo.Collection('vendors'); //Define the collection.
VendorCategoriesSchema = new SimpleSchema({
name: {
type: String,
label: "Category"
},
slug: {
type: String,
label: "Slug"
},
createdAt : {
type: Date,
label: "Created At",
autoValue: function(){
return new Date()//return the current date timestamp to the schema
}
}
});
VendorSchema = new SimpleSchema({
name: {
type: String,
label: "Name"
},
phone: {
type: String,
label: "Phone"
},
vendorCategories:{
type: [VendorCategoriesSchema],
optional: true
}
});
Vendors.attachSchema(VendorSchema);
The vendorCategory will be added after the Vendor document is created by the user.
Here is what my client side looks like.
Template.addCategory.events({
'click #app-vendor-category-submit': function(e,t){
var category = {
vendorID: Session.get("currentViewingVendor"),
name: $.trim(t.find('#app-cat-name').value),
slug: $.trim(t.find('#app-cat-slug').value),
};
Meteor.call('createVendorCategory', category, function(error) {
//Server-side validation
if (error) {
alert(error);
}
});
}
});
And here is what my server side Meteor.methods look like
createVendorCategory: function(category)
{
var vendorID = Vendors.findOne(category.vendorID);
if(!vendorID){
throw new Meteor.Error(403, 'This Vendor is not found!');
}
//build the arr to be passed to collection
var vendorCategories = {
name: category.name,
slug: category.slug
}
var isValid = check( vendorCategories, VendorSchema.vendorCategories.simpleSchema());//This is not working?
if(isValid){
Vendors.update(VendorID, vendorCategories);
// return vendorReview;
console.log(vendorCategories);
}
else{
throw new Meteor.Error(403, 'Data is not valid');
}
}
I'm guessing this is where the error is coming from.
var isValid = check( vendorCategories, VendorSchema.vendorCategories.simpleSchema());//This is not working?
Any help would be greatly appreciated.
Since you've already defined a sub-schema for the sub-object you can directly check against that:
check(vendorCategories,VendorCategoriesSchema)

Public Key Encryption in Microsoft Edge

I have the following JavaScript code to implement public key encryption using the Web Cryptography API. It works for Firefox and Chrome but fails for Microsoft Edge. The error I am getting from Edge is "Could not complete the operation due to error 80700011." What have I missed?
<script>
var data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
var crypto = window.crypto || window.msCrypto;
var cryptoSubtle = crypto.subtle;
cryptoSubtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: "SHA-256" },
},
true,
["encrypt", "decrypt"]
).then(function (key) {
console.log(key);
console.log(key.publicKey);
return cryptoSubtle.encrypt(
{
name: "RSA-OAEP"
},
key.publicKey,
data
);
}).then(function (encrypted) {
console.log(new Uint8Array(encrypted));
}).catch(function (err) {
console.error(err);
});
</script>
I've found the cause of this issue. I have to add the hash field when invoking the encrypt function:
return cryptoSubtle.encrypt(
{
name: "RSA-OAEP",
hash: { name: "SHA-256" }
},
key.publicKey,
data
);
This does not match the Web Cryptography API Spec but it works.
Same problem with crypto.subtle.sign. Needed to add the hashing algorithm (same issue in Safari)
Replace
crypto.subtle.sign(
{
name: "RSASSA-PKCS1-v1_5"
},
cryptoKey,
digestToSignBuf);
with
crypto.subtle.sign(
{
name: "RSASSA-PKCS1-v1_5",
hash: "SHA-256"
},
cryptoKey,
digestToSignBuf);

meteor - How to add a subdocument as reference with SimpleSchema

I have the following SimpleSchema
Schema.Team = new SimpleSchema({
name:{
type:String
},
members: {
type: [Schema.User],
optional:true
}
});
I would like to insert (on the server) a new team document with the current user, as a reference (not as an embedded document).
I have tried:
Teams.insert({name:"theName",members:[Meteor.user()]}) // works but insert the user as an embedded doc.
Teams.insert({name:"theName",members:[Meteor.user()._id]}) // Error: 0 must be an object
I have also tried in two steps:
var id = Teams.insert({name:teamName});
Teams.update({ _id: id },{ $push: { 'users': Meteor.user()._id } });
Then I have another error I don't understand: Error: When the modifier option is true, validation object must have at least one operator
So how can I insert a document with a reference to another schema?
If you just want to store an array of userIds in your Team collection try:
Schema.Team = new SimpleSchema({
name:{
type:String
},
members: {
type: [String],
optional:true
}
});
Then
Teams.insert({ name: "theName", members: [Meteor.userId()] });
Should work. Later when you want to add an additional id you can just:
Teams.update({ _id: teamId },{ $addToSet: { members: Meteor.userId() }});
The following is probably the syntax you are after, assuming you are also using AutoForm.
If you are using collection2, you can also add an autovalue for when a team is created to automatically add the creator to that team for more convenience.
Schema.Team = new SimpleSchema({
name: {
type:String
},
members: {
type: [String],
defaultValue: [],
allowedValues: function () {
// only allow references to the user collection.
return Meteor.users.find().map(function (doc) {
return doc._id
});
},
autoform: {
// if using autoform, this will display their username as the option instead of their id.
options: function () {
return Meteor.users.find().map(function (doc) {
return {
value: doc._id,
label: doc.username // or something
}
})
}
},
autoValue: function () {
if (this.isInsert && !this.isFromTrustedCode) {
return [this.userId];
}
}
}
});

How to change a schema key?

I have a schema defined below and how can I change the predefined schema key (summary: key) via meteor template?
Schemas.Books = new SimpleSchema(
{
summary: {
type: String
}
}
);
For instance, I want to change this key through a session variable that was defined by router or through a user input.
Not Sure, Try this
If your schema is like this
Books = new SimpleSchema(
{
summary: {
type: String
}
}
);
then in tempalte helpers,
Books._schema.summary.type = function() {
return Session.get("typeValue");
};
In my project I have schema like this
RegisterSchema = new SimpleSchema({
name: {
type: String
},
email: {
type: String,
regEx: SimpleSchema.RegEx.Email
},
password: {
type: String,
label: "Password",
min: 8
},
confirmPassword: {
type: String,
label: "Confirm Password",
min: 8,
custom: function () {
if (this.value !== this.field('password').value) {
return "passwordMismatch";
}
}
}
});
and I'm dynamically setting optional value for email like
RegisterSchema._schema.email.optional = function() { return true };
this worked for me.
All d best
This is not the thing that I'm trying to do but I have learned a new trick : )
I want to change the schema key that I described above like this.
Books = new SimpleSchema(
{
bookName: {
type: String
}
}
);
Changing summary: with bookName:
Actually I want to define schema keys dynamically with respect to user information (userId, userName etc.).

Resources