Skip to content

Commit

Permalink
authentication start
Browse files Browse the repository at this point in the history
  • Loading branch information
BIJOY-SUST committed Nov 7, 2019
1 parent 2d9aa99 commit 119fdbe
Show file tree
Hide file tree
Showing 14 changed files with 665 additions and 27 deletions.
116 changes: 104 additions & 12 deletions javascript/app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
/* eslint-disable quotes */
/* eslint-disable no-unused-vars */
/* eslint-disable no-var */
/* eslint-disable strict */
const path = require('path');

const createUser = require('./routers/createUser');
const registerUserDB = require('./routers/register');
const loginUserDB = require('./routers/login');

const express = require('express');
const hbs = require('hbs');
const crypto = require("crypto");
const path = require('path');
const fs = require('file-system');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());

var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

const publicDirectoryPath = path.join(__dirname, './website');

// console.log(__dirname);
Expand All @@ -18,10 +30,8 @@ app.use(express.static(publicDirectoryPath));

const port = process.env.PORT || 3000;



// index page
app.get('/', function (req, res) {
app.get('/', (req, res) => {
// res.send('Hello World');
res.render('index');
});
Expand All @@ -31,7 +41,10 @@ app.get('/login', (req, res) => {
res.render('login');
});
// login page
app.post('/login', (req, res) => {
app.post('/login', async (req, res) => {

var result = await loginUserDB();
console.log(result);
res.render('home');
});

Expand All @@ -40,30 +53,109 @@ app.get('/register', (req, res) => {
res.render('register');
});
// register page
app.post('/register', (req, res) => {
res.render('login');
app.post('/register', urlencodedParser , async function (req, res) {
const user = {
key: req.body.username+req.body.email,
token: req.body.email+req.body.username,
name: req.body.username,
email: req.body.email,
password: req.body.password
};
console.log(user.password);
user.password = crypto.createHash('sha256').update(user.password).digest("base64");
console.log(user.password);

console.log(user.key);
user.key = crypto.createHash('sha256').update(user.key).digest("base64");
console.log(user.key);

console.log(user.token);
user.token = crypto.createHash('sha256').update(user.token).digest("base64");
console.log(user.token);


// console.log(user.name);
// console.log(user.email);
// console.log(user.password);

await createUser(user.name);

var keyDirectorey = path.join(__dirname, './wallet/' + user.name);
// console.log(keyDirectorey);
var privateKey, publicKey;
fs.readdir(keyDirectorey, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
if (file !== user.name) {
var name = file;
var len = name.length;
var i = len - 3;
var lastThree = name.substring(i, len);
console.log(lastThree);
fs.readFile(keyDirectorey + '/' + file, 'utf-8', function (err, content) {
if (err) {
return console.log('Unable to scan file: ' + err);
}
content = content.replace(/(\r\n|\n|\r)/gm, "");
// console.log(content);
if (lastThree === 'riv') {
privateKey = content;
// console.log(privateKey);
}
else if (lastThree === 'pub') {
publicKey = content;
// console.log(publicKey);
}
});
}
});
});

setTimeout( async function () {
console.log('Waiting for key');
console.log(privateKey);
console.log(publicKey);

await registerUserDB(user,privateKey,publicKey).then((result)=>{
console.log('Register successfully');
res.render('login');
}).catch((error)=>{
console.error('Failed to register successfully');
res.render('register');
});
res.render('login');
}, 2000);




});

//home page
app.get('/home', function(req,res){
app.get('/home', function (req, res) {
res.render('home');
});

// upload page
app.get('/upload', function(req,res){
app.get('/upload', function (req, res) {
res.render('upload');
});
// upload page
app.post('/upload', function(req,res){
app.post('/upload', function (req, res) {
res.render('home');
});



app.get('/logout', function(req,res) {
app.get('/logout', function (req, res) {
res.render('index');
});
app.get('/test', function(req,res) {
app.get('/test', function (req, res) {
res.render('test');
});

Expand Down
27 changes: 27 additions & 0 deletions javascript/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions javascript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
"dependencies": {
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.4",
"crypto": "^1.0.1",
"express": "^4.17.1",
"fabric-ca-client": "~1.4.0",
"fabric-network": "~1.4.0",
"file-system": "^2.2.2",
"hbs": "^4.0.6",
"multer": "^1.4.2",
"nodemon": "^1.19.4"
Expand Down
8 changes: 4 additions & 4 deletions javascript/registerUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function main() {
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1');
if (userExists) {
console.log('An identity for the user "user1" already exists in the wallet');
console.log('An identity for the user user1 already exists in the wallet');
return;
}

Expand All @@ -45,12 +45,12 @@ async function main() {
const enrollment = await ca.enroll({ enrollmentID: 'user1', enrollmentSecret: secret });
const userIdentity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
await wallet.import('user1', userIdentity);
console.log('Successfully registered and enrolled admin user "user1" and imported it into the wallet');
console.log('Successfully registered and enrolled admin user user1 and imported it into the wallet');

} catch (error) {
console.error(`Failed to register user "user1": ${error}`);
console.error(`Failed to register user '+userName+': ${error}`);
process.exit(1);
}
}

main();
main();
57 changes: 57 additions & 0 deletions javascript/routers/createUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/

'use strict';

const { FileSystemWallet, Gateway, X509WalletMixin } = require('fabric-network');
const path = require('path');

const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');

async function main(userName) {
try {

// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path(creatUser): ${walletPath}`);

// Check to see if we've already enrolled the user.
const userExists = await wallet.exists(userName);
if (userExists) {
console.log('An identity for the user '+userName+' already exists in the wallet');
return;
}

// Check to see if we've already enrolled the admin user.
const adminExists = await wallet.exists('admin');
if (!adminExists) {
console.log('An identity for the admin user "admin" does not exist in the wallet');
console.log('Run the enrollAdmin.js application before retrying');
return;
}

// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'admin', discovery: { enabled: true, asLocalhost: true } });

// Get the CA client object from the gateway for interacting with the CA.
const ca = gateway.getClient().getCertificateAuthority();
const adminIdentity = gateway.getCurrentIdentity();

// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: userName, role: 'client' }, adminIdentity);
const enrollment = await ca.enroll({ enrollmentID: userName, enrollmentSecret: secret });
const userIdentity = X509WalletMixin.createIdentity('Org1MSP', enrollment.certificate, enrollment.key.toBytes());
await wallet.import(userName, userIdentity);
console.log('Successfully registered and enrolled admin user '+userName+' and imported it into the wallet');

} catch (error) {
console.error(`Failed to register user '+userName+': ${error}`);
process.exit(1);
}
}

// main();
module.exports = main;
54 changes: 54 additions & 0 deletions javascript/routers/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/

'use strict';

const { FileSystemWallet, Gateway } = require('fabric-network');
const path = require('path');

const ccpPath = path.resolve(__dirname, '..', '..', '..', 'first-network', 'connection-org1.json');

async function main() {
try {

// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path(login): ${walletPath}`);

// Check to see if we've already enrolled the user.
const userExists = await wallet.exists('user1');
if (!userExists) {
console.log('An identity for the user "user1" does not exist in the wallet');
console.log('Run the registerUser.js application before retrying');
return;
}

// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, { wallet, identity: 'user1', discovery: { enabled: true, asLocalhost: true } });

// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('mychannel');

// Get the contract from the network.
const contract = network.getContract('IntellectualProperty');

// Evaluate the specified transaction.
// queryCar transaction - requires 1 argument, ex: ('queryCar', 'CAR4')
// queryAllCars transaction - requires no arguments, ex: ('queryAllCars')
// const result = await contract.evaluateTransaction('queryAllCars');
const result = await contract.evaluateTransaction('queryCar', 'CAR4');
console.log(`Transaction has been evaluated, result is: ${result.toString()}`);
return result.toString();

} catch (error) {
console.error(`Failed to evaluate transaction: ${error}`);
process.exit(1);
return error;
}
}

// main();
module.exports = main;
Loading

0 comments on commit 119fdbe

Please sign in to comment.