-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathiot.js
95 lines (72 loc) · 2.36 KB
/
iot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//iot side
// don't forget to install the following modules
var keythereum = require("keythereum");
const secp256k1 = require('secp256k1')
const createKeccakHash = require('keccak')
var net = require('net');
const express = require('express');
const bodyParser = require('body-parser');
const LoginContract = require('./login_contract.js');
const jwt = require('jsonwebtoken');
const cuid = require('cuid');
const cors = require('cors');
var Web3 = require('web3');
var web3 = new Web3();
var HOST = '<IOT ip address>';
var event_happened = false;
var PORT = 9090;
var message;
var sign;
var cnt =0;
var token ;
var address;
var publickey = new Buffer(1)
//////////////////wait for event
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
const loginContract = LoginContract.at(process.env.LOGIN_CONTRACT_ADDRESS || '<smart contract eth address>');
const loginAttempt = loginContract.LoginAttempt();
loginAttempt.watch((error, event) => {
if(error) {
console.log(error);
return;
}
event_happened = true;
address = event.args.sender.toLowerCase();
token = event.args.token;
console.log("\x1b[42m","[+] Authentication Event Arrived")
console.log("\x1b[0m","\n");
console.log("Sender Address: "+address);
console.log("Authentication Token: "+token);
});
// listen to input
net.createServer(function(sock) {
console.log('CONNECTED Client: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.on('data', function(data) {
if (cnt == 0){message=data.toString();
cnt++;
}
if (cnt == 1){publickey=data;
cnt++;
}
if (cnt==2){ sign=data.toString();
cnt++;
}
var resM = message.split(",")
if(cnt===3 && resM[0]===token && resM[1]==sock.remoteAddress.toString()){
createKeccakHash('keccak256').digest().toString('hex');
var add = createKeccakHash('keccak256').update(publickey).digest('hex');
if (address.toString().trim() === address) {
console.log("\x1b[42m","[+] User Validated .. Access Granted");
console.log("\x1b[0m","\n");
cnt=0;
sock.write('All Good');
}
}
else {sock.write('!');}
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Device listening on ' + HOST +':'+ PORT);