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

Store keys #37

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@
"@angular/platform-browser": "6.0.7",
"@angular/platform-browser-dynamic": "6.0.7",
"@angular/router": "6.0.7",
"angularfire2": "^5.0.0-rc.11",
"chart.js": "^2.7.2",
"core-js": "^2.5.7",
"firebase": "^5.2.0",
"ng2-charts": "^1.6.0",
"rxjs": "^6.2.1",
"web3": "1.0.0-beta.33",
Expand Down
4 changes: 3 additions & 1 deletion src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
<a mat-button routerLink="/send-tx">Send GO</a>
</mat-toolbar-row>


</mat-toolbar>

<div class="content-wrapper">
Expand All @@ -47,6 +46,9 @@
</mat-card-content>
</mat-card>
<router-outlet></router-outlet>
<div>
<app-auth></app-auth>
</div>
<app-messages></app-messages>
<footer>
<a href="{{explorerHost()}}" class="sugar">
Expand Down
26 changes: 23 additions & 3 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ import { RouterModule, Routes } from '@angular/router';
import {FlexLayoutModule} from '@angular/flex-layout';
import {MatFormFieldModule, MatButtonModule, MatCheckboxModule, MatInputModule, MatCardModule, MatProgressSpinnerModule, MatProgressBarModule, MatToolbarModule, MatSnackBarModule,
MatSelectModule} from '@angular/material';
import { HttpClientModule } from '@angular/common/http';

import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { Globals } from './globals';
import { environment } from '../environments/environment';

import { AppComponent } from './app.component';
import { WalletComponent } from './wallet/wallet.component';
Expand All @@ -21,6 +26,8 @@ import { PageNotFoundComponent } from './page-not-found/page-not-found.component
import { GetGoComponent } from './get-go/get-go.component';
import { SendTxComponent } from './send-tx/send-tx.component';
import { ChartsModule } from 'ng2-charts';
import { AuthComponent } from './auth/auth.component';


const appRoutes: Routes = [
{ path: 'view-balance', component: ViewBalanceComponent },
Expand Down Expand Up @@ -51,21 +58,34 @@ const appRoutes: Routes = [
PageNotFoundComponent,
GetGoComponent,
SendTxComponent,
ViewBalanceComponent
ViewBalanceComponent,
AuthComponent,
],
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
),
BrowserModule,
HttpClientModule,
// FormsModule,
ReactiveFormsModule,
BrowserAnimationsModule,
FlexLayoutModule,
MatFormFieldModule, MatButtonModule, MatCheckboxModule, MatInputModule, MatCardModule, MatProgressSpinnerModule, MatProgressBarModule, MatToolbarModule, MatSnackBarModule,
MatFormFieldModule,
MatButtonModule,
MatCheckboxModule,
MatInputModule,
MatCardModule,
MatProgressSpinnerModule,
MatProgressBarModule,
MatToolbarModule,
MatSnackBarModule,
MatSelectModule,
ChartsModule,
MatSelectModule,
ChartsModule
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule
],
providers: [
Globals,
Expand Down
8 changes: 8 additions & 0 deletions src/app/auth/auth.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<div *ngIf="afAuth.user | async as user; else showLogin">
<h1>Hello {{ user.displayName }}!</h1>
<button (click)="logout()">Logout</button>
</div>
<ng-template #showLogin>
<p>Please login.</p>
<button (click)="login()">Login with Google</button>
</ng-template>
Empty file.
25 changes: 25 additions & 0 deletions src/app/auth/auth.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AuthComponent } from './auth.component';

describe('AuthComponent', () => {
let component: AuthComponent;
let fixture: ComponentFixture<AuthComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AuthComponent ]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(AuthComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
53 changes: 53 additions & 0 deletions src/app/auth/auth.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { auth } from 'firebase';

import {Globals} from '../globals';

@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {

constructor(public afAuth: AngularFireAuth, private globals: Globals) {
}

login() {
var provider = new auth.GoogleAuthProvider();
// provider.addScope('profile');
// provider.addScope('email');
provider.addScope('https://www.googleapis.com/auth/drive.appdata');
provider.addScope('https://www.googleapis.com/auth/drive.file');
let a = this.afAuth.auth;
a.setPersistence(auth.Auth.Persistence.SESSION); // this returns a promise... so could do something? https://firebase.google.com/docs/reference/js/firebase.auth.Auth#setPersistence
a.signInWithPopup(provider).then(data => {
// This gives you a Google Access Token.
let at = data.credential['accessToken'];
console.log("access token:", at);
sessionStorage.setItem("gAccessToken", at);
// The signed-in user info.
// var user = result.user;
});
}

logout() {
this.afAuth.auth.signOut();
}

ngOnInit() {
// this.afAuth.user.subscribe(user => {
// console.log("auth component init", user);
// if(user != null){
// console.log("get access token")
// user.getIdToken().then(data => {
// console.log("idtoken:", data);
// })
// .catch(err => {
// console.log("ERROR!", err);
// });
// }
// })
}
}
7 changes: 5 additions & 2 deletions src/app/create-account/create-account.component.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Component, OnInit } from '@angular/core';

import { WalletService } from '../wallet.service';
import { MessageService } from '../message.service';
import { DriveService } from '../drive.service';

@Component({
selector: 'app-create-account',
Expand All @@ -11,13 +12,15 @@ export class CreateAccountComponent implements OnInit {

newAccount: any;

constructor(private walletService: WalletService) { }
constructor(private walletService: WalletService, public drive: DriveService) { }

ngOnInit() {
}

createAccount(): void {
this.newAccount = this.walletService.createAccount();
let contents = {address: this.newAccount.address, privateKey: this.newAccount.privateKey};
this.drive.uploadJSON("gokey-" + this.newAccount.address, contents).subscribe((data) => console.log(data));
}

}
15 changes: 15 additions & 0 deletions src/app/drive.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { TestBed, inject } from '@angular/core/testing';

import { DriveService } from './drive.service';

describe('DriveService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [DriveService]
});
});

