-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
CloudBackup.js
51 lines (43 loc) · 1.79 KB
/
CloudBackup.js
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
import bcrypt from 'bcrypt';
import aes from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import axios from 'axios';
import { backupEndpoint } from '@/utils/defaults';
const ENDPOINT = backupEndpoint; // 'https://shipyard-sync-service.as93.net';
/* Stringify, encrypt and encode data for transmission */
const encryptData = (data, password) => {
const stringifiedData = JSON.stringify(data);
const encryptedData = aes.encrypt(stringifiedData, password);
return encryptedData.toString();
};
/* Decrypt, decode and parse received data */
const decryptData = (data, password) => aes.decrypt(data, password).toString(Utf8);
/* Returns a splice of the hash of the users password */
const makeSubHash = (pass) => bcrypt.hashSync(pass, 10).slice(0, 14);
/* Makes the backup */
export const backup = (data, password) => axios.post(ENDPOINT, {
userData: encryptData(data, password),
subHash: makeSubHash(password),
});
/* Updates and existing backup */
export const update = (data, password, backupId) => axios.put(ENDPOINT, {
backupId,
userData: encryptData(data, password),
subHash: makeSubHash(password),
});
const encodeGetParams = p => Object.entries(p).map(kv => kv.map(encodeURIComponent).join('=')).join('&');
/* Restores the backup */
export const restore = (backupId, password) => {
const params = encodeGetParams({ backupId, subHash: makeSubHash(password) });
const url = `${ENDPOINT}/?${params}`;
return new Promise((resolve, reject) => {
axios.get(url).then((response) => {
if (!response.data || response.data.errorMsg) {
reject(response.data.errorMsg || 'Error');
} else {
const decryptedData = decryptData(response.data.userData.userData, password);
try { resolve(JSON.parse(decryptedData)); } catch (e) { reject(e); }
}
});
});
};