Working on refresh token feature

This commit is contained in:
Mustafa Buyukcelebi 2019-01-01 20:48:49 +03:00
parent cdb67bc627
commit 0e468ad6ff
4 changed files with 80 additions and 22 deletions

View File

@ -195,3 +195,9 @@ export const uploadImage = (file) => {
// }); // });
export const getNodes = () => serverList.get().then(resp => resp.data.nodes); export const getNodes = () => serverList.get().then(resp => resp.data.nodes);
export const getSCAccessToken = code => api
.post('/api/sc-token-refresh', {
code,
})
.then(resp => resp.data);

View File

@ -7,9 +7,11 @@ import {
updateUserData, updateUserData,
updateCurrentUsername, updateCurrentUsername,
getUserData, getUserData,
setSCAccount,
} 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';
export const login = async (username, password) => { export const login = async (username, password) => {
const resultKeys = { const resultKeys = {
@ -26,7 +28,9 @@ export const login = async (username, password) => {
return Promise.reject(new Error('Invalid pin code, please check and try again')); return Promise.reject(new Error('Invalid pin code, please check and try again'));
} }
if (isLoggedInUser(username)) { if (isLoggedInUser(username)) {
return Promise.reject(new Error('You are already logged in, please try to add another account')); return Promise.reject(
new Error('You are already logged in, please try to add another account'),
);
} }
// Public keys of user // Public keys of user
@ -74,13 +78,15 @@ export const login = async (username, password) => {
// 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);
return ({ ...account, password }); return { ...account, password };
} }
return Promise.reject(new Error('Invalid pin code, please check and try again')); return Promise.reject(new Error('Invalid pin code, please check and try again'));
}; };
export const loginWithSC2 = async (accessToken) => { export const loginWithSC2 = async (code) => {
await steemConnect.setAccessToken(accessToken); const scTokens = await getSCAccessToken(code);
await setSCAccount(scTokens);
await steemConnect.setAccessToken(scTokens.access_token);
const account = await steemConnect.me(); const account = await steemConnect.me();
let avatar = ''; let avatar = '';
@ -129,7 +135,8 @@ export const setUserDataWithPinCode = async (data) => {
const updatedUserData = { const updatedUserData = {
username: userData.username, username: userData.username,
authType: userData.authType, authType: userData.authType,
accessToken: userData.authType === 'steemConnect' ? encryptKey(data.accessToken, data.pinCode) : '', accessToken:
userData.authType === 'steemConnect' ? encryptKey(data.accessToken, data.pinCode) : '',
masterKey: userData.authType === 'masterKey' ? encryptKey(data.password, data.pinCode) : '', masterKey: userData.authType === 'masterKey' ? encryptKey(data.password, data.pinCode) : '',
postingKey: encryptKey(privateKeys.posting.toString(), data.pinCode), postingKey: encryptKey(privateKeys.posting.toString(), data.pinCode),
activeKey: encryptKey(privateKeys.active.toString(), data.pinCode), activeKey: encryptKey(privateKeys.active.toString(), data.pinCode),
@ -143,11 +150,11 @@ export const setUserDataWithPinCode = async (data) => {
}; };
await setAuthStatus(authData); await setAuthStatus(authData);
return (response); return response;
}; };
export const updatePinCode = async (data) => { export const updatePinCode = async (data) => {
let password = null; let password = null;
let accessToken = null; let accessToken = null;
const users = await getUserData(); const users = await getUserData();
if (users.length > 0) { if (users.length > 0) {
@ -161,7 +168,8 @@ export const updatePinCode = async (data) => {
const updatedUserData = { const updatedUserData = {
username: userData.username, username: userData.username,
authType: userData.authType, authType: userData.authType,
accessToken: userData.authType === 'steemConnect' ? encryptKey(accessToken, data.pinCode) : '', accessToken:
userData.authType === 'steemConnect' ? encryptKey(accessToken, data.pinCode) : '',
masterKey: userData.authType === 'masterKey' ? encryptKey(password, data.pinCode) : '', masterKey: userData.authType === 'masterKey' ? encryptKey(password, data.pinCode) : '',
postingKey: encryptKey(privateKeys.posting.toString(), data.pinCode), postingKey: encryptKey(privateKeys.posting.toString(), data.pinCode),
activeKey: encryptKey(privateKeys.active.toString(), data.pinCode), activeKey: encryptKey(privateKeys.active.toString(), data.pinCode),
@ -231,7 +239,7 @@ export const verifyPinCode = async (data) => {
memoKey: decryptKey(userData.memoKey, data.pinCode), memoKey: decryptKey(userData.memoKey, data.pinCode),
}; };
await setAuthStatus(authData); await setAuthStatus(authData);
return (response); return response;
} }
return Promise.reject(new Error('Invalid pin code, please check and try again')); return Promise.reject(new Error('Invalid pin code, please check and try again'));
}; };
@ -239,12 +247,15 @@ export const verifyPinCode = async (data) => {
export const switchAccount = username => new Promise((resolve, reject) => { export const switchAccount = username => new Promise((resolve, reject) => {
getUser(username) getUser(username)
.then((account) => { .then((account) => {
updateCurrentUsername(username).then(() => { updateCurrentUsername(username)
resolve(account); .then(() => {
}).catch(() => { resolve(account);
reject(new Error('Unknown error, please contact to eSteem.')); })
}); .catch(() => {
}).catch(() => { reject(new Error('Unknown error, please contact to eSteem.'));
});
})
.catch(() => {
reject(new Error('Unknown error, please contact to eSteem.')); reject(new Error('Unknown error, please contact to eSteem.'));
}); });
}); });

View File

@ -2,6 +2,7 @@ import Realm from 'realm';
// CONSTANTS // CONSTANTS
const USER_SCHEMA = 'user'; const USER_SCHEMA = 'user';
const SC_ACCOUNTS = 'sc_accounts';
const AUTH_SCHEMA = 'auth'; const AUTH_SCHEMA = 'auth';
const DRAFT_SCHEMA = 'draft'; const DRAFT_SCHEMA = 'draft';
const SETTINGS_SCHEMA = 'settings'; const SETTINGS_SCHEMA = 'settings';
@ -21,6 +22,16 @@ const userSchema = {
}, },
}; };
const scAccounts = {
name: SC_ACCOUNTS,
properties: {
username: { type: 'string', default: null },
accessToken: { type: 'string', default: null },
refreshToken: { type: 'string', default: null },
expireDate: { type: 'string', default: null },
},
};
const draftSchema = { const draftSchema = {
name: DRAFT_SCHEMA, name: DRAFT_SCHEMA,
properties: { properties: {
@ -62,7 +73,7 @@ const authSchema = {
const realm = new Realm({ const realm = new Realm({
path: 'esteem.realm', path: 'esteem.realm',
schema: [userSchema, authSchema, draftSchema, settingsSchema, applicationSchema], schema: [userSchema, authSchema, draftSchema, settingsSchema, applicationSchema, scAccounts],
}); });
const settings = realm.objects(SETTINGS_SCHEMA); const settings = realm.objects(SETTINGS_SCHEMA);
@ -155,7 +166,6 @@ export const removeUserData = username => new Promise((resolve, reject) => {
realm.delete(account); realm.delete(account);
resolve(); resolve();
}); });
} else { } else {
reject('Could not remove selected user'); reject('Could not remove selected user');
} }
@ -491,3 +501,33 @@ export const setExistUser = existUser => new Promise((resolve, reject) => {
reject(error); reject(error);
} }
}); });
export const setSCAccount = data => new Promise((resolve, reject) => {
try {
const scAccount = realm.objects(SC_ACCOUNTS).filtered('username = $0', data.username);
const date = new Date();
const test = new Date(data.expires_in);
console.log('date :', date);
console.log('test :', test);
// TODO: expire date colculate
realm.write(() => {
if (Array.from(scAccount).length > 0) {
scAccount[0].accessToken = data.accessToken;
scAccount[0].refreshToken = data.refreshToken;
scAccount[0].expireDate = data.expireDate;
resolve();
} else {
const account = {
username: data.username,
accessToken: data.access_token,
refreshToken: data.refresh_token,
expireDate: data.expires_in,
};
realm.create(APPLICATION_SCHEMA, { ...account });
resolve();
}
});
} catch (error) {
reject(error);
}
});

