Merge pull request #384 from esteemapp/bugfix/pin

Fixed login issue, changed pin code structure. Also fixed #331 fixed #332
This commit is contained in:
uğur erdal 2019-01-10 14:02:44 +03:00 committed by GitHub
commit a891529314
7 changed files with 390 additions and 283 deletions

View File

@ -134,7 +134,7 @@ class UpvoteView extends Component {
const _percent = `${(sliderValue * 100).toFixed(0)}%`; const _percent = `${(sliderValue * 100).toFixed(0)}%`;
const _amount = `$${amount}`; const _amount = `$${amount}`;
const _totalPayout = totalPayout ? totalPayout : '0.000'; const _totalPayout = totalPayout || '0.000';
return ( return (
<PopoverController> <PopoverController>

View File

@ -1,7 +1,13 @@
const STEEM_CONNECT = 'steemConnect'; const STEEM_CONNECT = 'steemConnect';
const MASTER_KEY = 'masterKey'; const MASTER_KEY = 'masterKey';
const ACTIVE_KEY = 'activeKey';
const MEMO_KEY = 'memoKey';
const POSTING_KEY = 'postingKey';
export default { export default {
STEEM_CONNECT, STEEM_CONNECT,
MASTER_KEY, MASTER_KEY,
ACTIVE_KEY,
MEMO_KEY,
POSTING_KEY,
}; };

View File

@ -1,4 +1,6 @@
import * as dsteem from 'dsteem'; import * as dsteem from 'dsteem';
import sha256 from 'crypto-js/sha256';
import { getUser } from './dsteem'; import { getUser } from './dsteem';
import { import {
setUserData, setUserData,
@ -9,20 +11,20 @@ import {
getUserData, getUserData,
setSCAccount, setSCAccount,
getSCAccount, getSCAccount,
setPinCode,
getPinCode,
} from '../../realm/realm'; } from '../../realm/realm';
import { encryptKey, decryptKey } from '../../utils/crypto'; import { encryptKey, decryptKey } from '../../utils/crypto';
import steemConnect from './steemConnectAPI'; import steemConnect from './steemConnectAPI';
import { getSCAccessToken } from '../esteem/esteem'; import { getSCAccessToken } from '../esteem/esteem';
// Constants
import AUTH_TYPE from '../../constants/authType';
export const login = async (username, password) => { export const login = async (username, password) => {
const resultKeys = {
active: null,
memo: null,
owner: null,
posting: null,
};
let loginFlag = false; let loginFlag = false;
let avatar = ''; let avatar = '';
let authType = '';
// Get user account data from STEEM Blockchain // Get user account data from STEEM Blockchain
const account = await getUser(username); const account = await getUser(username);
if (!account) { if (!account) {
@ -33,23 +35,23 @@ export const login = async (username, password) => {
new Error('You are already logged in, please try to add another account'), new Error('You are already logged in, please try to add another account'),
); );
} }
// Public keys of user // Public keys of user
const publicKeys = { const publicKeys = {
active: account.active.key_auths.map(x => x[0]), activeKey: account.active.key_auths.map(x => x[0])[0],
memo: account.memo_key, memoKey: account.memo_key,
owner: account.owner.key_auths.map(x => x[0]), ownerKey: account.owner.key_auths.map(x => x[0])[0],
posting: account.posting.key_auths.map(x => x[0]), postingKey: account.posting.key_auths.map(x => x[0])[0],
}; };
// Set private keys of user // // Set private keys of user
const privateKeys = getPrivateKeys(username, password); const privateKeys = getPrivateKeys(username, password);
// Check all keys // Check all keys
Object.keys(publicKeys).map((pubKey) => { Object.keys(publicKeys).map((pubKey) => {
if (publicKeys[pubKey] === privateKeys[pubKey].createPublic().toString()) { if (publicKeys[pubKey] === privateKeys[pubKey].createPublic().toString()) {
loginFlag = true; loginFlag = true;
resultKeys[pubKey] = publicKeys[pubKey]; if (privateKeys.isMasterKey) authType = AUTH_TYPE.MASTER_KEY;
else authType = pubKey;
} }
}); });
@ -66,7 +68,7 @@ export const login = async (username, password) => {
const userData = { const userData = {
username, username,
avatar, avatar,
authType: 'masterKey', authType,
masterKey: '', masterKey: '',
postingKey: '', postingKey: '',
activeKey: '', activeKey: '',
@ -76,6 +78,12 @@ export const login = async (username, password) => {
account.local = userData; account.local = userData;
const authData = {
isLoggedIn: true,
currentUsername: username,
};
await setAuthStatus(authData);
// Save user data to Realm DB // Save user data to Realm DB
await setUserData(userData); await setUserData(userData);
await updateCurrentUsername(account.name); await updateCurrentUsername(account.name);
@ -86,7 +94,6 @@ export const login = async (username, password) => {
export const loginWithSC2 = async (code) => { export const loginWithSC2 = async (code) => {
const scTokens = await getSCAccessToken(code); const scTokens = await getSCAccessToken(code);
await setSCAccount(scTokens);
await steemConnect.setAccessToken(scTokens.access_token); await steemConnect.setAccessToken(scTokens.access_token);
const account = await steemConnect.me(); const account = await steemConnect.me();
let avatar = ''; let avatar = '';
@ -103,7 +110,7 @@ export const loginWithSC2 = async (code) => {
const userData = { const userData = {
username: account.account.name, username: account.account.name,
avatar, avatar,
authType: 'steemConnect', authType: AUTH_TYPE.STEEM_CONNECT,
masterKey: '', masterKey: '',
postingKey: '', postingKey: '',
activeKey: '', activeKey: '',
@ -116,9 +123,14 @@ export const loginWithSC2 = async (code) => {
} }
setUserData(userData) setUserData(userData)
.then(() => { .then(async () => {
account.account.username = account.account.name;
updateCurrentUsername(account.account.name); updateCurrentUsername(account.account.name);
const authData = {
isLoggedIn: true,
currentUsername: account.account.name,
};
await setAuthStatus(authData);
await setSCAccount(scTokens);
resolve({ ...account.account, accessToken: scTokens.access_token }); resolve({ ...account.account, accessToken: scTokens.access_token });
}) })
.catch((error) => { .catch((error) => {
@ -128,133 +140,85 @@ export const loginWithSC2 = async (code) => {
}; };
export const setUserDataWithPinCode = async (data) => { export const setUserDataWithPinCode = async (data) => {
const result = getUserDataWithUsername(data.username); try {
const userData = result[0]; const result = getUserDataWithUsername(data.username);
const userData = result[0];
const privateKeys = getPrivateKeys(userData.username, data.password); const updatedUserData = getUpdatedUserData(userData, data);
const updatedUserData = { await setPinCode(data.pinCode);
username: userData.username, await updateUserData(updatedUserData);
authType: userData.authType,
accessToken:
userData.authType === 'steemConnect' ? encryptKey(data.accessToken, data.pinCode) : '',
masterKey: userData.authType === 'masterKey' ? encryptKey(data.password, data.pinCode) : '',
postingKey: encryptKey(privateKeys.posting.toString(), data.pinCode),
activeKey: encryptKey(privateKeys.active.toString(), data.pinCode),
memoKey: encryptKey(privateKeys.memo.toString(), data.pinCode),
};
const response = await updateUserData(updatedUserData); return updatedUserData;
const authData = { } catch (error) {
isLoggedIn: true, return Promise.reject(new Error('Unknown error, please contact to eSteem.'));
currentUsername: userData.username, }
};
await setAuthStatus(authData);
return response;
}; };
export const updatePinCode = async (data) => { export const updatePinCode = async (data) => {
let password = null; try {
let accessToken = null; await setPinCode(data.pinCode);
const users = await getUserData(); const users = await getUserData();
if (users.length > 0) { if (users && users.length > 0) {
users.forEach(async (userData) => { users.forEach(async (userData) => {
if (userData.authType === 'masterKey') { if (userData.authType === AUTH_TYPE.MASTER_KEY) {
password = decryptKey(userData.masterKey, data.oldPinCode); data.password = decryptKey(userData.masterKey, data.oldPinCode);
} else if (userData.authType === 'steemConnect') { } else if (userData.authType === AUTH_TYPE.STEEM_CONNECT) {
accessToken = decryptKey(userData.accessToken, data.oldPinCode); data.accessToken = decryptKey(userData.accessToken, data.oldPinCode);
} }
const privateKeys = getPrivateKeys(userData.username, password); const updatedUserData = getUpdatedUserData(userData, data);
const updatedUserData = { await updateUserData(updatedUserData);
username: userData.username, });
authType: userData.authType, return true;
accessToken: }
userData.authType === 'steemConnect' ? encryptKey(accessToken, data.pinCode) : '', return false;
masterKey: userData.authType === 'masterKey' ? encryptKey(password, data.pinCode) : '', } catch (error) {
postingKey: encryptKey(privateKeys.posting.toString(), data.pinCode), return Promise.reject(new Error('Unknown error, please contact to eSteem.'));
activeKey: encryptKey(privateKeys.active.toString(), data.pinCode),
memoKey: encryptKey(privateKeys.memo.toString(), data.pinCode),
};
const response = await updateUserData(updatedUserData);
const authData = {
isLoggedIn: true,
currentUsername: userData.username,
};
await setAuthStatus(authData);
return response;
});
} }
}; };
export const verifyPinCode = async (data) => { export const verifyPinCode = async (data) => {
const pinHash = await getPinCode();
const result = getUserDataWithUsername(data.username); const result = getUserDataWithUsername(data.username);
const userData = result[0]; const userData = result[0];
let account = null;
let loginFlag = false;
if (result.length > 0) {
if (userData.authType === 'steemConnect') {
let accessToken;
try {
accessToken = decryptKey(userData.accessToken, data.pinCode);
} catch (error) {
return Promise.reject(new Error('Invalid pin code, please check and try again'));
}
const scAccount = await getSCAccount(userData.username); // This is migration for new pin structure, it will remove v2.2
const now = new Date(); if (!pinHash) {
const expireDate = new Date(scAccount.expireDate); try {
if (now >= expireDate) { if (userData.authType === AUTH_TYPE.STEEM_CONNECT) {
const newSCAccountData = await getSCAccessToken(scAccount.refreshToken); decryptKey(userData.accessToken, data.pinCode);
await setSCAccount(newSCAccountData); } else {
accessToken = newSCAccountData.access_token; decryptKey(userData.masterKey, data.pinCode);
await updateUserData(
{ ...userData, accessToken: encryptKey(accessToken, data.pinCode) },
);
} }
await steemConnect.setAccessToken(accessToken); await setPinCode(data.pinCode);
account = await steemConnect.me(); } catch (error) {
if (account) { return Promise.reject(new Error('Invalid pin code, please check and try again'));
loginFlag = true;
}
} else if (userData.authType === 'masterKey') {
const password = decryptKey(userData.masterKey, data.pinCode);
account = await getUser(data.username);
// Public keys of user
const publicKeys = {
active: account.active.key_auths.map(x => x[0]),
memo: account.memo_key,
owner: account.owner.key_auths.map(x => x[0]),
posting: account.posting.key_auths.map(x => x[0]),
};
// Set private keys of user
const privateKeys = getPrivateKeys(data.username, password);
// Check all keys
Object.keys(publicKeys).map((pubKey) => {
if (publicKeys[pubKey] === privateKeys[pubKey].createPublic().toString()) {
loginFlag = true;
}
});
} }
} }
if (loginFlag) {
const authData = { if (sha256(data.pinCode).toString() !== pinHash) {
isLoggedIn: true, return Promise.reject(new Error('Invalid pin code, please check and try again'));
currentUsername: data.username, }
};
const response = { if (result.length > 0) {
accessToken: decryptKey(userData.accessToken, data.pinCode), if (userData.authType === AUTH_TYPE.STEEM_CONNECT) {
postingKey: decryptKey(userData.postingKey, data.pinCode), await refreshSCToken(userData, data.pinCode);
masterKey: decryptKey(userData.masterKey, data.pinCode), }
activeKey: decryptKey(userData.activeKey, data.pinCode), }
memoKey: decryptKey(userData.memoKey, data.pinCode), return true;
}; };
await setAuthStatus(authData);
return response; export const refreshSCToken = async (userData, pinCode) => {
const scAccount = await getSCAccount(userData.username);
const now = new Date();
const expireDate = new Date(scAccount.expireDate);
if (now >= expireDate) {
const newSCAccountData = await getSCAccessToken(scAccount.refreshToken);
await setSCAccount(newSCAccountData);
const accessToken = newSCAccountData.access_token;
await updateUserData({ ...userData, accessToken: encryptKey(accessToken, pinCode) });
} }
return Promise.reject(new Error('Invalid pin code, please check and try again'));
}; };
export const switchAccount = username => new Promise((resolve, reject) => { export const switchAccount = username => new Promise((resolve, reject) => {
@ -273,12 +237,53 @@ export const switchAccount = username => new Promise((resolve, reject) => {
}); });
}); });
const getPrivateKeys = (username, password) => ({ const getPrivateKeys = (username, password) => {
active: dsteem.PrivateKey.fromLogin(username, password, 'active'), try {
memo: dsteem.PrivateKey.fromLogin(username, password, 'memo'), return {
owner: dsteem.PrivateKey.fromLogin(username, password, 'owner'), activeKey: dsteem.PrivateKey.from(password),
posting: dsteem.PrivateKey.fromLogin(username, password, 'posting'), memoKey: dsteem.PrivateKey.from(password),
}); ownerKey: dsteem.PrivateKey.from(password),
postingKey: dsteem.PrivateKey.from(password),
isMasterKey: false,
};
} catch (e) {
return {
activeKey: dsteem.PrivateKey.fromLogin(username, password, 'active'),
memoKey: dsteem.PrivateKey.fromLogin(username, password, 'memo'),
ownerKey: dsteem.PrivateKey.fromLogin(username, password, 'owner'),
postingKey: dsteem.PrivateKey.fromLogin(username, password, 'posting'),
isMasterKey: true,
};
}
};
export const getUpdatedUserData = (userData, data) => {
const privateKeys = getPrivateKeys(userData.username, data.password);
return {
username: userData.username,
authType: userData.authType,
accessToken:
userData.authType === AUTH_TYPE.STEEM_CONNECT
? encryptKey(data.accessToken, data.pinCode)
: '',
masterKey:
userData.authType === AUTH_TYPE.MASTER_KEY
? encryptKey(data.password, data.pinCode)
: '',
postingKey:
userData.authType === AUTH_TYPE.MASTER_KEY || userData.authType === AUTH_TYPE.POSTING_KEY
? encryptKey(privateKeys.postingKey.toString(), data.pinCode)
: '',
activeKey:
userData.authType === AUTH_TYPE.MASTER_KEY || userData.authType === AUTH_TYPE.ACTIVE_KEY
? encryptKey(privateKeys.activeKey.toString(), data.pinCode)
: '',
memoKey:
userData.authType === AUTH_TYPE.MASTER_KEY || userData.authType === AUTH_TYPE.MEMO_KEY
? encryptKey(privateKeys.memoKey.toString(), data.pinCode)
: '',
};
};
const isLoggedInUser = (username) => { const isLoggedInUser = (username) => {
const result = getUserDataWithUsername(username); const result = getUserDataWithUsername(username);

View File

@ -2,7 +2,7 @@ import { Client, PrivateKey } from 'dsteem';
import steemConnect from 'steemconnect'; import steemConnect from 'steemconnect';
import Config from 'react-native-config'; import Config from 'react-native-config';
import { getServer, getPinCode } from '../../realm/realm'; import { getServer } from '../../realm/realm';
import { getUnreadActivityCount } from '../esteem/esteem'; import { getUnreadActivityCount } from '../esteem/esteem';
// Utils // Utils
@ -198,9 +198,18 @@ export const getIsMuted = async (username, targetUsername) => {
export const ignoreUser = async (currentAccount, pin, data) => { export const ignoreUser = async (currentAccount, pin, data) => {
const digitPinCode = getDigitPinCode(pin); const digitPinCode = getDigitPinCode(pin);
const key = getAnyPrivateKey(currentAccount.local, digitPinCode);
if (currentAccount.local.authType === AUTH_TYPE.MASTER_KEY) { if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const key = decryptKey(currentAccount.local.postingKey, digitPinCode); const token = decryptKey(currentAccount.local.accessToken, digitPinCode);
const api = steemConnect.Initialize({
accessToken: token,
});
return api.ignore(data.follower, data.following);
}
if (key) {
const privateKey = PrivateKey.fromString(key); const privateKey = PrivateKey.fromString(key);
const json = { const json = {
@ -229,14 +238,7 @@ export const ignoreUser = async (currentAccount, pin, data) => {
}); });
} }
if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) { return Promise.reject(new Error('You dont have permission!'));
const token = decryptKey(currentAccount.local.accessToken, digitPinCode);
const api = steemConnect.Initialize({
accessToken: token,
});
return api.ignore(data.follower, data.following);
}
}; };
/** /**
@ -370,30 +372,7 @@ export const getPostWithComments = async (user, permlink) => {
*/ */
export const vote = async (currentAccount, pin, author, permlink, weight) => { export const vote = async (currentAccount, pin, author, permlink, weight) => {
const digitPinCode = getDigitPinCode(pin); const digitPinCode = getDigitPinCode(pin);
const key = getAnyPrivateKey(currentAccount.local, digitPinCode);
if (currentAccount.local.authType === AUTH_TYPE.MASTER_KEY) {
const key = decryptKey(currentAccount.local.postingKey, digitPinCode);
const privateKey = PrivateKey.fromString(key);
const voter = currentAccount.name;
const args = {
voter,
author,
permlink,
weight,
};
return new Promise((resolve, reject) => {
client.broadcast
.vote(args, privateKey)
.then((result) => {
resolve(result);
})
.catch((err) => {
reject(err);
});
});
}
if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) { if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const token = decryptKey(currentAccount.local.accessToken, digitPinCode); const token = decryptKey(currentAccount.local.accessToken, digitPinCode);
@ -414,6 +393,31 @@ export const vote = async (currentAccount, pin, author, permlink, weight) => {
}); });
}); });
} }
if (key) {
const privateKey = PrivateKey.fromString(key);
const voter = currentAccount.name;
const args = {
voter,
author,
permlink,
weight,
};
return new Promise((resolve, reject) => {
client.broadcast
.vote(args, privateKey)
.then((result) => {
resolve(result);
})
.catch((err) => {
reject(err);
});
});
}
return Promise.reject(new Error('You dont have permission!'));
}; };
/** /**
@ -455,9 +459,18 @@ export const transferToken = (data, activeKey) => {
export const followUser = async (currentAccount, pin, data) => { export const followUser = async (currentAccount, pin, data) => {
const digitPinCode = getDigitPinCode(pin); const digitPinCode = getDigitPinCode(pin);
const key = getAnyPrivateKey(currentAccount.local, digitPinCode);
if (currentAccount.local.authType === AUTH_TYPE.MASTER_KEY) { if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const key = decryptKey(currentAccount.local.postingKey, digitPinCode); const token = decryptKey(currentAccount.local.accessToken, digitPinCode);
const api = steemConnect.Initialize({
accessToken: token,
});
return api.follow(data.follower, data.following);
}
if (key) {
const privateKey = PrivateKey.fromString(key); const privateKey = PrivateKey.fromString(key);
const json = { const json = {
id: 'follow', id: 'follow',
@ -484,21 +497,24 @@ export const followUser = async (currentAccount, pin, data) => {
}); });
}); });
} }
return Promise.reject(new Error('You dont have permission!'));
};
export const unfollowUser = async (currentAccount, pin, data) => {
const digitPinCode = getDigitPinCode(pin);
const key = getAnyPrivateKey(currentAccount.local, digitPinCode);
if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) { if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const token = decryptKey(currentAccount.local.accessToken, digitPinCode); const token = decryptKey(currentAccount.local.accessToken, digitPinCode);
const api = steemConnect.Initialize({ const api = steemConnect.Initialize({
accessToken: token, accessToken: token,
}); });
return api.follow(data.follower, data.following); return api.unfollow(data.follower, data.following);
} }
};
export const unfollowUser = async (currentAccount, pin, data) => { if (key) {
const digitPinCode = getDigitPinCode(pin);
if (currentAccount.local.authType === AUTH_TYPE.MASTER_KEY) {
const key = decryptKey(currentAccount.local.postingKey, digitPinCode);
const privateKey = PrivateKey.fromString(key); const privateKey = PrivateKey.fromString(key);
const json = { const json = {
@ -526,14 +542,8 @@ export const unfollowUser = async (currentAccount, pin, data) => {
}); });
}); });
} }
if (currentAccount.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const token = decryptKey(currentAccount.local.accessToken, digitPinCode);
const api = steemConnect.Initialize({
accessToken: token,
});
return api.unfollow(data.follower, data.following); return Promise.reject(new Error('You dont have permission!'));
}
}; };
export const delegate = (data, activeKey) => { export const delegate = (data, activeKey) => {
@ -642,55 +652,7 @@ export const postContent = async (
) => { ) => {
const { name: author } = account; const { name: author } = account;
const digitPinCode = getDigitPinCode(pin); const digitPinCode = getDigitPinCode(pin);
const key = getAnyPrivateKey(account.local, digitPinCode);
if (account.local.authType === AUTH_TYPE.MASTER_KEY) {
const opArray = [
[
'comment',
{
parent_author: parentAuthor,
parent_permlink: parentPermlink,
author,
permlink,
title,
body,
json_metadata: JSON.stringify(jsonMetadata),
},
],
];
if (options) {
const e = ['comment_options', options];
opArray.push(e);
}
if (voteWeight) {
const e = [
'vote',
{
voter: author,
author,
permlink,
weight: voteWeight,
},
];
opArray.push(e);
}
const key = decryptKey(account.local.postingKey, digitPinCode);
const privateKey = PrivateKey.fromString(key);
return new Promise((resolve, reject) => {
client.broadcast
.sendOperations(opArray, privateKey)
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
});
}
if (account.local.authType === AUTH_TYPE.STEEM_CONNECT) { if (account.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const token = decryptKey(account.local.accessToken, digitPinCode); const token = decryptKey(account.local.accessToken, digitPinCode);
@ -730,14 +692,75 @@ export const postContent = async (
return api.broadcast(opArray); return api.broadcast(opArray);
} }
if (key) {
const opArray = [
[
'comment',
{
parent_author: parentAuthor,
parent_permlink: parentPermlink,
author,
permlink,
title,
body,
json_metadata: JSON.stringify(jsonMetadata),
},
],
];
if (options) {
const e = ['comment_options', options];
opArray.push(e);
}
if (voteWeight) {
const e = [
'vote',
{
voter: author,
author,
permlink,
weight: voteWeight,
},
];
opArray.push(e);
}
const privateKey = PrivateKey.fromString(key);
return new Promise((resolve, reject) => {
client.broadcast
.sendOperations(opArray, privateKey)
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
});
}
return Promise.reject(new Error('You dont have permission!'));
}; };
// Re-blog // Re-blog
export const reblog = async (account, pinCode, author, permlink) => { export const reblog = async (account, pinCode, author, permlink) => {
const pin = getDigitPinCode(pinCode); const pin = getDigitPinCode(pinCode);
const key = getAnyPrivateKey(account.local, pin);
if (account.local.authType === AUTH_TYPE.MASTER_KEY) { if (account.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const key = decryptKey(account.local.postingKey, pin); const token = decryptKey(account.local.accessToken, pin);
const api = steemConnect.Initialize({
accessToken: token,
});
const follower = account.name;
return api.reblog(follower, author, permlink);
}
if (key) {
const privateKey = PrivateKey.fromString(key); const privateKey = PrivateKey.fromString(key);
const follower = account.name; const follower = account.name;
@ -758,29 +781,23 @@ export const reblog = async (account, pinCode, author, permlink) => {
return client.broadcast.json(json, privateKey); return client.broadcast.json(json, privateKey);
} }
return Promise.reject(new Error('You dont have permission!'));
};
export const claimRewardBalance = (account, pinCode, rewardSteem, rewardSbd, rewardVests) => {
const pin = getDigitPinCode(pinCode);
const key = getAnyPrivateKey(account.local, pin);
if (account.local.authType === AUTH_TYPE.STEEM_CONNECT) { if (account.local.authType === AUTH_TYPE.STEEM_CONNECT) {
const token = decryptKey(account.local.accessToken, pin); const token = decryptKey(account.local.accessToken, pin);
const api = steemConnect.Initialize({ const api = steemConnect.Initialize({
accessToken: token, accessToken: token,
}); });
const follower = account.name; return api.claimRewardBalance(account.name, rewardSteem, rewardSbd, rewardVests);
return api.reblog(follower, author, permlink);
} }
};
export const claimRewardBalance = ( if (key) {
account,
pinCode,
rewardSteem,
rewardSbd,
rewardVests,
) => {
const pin = getDigitPinCode(pinCode);
if (account.local.authType === AUTH_TYPE.MASTER_KEY) {
const key = decryptKey(account.local.postingKey, pin);
const privateKey = PrivateKey.fromString(key); const privateKey = PrivateKey.fromString(key);
const opArray = [ const opArray = [
@ -798,17 +815,30 @@ export const claimRewardBalance = (
return client.broadcast.sendOperations(opArray, privateKey); return client.broadcast.sendOperations(opArray, privateKey);
} }
if (account.local.authType === AUTH_TYPE.STEEM_CONNECT) { return Promise.reject(new Error('You dont have permission!'));
const token = decryptKey(account.local.accessToken, pin); };
const api = steemConnect.Initialize({
accessToken: token, const getAnyPrivateKey = (local, pin) => {
}); const { postingKey, activeKey } = local;
return api.claimRewardBalance( if (postingKey) {
account.name, return decryptKey(local.postingKey, pin);
rewardSteem, }
rewardSbd,
rewardVests, if (activeKey) {
); return decryptKey(local.postingKey, pin);
} }
return false;
// ['postingKey', 'activeKey'].forEach((key) => {
// console.log('key :', key);
// console.log('pin :', pin);
// console.log('local[key] :', local[key]);
// if (key) {
// const privateKey = decryptKey(local[key], pin);
// console.log('privateKey :', privateKey);
// return true;
// }
// });
}; };

View File

@ -1,4 +1,5 @@
import Realm from 'realm'; import Realm from 'realm';
import sha256 from 'crypto-js/sha256';
// CONSTANTS // CONSTANTS
const USER_SCHEMA = 'user'; const USER_SCHEMA = 'user';
@ -294,9 +295,23 @@ export const updateCurrentUsername = username => new Promise((resolve, reject) =
export const setPinCode = pinCode => new Promise((resolve, reject) => { export const setPinCode = pinCode => new Promise((resolve, reject) => {
try { try {
const auth = realm.objects(AUTH_SCHEMA); const auth = realm.objects(AUTH_SCHEMA);
const pinHash = sha256(pinCode);
realm.write(() => { realm.write(() => {
auth[0].pinCode = pinCode; auth[0].pinCode = pinHash.toString();
resolve(auth[0]);
});
} catch (error) {
reject(error);
}
});
export const removePinCode = () => new Promise((resolve, reject) => {
try {
const auth = realm.objects(AUTH_SCHEMA);
realm.write(() => {
auth[0].pinCode = '';
resolve(auth[0]); resolve(auth[0]);
}); });
} catch (error) { } catch (error) {
@ -555,3 +570,20 @@ export const getSCAccount = username => new Promise((resolve, reject) => {
reject(error); reject(error);
} }
}); });
export const removeSCAccount = username => new Promise((resolve, reject) => {
try {
const scAccount = realm.objects(SC_ACCOUNTS).filtered('username = $0', username);
if (Array.from(scAccount).length > 0) {
realm.write(() => {
realm.delete(scAccount);
resolve();
});
} else {
reject(new Error('Could not remove selected user'));
}
} catch (error) {
reject(error);
}
});

View File

@ -10,6 +10,7 @@ import { NavigationActions } from 'react-navigation';
import en from 'react-intl/locale-data/en'; import en from 'react-intl/locale-data/en';
import tr from 'react-intl/locale-data/tr'; import tr from 'react-intl/locale-data/tr';
import ru from 'react-intl/locale-data/ru'; import ru from 'react-intl/locale-data/ru';
import AUTH_TYPE from '../../../constants/authType';
// Services // Services
import { import {
@ -21,6 +22,10 @@ import {
removeUserData, removeUserData,
setPushTokenSaved, setPushTokenSaved,
getUserDataWithUsername, getUserDataWithUsername,
removePinCode,
setAuthStatus,
removeSCAccount,
setExistUser,
} from '../../../realm/realm'; } from '../../../realm/realm';
import { getUser } from '../../../providers/steem/dsteem'; import { getUser } from '../../../providers/steem/dsteem';
import { setPushToken } from '../../../providers/esteem/esteem'; import { setPushToken } from '../../../providers/esteem/esteem';
@ -93,7 +98,7 @@ class ApplicationContainer extends Component {
_getUserData = async () => { _getUserData = async () => {
const { dispatch, pinCode } = this.props; const { dispatch, pinCode } = this.props;
let realmData; let realmData = [];
let currentUsername; let currentUsername;
await getAuthStatus().then((res) => { await getAuthStatus().then((res) => {
@ -102,28 +107,52 @@ class ApplicationContainer extends Component {
getUserData().then(async (userData) => { getUserData().then(async (userData) => {
if (userData.length > 0) { if (userData.length > 0) {
realmData = userData; realmData = userData;
userData.forEach((accountData, index) => {
userData.forEach((accountData) => { if (
dispatch(addOtherAccount({ username: accountData.username })); !accountData.accessToken
&& !accountData.masterKey
&& !accountData.postingKey
&& !accountData.activeKey
&& !accountData.memoKey
) {
realmData.splice(index, 1);
if (realmData.length === 0) {
dispatch(login(false));
dispatch(logoutDone());
removePinCode();
setAuthStatus({ isLoggedIn: false });
setExistUser(false);
if (accountData.authType === AUTH_TYPE.STEEM_CONNECT) {
removeSCAccount(accountData.username);
}
}
removeUserData(accountData.username);
} else {
dispatch(addOtherAccount({ username: accountData.username }));
}
}); });
} }
}); });
} }
}); });
if (realmData) { if (realmData.length > 0) {
await getUser(currentUsername) const realmObject = realmData.filter(data => data.username === currentUsername);
if (realmObject.length === 0) {
realmObject[0] = realmData[realmData.length - 1];
await switchAccount(realmObject[0].username);
}
await getUser(realmObject[0].username)
.then(async (accountData) => { .then(async (accountData) => {
dispatch(login(true)); dispatch(login(true));
const isExistUser = await getExistUser(); const isExistUser = await getExistUser();
const realmObject = realmData.filter(data => data.username === currentUsername);
[accountData.local] = realmObject; [accountData.local] = realmObject;
dispatch(updateCurrentAccount(accountData)); dispatch(updateCurrentAccount(accountData));
// If in dev mode pin code does not show // If in dev mode pin code does not show
// eslint-disable-next-line
if (!isExistUser || !pinCode) { if (!isExistUser || !pinCode) {
dispatch(openPinCodeModal()); dispatch(openPinCodeModal());
} }
@ -190,12 +219,14 @@ class ApplicationContainer extends Component {
}; };
_logout = () => { _logout = () => {
const { otherAccounts, currentAccountUsername, dispatch } = this.props; const {
otherAccounts, currentAccount, dispatch,
} = this.props;
removeUserData(currentAccountUsername) removeUserData(currentAccount.name)
.then(() => { .then(() => {
const _otherAccounts = otherAccounts.filter( const _otherAccounts = otherAccounts.filter(
user => user.username !== currentAccountUsername, user => user.username !== currentAccount.name,
); );
if (_otherAccounts.length > 0) { if (_otherAccounts.length > 0) {
@ -205,9 +236,15 @@ class ApplicationContainer extends Component {
} else { } else {
dispatch(updateCurrentAccount({})); dispatch(updateCurrentAccount({}));
dispatch(login(false)); dispatch(login(false));
removePinCode();
setAuthStatus({ isLoggedIn: false });
setExistUser(false);
if (currentAccount.local === AUTH_TYPE.STEEM_CONNECT) {
removeSCAccount(currentAccount.name);
}
} }
dispatch(removeOtherAccount(currentAccountUsername)); dispatch(removeOtherAccount(currentAccount.name));
dispatch(logoutDone()); dispatch(logoutDone());
}) })
.catch(() => {}); .catch(() => {});
@ -252,7 +289,7 @@ const mapStateToProps = state => ({
// Account // Account
unreadActivityCount: state.account.currentAccount.unread_activity_count, unreadActivityCount: state.account.currentAccount.unread_activity_count,
currentAccountUsername: state.account.currentAccount.name, currentAccount: state.account.currentAccount,
otherAccounts: state.account.otherAccounts, otherAccounts: state.account.otherAccounts,
pinCode: state.account.pin, pinCode: state.account.pin,
}); });

View File

@ -157,7 +157,6 @@ class PinCodeContainer extends Component {
accessToken, accessToken,
navigateTo, navigateTo,
navigation, navigation,
setWrappedComponentState,
intl, intl,
} = this.props; } = this.props;
@ -169,10 +168,8 @@ class PinCodeContainer extends Component {
accessToken, accessToken,
}; };
verifyPinCode(pinData) verifyPinCode(pinData)
.then((res) => { .then(() => {
setWrappedComponentState(res);
this._savePinCode(pin); this._savePinCode(pin);
const realmData = getUserDataWithUsername(currentAccount.name); const realmData = getUserDataWithUsername(currentAccount.name);
const _currentAccount = currentAccount; const _currentAccount = currentAccount;
_currentAccount.username = _currentAccount.name; _currentAccount.username = _currentAccount.name;