@safient/core
Version:
JavaScript SDK to manage safes and interact with Safient protocol.
80 lines (79 loc) • 3.59 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getThreadId = exports.getCredentials = exports.loginUserWithChallenge = exports.solveChallenge = void 0;
const { Client, Where, ThreadID } = require('@textile/hub');
const io = require('socket.io-client');
const threadConfig_json_1 = require("./threadConfig.json");
const solveChallenge = (identity) => {
return new Promise((resolve, reject) => {
const socket = io(process.env.NEXT_PUBLIC_MIDDLEWARE_URL);
socket.on('connect', () => {
const publicKey = identity.public.toString();
// Send public key to server
socket.emit('authInit', JSON.stringify({
pubKey: publicKey,
type: 'token',
}));
socket.on('authMsg', (event) => __awaiter(void 0, void 0, void 0, function* () {
const data = JSON.parse(event);
switch (data.type) {
case 'error': {
reject(data.value);
break;
}
//solve the challenge
case 'challenge': {
const buf = Buffer.from(data.value);
const signed = yield identity.sign(buf);
socket.emit('challengeResp', signed);
break;
}
//get the token and store it
case 'token': {
resolve(data.value);
socket.disconnect();
break;
}
}
}));
});
});
};
exports.solveChallenge = solveChallenge;
const loginUserWithChallenge = function (id) {
return __awaiter(this, void 0, void 0, function* () {
if (!id) {
throw Error('No user ID found');
}
/** Use the identity to request a new API token when needed */
const credentials = yield (0, exports.solveChallenge)(id);
localStorage.setItem('payload', JSON.stringify(credentials));
const client = yield Client.withUserAuth(credentials.payload);
console.log('Verified on Textile API!!');
return client;
});
};
exports.loginUserWithChallenge = loginUserWithChallenge;
const getCredentials = function () {
return __awaiter(this, void 0, void 0, function* () {
const credentials = JSON.parse(localStorage.getItem('payload'));
const threadDB = credentials.threadDbId;
const client = Client.withUserAuth(credentials.payload);
const threadDb = Uint8Array.from(threadDB);
return { client, threadDb };
});
};
exports.getCredentials = getCredentials;
const getThreadId = () => __awaiter(void 0, void 0, void 0, function* () {
return threadConfig_json_1.threadId;
});
exports.getThreadId = getThreadId;