View File

@ -21,27 +21,28 @@ class SteemConnect extends PureComponent {
} }
_onNavigationStateChange = (event) => { _onNavigationStateChange = (event) => {
let accessToken; let code;
const { dispatch, setPinCodeState, handleOnModalClose } = this.props; const { dispatch, setPinCodeState, handleOnModalClose } = this.props;
const { isLoading } = this.state; const { isLoading } = this.state;
if (event.url.indexOf('?access_token=') > -1) { if (event.url.indexOf('?code=') > -1) {
this.webview.stopLoading(); this.webview.stopLoading();
try { try {
accessToken = event.url.match(/\?(?:access_token)\=([\S\s]*?)\&/)[1]; code = event.url.match(/\?(?:code)\=([\S\s]*?)\&/)[1];
} catch (error) { } catch (error) {
// TODO: return // TODO: return
} }
if (!isLoading) { if (!isLoading) {
this.setState({ isLoading: true }); this.setState({ isLoading: true });
handleOnModalClose(); handleOnModalClose();
loginWithSC2(accessToken, 'pinCode') loginWithSC2(code, 'pinCode')
.then((result) => { .then((result) => {
if (result) { if (result) {
dispatch(updateCurrentAccount({ ...result })); dispatch(updateCurrentAccount({ ...result }));
dispatch(addOtherAccount({ username: result.name })); dispatch(addOtherAccount({ username: result.name }));
dispatch(loginAction(true)); dispatch(loginAction(true));
dispatch(openPinCodeModal()); dispatch(openPinCodeModal());
setPinCodeState({ accessToken, navigateTo: ROUTES.DRAWER.MAIN }); // TODO: return accesstoken
setPinCodeState({ accessToken: result.accessToken, navigateTo: ROUTES.DRAWER.MAIN });
} else { } else {
// TODO: Error alert (Toast Message) // TODO: Error alert (Toast Message)
} }