Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Account recovery #28

Merged
merged 9 commits into from
May 9, 2019
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules/
.env
78 changes: 43 additions & 35 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ app.use(async function(ctx, next) {
try {
await next();
} catch(e) {
console.log("Error: ", e);
console.log('Error: ', e);
if (e.response) {
ctx.throw(e.response.status, e.response.text);
}
Expand Down Expand Up @@ -47,41 +47,7 @@ const near = new Near(nearClient);
const account = new Account(nearClient);
const NEW_ACCOUNT_AMOUNT = 100;

const viewAccount = accountId => {
return account.viewAccount(accountId);
};

router.post('/contract', async ctx => {
const body = ctx.request.body;
keyStore.setKey(body.receiver, defaultKey);
ctx.body = await near.waitForTransactionResult(
await near.deployContract(body.receiver, Buffer.from(body.contract, 'base64')));
});

router.post('/contract/:name/:methodName', async ctx => {
const body = ctx.request.body;
const sender = body.sender || defaultSender;
const args = body.args || {};
ctx.body = await near.waitForTransactionResult(
await near.scheduleFunctionCall(parseInt(body.amount) || 0, sender, ctx.params.name, ctx.params.methodName, args));
});

router.post('/contract/view/:name/:methodName', async ctx => {
const body = ctx.request.body;
const args = body.args || {};
ctx.body = await near.callViewFunction(defaultSender, ctx.params.name, ctx.params.methodName, args);
});

router.get('/account/:name', async ctx => {
ctx.body = await viewAccount(ctx.params.name);
});

/**
* Create a new account. Generate a throw away account id (UUID).
* Returns account name and public/private key.
*/
router.post('/account', async ctx => {
// TODO: this is using alice account to create all accounts. We may want to change that.
const body = ctx.request.body;
const newAccountId = body.newAccountId;
const newAccountPublicKey = body.newAccountPublicKey;
Expand All @@ -93,6 +59,48 @@ router.post('/account', async ctx => {
ctx.body = response;
});

const password = require('secure-random-password');
const models = require('./models');
const FROM_PHONE = '+14086179592';
vgrichina marked this conversation as resolved.
Show resolved Hide resolved
router.post('/account/:phoneNumber/:accountId/requestCode', async ctx => {
const accountId = ctx.params.accountId;
const phoneNumber = ctx.params.phoneNumber;

const securityCode = password.randomPassword({ length: 6, characters: password.digits });
vgrichina marked this conversation as resolved.
Show resolved Hide resolved
const [account] = await models.Account.findOrCreate({ where: { accountId, phoneNumber } });
await account.update({ securityCode });

const accountSid = process.env.TWILIO_ACCOUNT_SID;
vgrichina marked this conversation as resolved.
Show resolved Hide resolved
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
await client.messages
.create({
body: `Your NEAR Wallet security code is: ${securityCode}`,
from: FROM_PHONE,
to: phoneNumber
});
ctx.body = {};
});

router.post('/account/:phoneNumber/:accountId/validateCode', async ctx => {
const accountId = ctx.params.accountId;
const phoneNumber = ctx.params.phoneNumber;

const securityCode = ctx.request.body.securityCode

const account = await models.Account.findOne({ where: { accountId, phoneNumber } });
if (!account.securityCode || account.securityCode != securityCode) {
ctx.throw(401);
}
if (!account.confirmed) {
// TODO: Validate that user actually owns account (e.g. expect signed message with securityCode)
}
await account.update({ securityCode: null, confirmed: true });
// TODO: Update account key using nearlib

ctx.body = {};
});

app
.use(router.routes())
.use(router.allowedMethods());
Expand Down
23 changes: 23 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"development": {
"username": "helper",
"password": "helper",
"database": "accounts_development",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "helper",
"password": "helper",
"database": "accounts_test",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"username": "helper",
"password": "helper",
"database": "accounts_production",
"host": "127.0.0.1",
"dialect": "postgres"
}
}
38 changes: 38 additions & 0 deletions migrations/20190430081305-create-account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Accounts', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
accountId: {
type: Sequelize.STRING
},
phoneNumber: {
type: Sequelize.STRING
},
securityCode: {
type: Sequelize.STRING
},
confirmed: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Accounts');
}
};
17 changes: 17 additions & 0 deletions models/account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const Account = sequelize.define('Account', {
accountId: DataTypes.STRING,
phoneNumber: DataTypes.STRING,
securityCode: DataTypes.STRING,
confirmed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
}, {});
Account.associate = function(models) {
// associations can be defined here
};
return Account;
};
37 changes: 37 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;