it('should be created', inject([DriveService], (service: DriveService) => {
expect(service).toBeTruthy();
}));
});
64 changes: 64 additions & 0 deletions src/app/drive.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import {throwError as observableThrowError, Observable , of , from as fromPromise } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';

import {Globals} from './globals';

@Injectable({
providedIn: 'root'
})

// good info here: https://stackoverflow.com/questions/10317638/how-do-i-add-create-insert-files-to-google-drive-through-the-api
export class DriveService {
uploadURL: string = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart";

constructor(private afAuth: AngularFireAuth, private http: HttpClient, private globals: Globals ) { }

uploadJSON(name: string, body: {[key: string]: string}): Observable<any> {
let user = this.afAuth.auth.currentUser;
if(user != null){
// let fd = new FormData();
// let metadata = {
// // "title": "file_name.extension",
// "name": "gokey-" + name,
// "mimeType": "application/json",
// "description": "Stuff about the file"
// }
// let blob = new Blob([JSON.stringify(metadata, null, 2)], {type : 'application/json; charset=UTF-8'});
// fd.append('metadata', blob);
// blob = new Blob([JSON.stringify(body, null, 2)], {type : 'application/json'});
// fd.append('file', blob);
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'multipart/related; boundary=foo_bar_baz',
'Authorization': 'Bearer ' + this.globals.gAccessToken()
})
};
let b = `--foo_bar_baz
Content-Type: application/json; charset=UTF-8

{
"name": "` + name + `",
"mimeType": "application/json"
}

--foo_bar_baz
Content-Type: application/json

` + JSON.stringify(body) + `
--foo_bar_baz--`
return this.http.post(this.uploadURL, b, httpOptions);
}
}

listFiles(q: string): Observable<any> {
let httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer ' + this.globals.gAccessToken()
})
};
return this.http.get('https://www.googleapis.com/drive/v3/files?q=' + q, httpOptions);
}
}
9 changes: 9 additions & 0 deletions src/app/globals.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { AngularFireAuth } from 'angularfire2/auth';

@Injectable()
export class Globals {
network: string = 'mainnet';
// googleAccessToken: string;


constructor(public afAuth: AngularFireAuth ) { }

public rpcHost(): string {
if (this.network == "testnet") {
Expand All @@ -21,4 +26,8 @@ export class Globals {
}
return 'http://localhost:8000';
}

public gAccessToken(): string {
return sessionStorage.getItem("gAccessToken"); // set in auth component
}
}
7 changes: 7 additions & 0 deletions src/app/send-tx/send-tx.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@
<mat-card-title>Send Transaction</mat-card-title>
<form [formGroup]="txForm">
<div class="form-group" id="div-tx-form">
<div *ngIf="addresses">
Stored Accounts:
<select class="form-control" id="address">
<option>Select an account:</option>
<option *ngFor="let addr of addresses" [value]="addr">{{addr}}</option>
</select>
</div>
<mat-form-field class="full-width">
<input matInput placeholder="Private Key" formControlName="privateKey">
</mat-form-field>
Expand Down
22 changes: 20 additions & 2 deletions src/app/send-tx/send-tx.component.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import {Globals} from '../globals'
import {Globals} from '../globals';
import { WalletService } from '../wallet.service';
import { MessageService } from '../message.service';
import { DriveService } from '../drive.service';

@Component({
selector: 'app-send-tx',
Expand All @@ -16,13 +17,30 @@ export class SendTxComponent implements OnInit {
balance: string;
sending: boolean = false;
receipt: Map<string,any>;
// list of stored addresses
addresses: string[];

constructor(private walletService: WalletService, private fb: FormBuilder, private messageService: MessageService, private globals: Globals) {
constructor(private walletService: WalletService, private fb: FormBuilder, private messageService: MessageService, public globals: Globals, public drive: DriveService) {
this.createForm();
}

ngOnInit() {
this.onChanges();
this.updateStoredAddresses();
}

updateStoredAddresses(): void {
if(this.globals.gAccessToken() != null) {
this.drive.listFiles("name contains 'gokey-'").subscribe(data => {
console.log(data);
let addrs = [];
for (var i = 0; i < data.files.length; i++) {
let f = data.files[i];
addrs.push(f.name.substring(6));
}
this.addresses = addrs;
})
}
}

createForm() {
Expand Down
10 changes: 9 additions & 1 deletion src/environments/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,13 @@
// The list of which env maps to which file can be found in `.angular-cli.json`.

export const environment = {
production: false
production: false,
firebase: {
apiKey: "AIzaSyA09X4-XEuSdo_b_ZgRnujY2Bl8dYMoKkA",
authDomain: "gochain-wallet.firebaseapp.com",
databaseURL: "https://gochain-wallet.firebaseio.com",
projectId: "gochain-wallet",
storageBucket: "gochain-wallet.appspot.com",
messagingSenderId: "264455571012"
}
};