Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
94 lines (69 loc) · 2.87 KB
/
Copy pathindex.js
File metadata and controls
94 lines (69 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const { MongoClient, Binary } = require('mongodb');
const { aesEncryption, hmac } = require('crypsi');
const AES_256_KEY = 'abc$#128djdyAgbjau&YAnmcbagryt5x';
const MONGODB_URI = "mongodb://admin:admin@localhost:27017/codebasedb?retryWrites=true&w=majority";
async function insertData(name, email, creditCard) {
try {
const database = 'codebasedb';
const userCollections = 'users';
const options = {
keepAlive: true,
maxPoolSize: 50,
socketTimeoutMS: 10000,
connectTimeoutMS: 10000
};
const client = new MongoClient(MONGODB_URI, options);
await client.connect();
const encryptedEmail = aesEncryption.encryptWithAes256Cbc(AES_256_KEY, email).toString('hex');
const emailHashed = hmac.sha256(AES_256_KEY, email);
const creditCardEncrypted = aesEncryption.encryptWithAes256Cbc(AES_256_KEY, creditCard).toString('hex');
const creditCardHashed = hmac.sha256(AES_256_KEY, creditCard);
const db = client.db(database);
await db.collection(userCollections).insertOne({
name: name,
email: encryptedEmail,
emailHashed: emailHashed,
creditCard: creditCardEncrypted,
creditCardHashed: creditCardHashed,
createdAt: new Date(),
});
await client.close();
} catch(e) {
console.log('error connecting to database server', e);
}
}
async function findByEmail(email) {
try {
const database = 'codebasedb';
const userCollections = 'users';
const options = {
keepAlive: true,
maxPoolSize: 50,
socketTimeoutMS: 10000,
connectTimeoutMS: 10000
};
const client = new MongoClient(MONGODB_URI, options);
await client.connect();
// email should be hashed first, before being used in filters
const emailHashed = hmac.sha256(AES_256_KEY, email);
// filter By Hashed Email
const findOneFilter = {"emailHashed": emailHashed};
const db = client.db(database);
const userOne = await db.collection(userCollections).findOne(findOneFilter);
// set Email field with Decrypted Email
userOne.email = aesEncryption.decryptWithAes256Cbc(AES_256_KEY, userOne.email).toString();
// set CreaditCard field with Decrypted CreaditCard
userOne.creditCard = aesEncryption.decryptWithAes256Cbc(AES_256_KEY, userOne.creditCard).toString();
console.log(userOne);
await client.close();
} catch(e) {
console.log('error connecting to database server', e);
}
}
// test
// insertData('wuri', 'wuri@yahoo.com', '4649931847550758')
// .then(() => console.log('insert data succeed'))
// .catch(e => console.log(e));
findByEmail('andy@gmail.com')
.then(() => console.log('read data succeed'))
.catch(e => console.log(e));