import {
Component,
ComponentFactoryResolver,
NgZone,
OnInit,
AfterViewInit,
ViewChild,
ViewContainerRef,
ViewEncapsulation
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ScriptLoaderService } from '../_services/script-loader.service';
import { AuthenticationService } from './_services/authentication.service';
import { AlertService } from './_services/alert.service';
import { UserService } from './_services/user.service';
import { AlertComponent } from './_directives/alert.component';
import { LoginCustom } from './_helpers/login-custom';
import { Helpers } from '../helpers';
import Web3 from 'web3';
//import { Credentials, SimpleSigner } from 'uport-connect';
// import { Connect, SimpleSigner } from 'uport-connect';
//import { civicSip , jwt, civic } from 'civic-sip-api';
import ipfsAPI from 'ipfs-api';
import { Buffer } from 'buffer';
import Readable from 'readable-stream';
import { ToastrService } from 'ngx-toastr';
//import { Connect } from 'uport-connect';
//import { Connect } from 'uport-connect';
declare var gapi: any;
declare var $: any;
@Component({
selector: '.m-grid.m-grid--hor.m-grid--root.m-page',
templateUrl: './templates/login-1.component.html',
encapsulation: ViewEncapsulation.None
})
export class AuthComponent implements OnInit, AfterViewInit {
model: any = {};
public loading = false;
loading1 = false;
loading2 = false;
returnUrl: string;
public auth2: any;
public gapi: any;
googleLoginButtonId = 'googleBtn';
userAuthToken = null;
userDisplayName = 'empty';
public ethAddress;
public uportID;
public showModal = false;
public web3;
public message;
public memberAddress;
public showLoader = false;
public showLoader1 = false;
public restrictLogin = false;
@ViewChild('alertSignin', { read: ViewContainerRef })
alertSignin: ViewContainerRef;
@ViewChild('alertSignup', { read: ViewContainerRef })
alertSignup: ViewContainerRef;
@ViewChild('alertForgotPass', { read: ViewContainerRef })
alertForgotPass: ViewContainerRef;
constructor(
private _router: Router,
private _script: ScriptLoaderService,
private _userService: UserService,
private _route: ActivatedRoute,
private _authService: AuthenticationService,
private _alertService: AlertService,
private cfr: ComponentFactoryResolver,
private _zone: NgZone,
private toastr: ToastrService
) {}
ngOnInit() {
// this.model.remember = true;
// get return url from route parameters or default to '/'
this.returnUrl = '/';
// this.returnUrl = this._route.snapshot.queryParams['returnUrl'] || '/';
this._router.navigate([this.returnUrl]);
this._script
.load(
'body',
'assets/vendors/base/vendors.bundle.js',
'assets/demo/default/base/scripts.bundle.js'
)
.then(() => {
Helpers.setLoading(false);
LoginCustom.init();
});
if (window['web3'] == undefined) {
var link =
'https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn';
var blank = '_blank';
this.message =
'The demo currently works on Ethereum Kovan Testnet. Please login to Kovan Testnet using MetaMask
';
$('#m_modal_2').modal('show');
} else {
this.web3 = new Web3(window['web3'].currentProvider);
console.log(this.web3);
this.web3.eth.defaultAccount = this.web3.eth.coinbase;
this.checkMetamask();
}
}
refresh(): void {
window.location.reload();
}
public GBMasterContractAddress;
checkMetamask() {
this.web3.version.getNetwork((err, netId) => {
// var GBMasteAddress ={4: "0xbc7e609bc10b22c206b4fd2dc90b5637697cad0d", 42: "0x5d44ab77ba6d993e23fb545fe678b2c811aab912"};
var GBMasteAddress = {
4: '0xca27deb069d83629db00579ab0f0d80cd119a79b',
42: '0xfd49ec86aaff8a312273cbebc3f48cc4c067c04a',
31: '0x26847806987d45cdb482987f2027b05eef14d061',
96: '0xd62d9f828928661808a4700ea747e8474b236961'
};
this.GBMasterContractAddress = GBMasteAddress[netId];
if (netId !== '4' && netId !== '42') {
// showrinkeby modal
if (this.restrictLogin == false) {
this.message =
'GovBlocks is currently available on Rinkeby and Kovan network.
To continue using GovBlocks please switch network';
$('#m_modal_2').modal('show');
}
this.restrictLogin = true;
if (this.restrictLogin == true) this.callTimeout();
} else if (this.web3.eth.accounts.length == 0) {
if (this.restrictLogin == false) {
this.message =
'Unable to fetch user information.
Please enter password in metamask.';
$('#m_modal_2').modal('show');
}
this.restrictLogin = true;
if (this.restrictLogin == true) this.callTimeout();
} else {
this.restrictLogin = false;
console.log('Hello11');
}
});
}
callTimeout() {
var restrictLogin = this.restrictLogin;
setTimeout(() => {
console.log('Hello');
if (restrictLogin) this.checkMetamask();
}, 2 * 1000);
}
ngAfterViewInit() {
// this.googleInit();
// gapi.signin2.render(
// this.googleLoginButtonId,
// {
// "onSuccess": this.onSignIn,
// "scope": "profile",
// "theme": "dark",
// "width": 180,
// "height": 50
// }
// );
}
googleInit() {
this.checkMetamask();
gapi.signin2.render(this.googleLoginButtonId, {
onSuccess: this.onSignIn.bind(this),
scope: 'profile',
theme: 'dark',
width: 180,
height: 50
});
}
showLoad() {
this.showLoader = true;
}
onSignIn(googleUser) {
var this1 = this;
this.showLoader = false;
var profile = googleUser.getBasicProfile();
// console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
// this.loading = true;
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
if (profile.getEmail != null) {
this.model.name = profile.getName();
this.model.email = profile.getEmail();
this1.signin();
}
}
// uportSign() {
// this.loading = true;
// const uport = new Connect('Prakriti Ailavadi\'s new app', {
// clientId: '2oxUkqEtJDeHLRq6dV37TZ415PjcSDn4npM',
// network: 'rinkeby',
// signer: SimpleSigner('268556fe734567d0f2eaa4dd436a92324f73183f91ca6662d18b0fa2d8f3aac7')
// })
// // Request credentials to login
// uport.requestCredentials({
// requested: ['name', 'phone', 'country'],
// notifications: true // We want this if we want to recieve credentials
// })
// .then((credentials) => {
// this.loading = false;
// console.log(credentials);
// // Do something
// },
// error => {
// this.showAlert('alertSignin');
// this._alertService.error(error);
// this.loading = false;
// })
// // Attest specific credentials
// // uport.attestCredentials({
// // sub: THE_RECEIVING_UPORT_ADDRESS,
// // claim: {
// // CREDENTIAL_NAME: CREDENTIAL_VALUE
// // },
// // exp: new Date().getTime() + 30 * 24 * 60 * 60 * 1000, // 30 days from now
// // })
// }
/*
For self created Prakriti's Civic App:
Private Signing key:- b59e4a23e138604ae5fdd92a1cb126c3ad77df43233624d4fc4ec2b3663723ea
Public Signing key:- 04dc89d9b13cf37b16e980ddcf94a72d2acec4b83b0854cf182640f49cc117ebb5760828f83f901957ab248e3e2216580ba70c5c77d81eaca1e45a653adf21f7ba
Secret:- 1e8fc509c2c26a7f04e01504dd0efb64
Private Encryption key:- be211219fe4c16d8ed9874e23ee100ef92827aff3c4b89f71a378aef5428c9f4
Public Encryption key:- 272742707074271ec9ce6ecfb435650245300739c87aa496c2e20f65cc3d09c5036de0fb5b4636e4cf2cf57ed3cecf647f44603f545042240db3fff1a1ded49f
App ID: HkXEO4dPf
*/
// civicSign() {
// console.log(civicSip);
// console.log(civic);
// // this.loading= true;
// // var civicSip = new civic.sip({ appId: 'rJTJlU9mz' });
// // console.log("in civic");
// this.loading1 = true;
// // Need to register with civic
// const civicClient = civicSip.newClient({
// appId: 'HkXEO4dPf',
// appSecret: '1e8fc509c2c26a7f04e01504dd0efb64',
// prvKey: 'b59e4a23e138604ae5fdd92a1cb126c3ad77df43233624d4fc4ec2b3663723ea',
// })
// .exchangeCode((jwtToken)
// .then((userData) => {
// // store user data and userId as appropriate
// console.log('userData = ', JSON.stringify(userData, null, 4));
// }).catch((error) => {
// console.log(error);
// }));
// console.log(civicClient);
// // civicClient.exchangeCode(jwtToken)
// // .then((userData) => {
// // // store user data and userId as appropriate
// // console.log('userData = ', JSON.stringify(userData, null, 4));
// // }).catch((error) => {
// // console.log(error);
// // });
// // civicClient.signup({ style: 'popup', scopeRequest: civicClient.ScopeRequests.BASIC_SIGNUP });
// // civicSip.newClient('auth-code-received', function (event) {
// // // encoded JWT Token is sent to the server
// // var jwtToken = event.response;
// // civicClient.exchangeCode(jwtToken)
// // .then((userData) => {
// // // store user data and userId as appropriate
// // console.log('userData = '+ userData);
// // }).catch((error) => {
// // console.log(error);
// // });
// // });
// }
getCivicData() {
this.loading1 = false;
}
signin() {
this.loading = true;
this.model.name = 'GOVBLOCKS';
// this.model.email = "govblocks@govblocks.io";
this.model.email = '';
// this._authService.login(this.model.email, this.model.password)
this._authService.login(this.model).subscribe(
data => {
this._router.navigate([this.returnUrl]);
},
error => {
this.memberAddress = this.web3.eth.accounts[0];
this.message =
'Current account ' +
this.model.email +
' is not linked to the current ethereum address ' +
this.memberAddress +
' . Do you wish to link them.';
$('#button1').trigger('click');
this.showAlert('alertSignin');
this._alertService.error(error);
this.loading = false;
}
);
}
signup() {
this.loading = true;
this._userService.create(this.model).subscribe(
data => {
this.showAlert('alertSignin');
this._alertService.success(
'Thank you. To complete your registration please check your email.',
true
);
this.loading = false;
LoginCustom.displaySignInForm();
console.log(data);
this.model = {};
},
error => {
this.showModal = true;
this.showAlert('alertSignup');
this._alertService.error(error);
this.loading = false;
}
);
}
forgotPass() {
this.loading = true;
this._userService.forgotPassword(this.model.email).subscribe(
data => {
this.showAlert('alertSignin');
this._alertService.success(
'Cool! Password recovery instruction has been sent to your email.',
true
);
this.loading = false;
LoginCustom.displaySignInForm();
this.model = {};
},
error => {
this.showAlert('alertForgotPass');
this._alertService.error(error);
this.loading = false;
}
);
}
showAlert(target) {
this[target].clear();
let factory = this.cfr.resolveComponentFactory(AlertComponent);
let ref = this[target].createComponent(factory);
ref.changeDetectorRef.detectChanges();
}
addDetails() {
this.showLoader = true;
this.memberAddress = this.web3.eth.accounts[0];
// var GBMasterContractAddress="0xbc7e609bc10b22c206b4fd2dc90b5637697cad0d";
var GBMasterAbi = [
{
constant: true,
inputs: [],
name: 'getGBTCAddress',
outputs: [{ name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_GDAddress', type: 'address' },
{ name: '_SVAddress', type: 'address' },
{ name: '_GOVAddress', type: 'address' }
],
name: 'changeAllAddress',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getAllDappLength',
outputs: [{ name: '', type: 'uint256' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [{ name: '_memberAddress', type: 'address' }],
name: 'changeAuthorizedGB',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_gbUserName', type: 'bytes32' }],
name: 'getGovBlocksUserDetails',
outputs: [
{ name: 'GbUserName', type: 'bytes32' },
{ name: 'masterContractAddress', type: 'address' },
{ name: 'allContractsbyteCodeHash', type: 'string' },
{ name: 'allCcontractsAbiHash', type: 'string' },
{ name: 'versionNo', type: 'uint256' }
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getGOVAddress',
outputs: [{ name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_memberAddress', type: 'address' },
{ name: '_memberRoleId', type: 'uint256' },
{ name: '_typeOf', type: 'uint8' }
],
name: 'updateMemberRoleGB',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_gbUserName', type: 'bytes32' }],
name: 'getDappDescHash',
outputs: [{ name: '', type: 'string' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_gbUserName', type: 'bytes32' }],
name: 'getDappMasterAddress',
outputs: [{ name: 'masterAddress', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_memberAddress', type: 'address' }],
name: 'isAuthorizedGBOwner',
outputs: [{ name: 'auth', type: 'uint256' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_GBTControllerAddress', type: 'address' },
{ name: '_GBTAddress', type: 'address' }
],
name: 'GovBlocksMasterInit',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_Address', type: 'address' }],
name: 'getGovBlocksUserDetails2',
outputs: [
{ name: 'dappName', type: 'bytes32' },
{ name: 'masterContractAddress', type: 'address' },
{ name: 'dappTokenAddress', type: 'address' }
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getDappUser',
outputs: [{ name: '', type: 'string' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_gbUserName', type: 'bytes32' }],
name: 'getDappTokenAddress',
outputs: [{ name: 'tokenAddres', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [{ name: '_GBTConrollerAddress', type: 'address' }],
name: 'updateGBTControllerAddress',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_categoryId', type: 'uint256' },
{ name: '_categoryData', type: 'string' }
],
name: 'updateCategoryGB',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_dappDescriptionHash', type: 'string' }
],
name: 'changeDappDescHash',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getGBTandGBTC',
outputs: [
{ name: '_GBTController', type: 'address' },
{ name: '_GBToken', type: 'address' }
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'owner',
outputs: [{ name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_gbUserName', type: 'bytes32' }],
name: 'getGovBlocksUserDetails1',
outputs: [
{ name: 'GbUserName', type: 'bytes32' },
{ name: 'masterContractAddress', type: 'address' },
{ name: 'dappTokenAddress', type: 'address' },
{ name: 'allContractsbyteCodeHash', type: 'string' },
{ name: 'allCcontractsAbiHash', type: 'string' },
{ name: 'versionNo', type: 'uint256' }
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getSVAddress',
outputs: [{ name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getAllDappArray',
outputs: [{ name: '', type: 'bytes32[]' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_descHash', type: 'string' }
],
name: 'addNewCategoryGB',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'authGBOwner',
outputs: [{ name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_GBTControllerAddress', type: 'address' },
{ name: '_GBTokenAddress', type: 'address' }
],
name: 'changeAllAddress1',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_index', type: 'uint256' }],
name: 'getGovBlocksUserDetailsByIndex',
outputs: [
{ name: 'index', type: 'uint256' },
{ name: 'GbUserName', type: 'bytes32' },
{ name: 'MasterContractAddress', type: 'address' }
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getGDAddress',
outputs: [{ name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_typeOf', type: 'bytes16' },
{ name: '_value', type: 'uint256' }
],
name: 'configureGlobalParameters',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: false,
inputs: [{ name: '_hash', type: 'string' }],
name: 'setDappUser',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_byteCodeHash', type: 'string' },
{ name: '_abiHash', type: 'string' }
],
name: 'setByteCodeAndAbi',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_newMasterAddress', type: 'address' }
],
name: 'changeDappMasterAddress',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getGBTAddress',
outputs: [{ name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_dappTokenAddress', type: 'address' }
],
name: 'changeDappTokenAddress',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_dappTokenAddress', type: 'address' },
{ name: '_dappDescriptionHash', type: 'string' }
],
name: 'addGovBlocksUser',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [],
name: 'getByteCodeAndAbi',
outputs: [
{ name: 'byteCode', type: 'string' },
{ name: 'abiHash', type: 'string' }
],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [
{ name: '_gbUserName', type: 'bytes32' },
{ name: '_newRoleName', type: 'bytes32' },
{ name: '_newDescHash', type: 'string' }
],
name: 'addNewMemberRoleGB',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: false,
inputs: [{ name: '_newOwner', type: 'address' }],
name: 'transferOwnership',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_contractAddress', type: 'address' }],
name: 'getDappNameByAddress',
outputs: [{ name: '', type: 'bytes32' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: true,
inputs: [{ name: '_gbIndex', type: 'uint256' }],
name: 'getAllDappById',
outputs: [{ name: '_gbUserName', type: 'bytes32' }],
payable: false,
stateMutability: 'view',
type: 'function'
},
{
constant: false,
inputs: [{ name: '_GBTContractAddress', type: 'address' }],
name: 'updateGBTAddress',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function'
}
];
var hash;
this.web3.eth.contract(GBMasterAbi).at(
this.GBMasterContractAddress,
function(error, result) {
let ans = result.getDappUser(
function(error1, result1) {
var hashDetails = this.getDataFromHash(result1);
if (hashDetails == null) {
hashDetails = {
gmail: []
};
} else if (hashDetails.gmail == null) {
hashDetails = {
gmail: []
};
}
hashDetails.gmail.push({
name: this.model.name,
email: this.model.email
});
console.log('Initializing ipfs');
var ipfs = ipfsAPI('ipfs.infura.io', '5001', { protocol: 'https' });
var quoteArdetails = hashDetails;
const rs1 = new Readable();
rs1.push(Buffer.from(JSON.stringify(quoteArdetails)));
rs1.push(null);
ipfs.files.add(
rs1,
function(err, files) {
if (!err) {
// console.log("No error");
// console.log(files[0].hash);
hash = files[0].hash;
ipfs.pin.add(files[0].hash, function(err) {});
console.log(hash);
let ans = result.setDappUser(
hash,
function(error2, result2) {
if (!error2) {
// console.log(hash);
this.toastr.info(
'Submitted to BlockChain.Awaiting confirmation!'
);
this.timeout(result2, this.web3);
} else {
// console.log(hash);
this.toastr.error('Error executing the \n operation');
this.showLoader = false;
}
}.bind(this)
);
}
}.bind(this)
);
}.bind(this)
);
}.bind(this)
);
}
timeout(hash, web3) {
setTimeout(() => {
console.log('Test');
var boundFunction = web3.eth.getTransactionReceipt(
hash,
function(error, result) {
// console.log(error);
// console.log(result);
if (result != null) {
this.toastr.success('Details Added Succesfully!');
this.showLoader = false;
setTimeout(() => {
this.signin();
}, 500);
} else this.timeout(hash, web3);
}.bind(this)
);
}, 10 * 1000);
}
getDataFromHash(hash) {
if (hash == '') {
return hash;
} else {
console.log(hash);
var XMLHttp = new XMLHttpRequest();
XMLHttp.open('GET', 'https://ipfs.govblocks.io/ipfs/' + hash, false);
XMLHttp.send(null);
// // // this gives the json containing the details - title, description, voting type
var hashDetails = JSON.parse(XMLHttp.responseText);
// console.log(hashDetails);
return hashDetails;
}
}
}