refactorization app creation calling order

This commit is contained in:
Nicolas Constant 2018-09-09 18:54:06 -04:00
parent 6784f43cfc
commit 4f117e87cd
No known key found for this signature in database
GPG Key ID: 1E9F677FB01A5688
1 changed files with 89 additions and 94 deletions

View File

@ -10,127 +10,122 @@ import { AddRegisteredApp, RegisteredAppsState, RegisteredAppsStateModel, AppInf
import { AccountInfo, AddAccount } from "../../states/accounts.state"; import { AccountInfo, AddAccount } from "../../states/accounts.state";
@Component({ @Component({
selector: "app-register-new-account", selector: "app-register-new-account",
templateUrl: "./register-new-account.component.html", templateUrl: "./register-new-account.component.html",
styleUrls: ["./register-new-account.component.scss"] styleUrls: ["./register-new-account.component.scss"]
}) })
export class RegisterNewAccountComponent implements OnInit { export class RegisterNewAccountComponent implements OnInit {
@Input() mastodonFullHandle: string; @Input() mastodonFullHandle: string;
result: string; result: string;
// registeredApps$: Observable<RegisteredAppsStateModel>; // registeredApps$: Observable<RegisteredAppsStateModel>;
private authStorageKey: string = 'tempAuth'; private authStorageKey: string = 'tempAuth';
constructor( constructor(
private readonly authService: AuthService, private readonly authService: AuthService,
private readonly accountsService: AccountsService, private readonly accountsService: AccountsService,
private readonly store: Store, private readonly store: Store,
private readonly activatedRoute: ActivatedRoute) { private readonly activatedRoute: ActivatedRoute) {
// this.registeredApps$ = this.store.select(state => state.registeredapps.registeredApps); // this.registeredApps$ = this.store.select(state => state.registeredapps.registeredApps);
this.activatedRoute.queryParams.subscribe(params => { this.activatedRoute.queryParams.subscribe(params => {
const code = params['code']; const code = params['code'];
if (!code) return; if (!code) return;
const appDataWrapper = <CurrentAuthProcess>JSON.parse(localStorage.getItem(this.authStorageKey)); const appDataWrapper = <CurrentAuthProcess>JSON.parse(localStorage.getItem(this.authStorageKey));
if(!appDataWrapper) return; if (!appDataWrapper) return;
const appInfo = this.getAllSavedApps().filter(x => x.instance === appDataWrapper.instance)[0]; const appInfo = this.getAllSavedApps().filter(x => x.instance === appDataWrapper.instance)[0];
console.warn('appInfo'); console.warn('appInfo');
console.warn(appInfo); console.warn(appInfo);
this.authService.getToken(appDataWrapper.instance, appInfo.app.client_id, appInfo.app.client_secret, code, appInfo.app.redirect_uri) this.authService.getToken(appDataWrapper.instance, appInfo.app.client_id, appInfo.app.client_secret, code, appInfo.app.redirect_uri)
.then((tokenData: TokenData) => { .then((tokenData: TokenData) => {
const accountInfo = new AccountInfo(); const accountInfo = new AccountInfo();
accountInfo.username = appDataWrapper.username; accountInfo.username = appDataWrapper.username;
accountInfo.instance = appDataWrapper.instance; accountInfo.instance = appDataWrapper.instance;
accountInfo.token= tokenData; accountInfo.token = tokenData;
this.store.dispatch([new AddAccount(accountInfo)])
.subscribe(() => {
localStorage.removeItem(this.authStorageKey);
});
});
this.store.dispatch([new AddAccount(accountInfo)])
.subscribe(() => {
localStorage.removeItem(this.authStorageKey);
});
}); });
}); }
} ngOnInit() {
// this.registeredApps$.subscribe(x => {
// console.error('registeredApps$')
// console.warn(x);
// });
}
ngOnInit() { onSubmit(): boolean {
// this.registeredApps$.subscribe(x => { let fullHandle = this.mastodonFullHandle.split('@').filter(x => x != null && x !== '');
// console.error('registeredApps$')
// console.warn(x);
// });
}
onSubmit(): boolean { const username = fullHandle[0];
let fullHandle = this.mastodonFullHandle.split('@').filter(x => x != null && x !== ''); const instance = fullHandle[1];
const username = fullHandle[0]; this.checkAndCreateApplication(instance)
const instance = fullHandle[1]; .then((appData: AppData) => {
this.redirectToInstanceAuthPage(username, instance, appData);
const alreadyRegisteredApps = this.getAllSavedApps();
const instanceApps = alreadyRegisteredApps.filter(x => x.instance === instance);
if (instanceApps.length !== 0) {
console.log('instance already registered');
const appData = instanceApps[0].app;
this.redirectToInstanceAuthPage(username, instance, appData);
} else {
console.log('instance not registered');
const redirect_uri = this.getLocalHostname() + '/register';
this.authService.createNewApplication(instance, 'Sengi', redirect_uri, 'read write follow', 'https://github.com/NicolasConstant/sengi')
.then((appData: AppData) => {
this.saveNewApp(instance, appData)
.then(() => {
this.redirectToInstanceAuthPage(username, instance, appData);
}); });
})
.catch(err => {
console.error(err);
});
}
return false;
}
private getLocalHostname(): string { return false;
let localHostname = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');
//Electron hack
if (localHostname === 'file://') {
localHostname = 'http://localhost:4200';
} }
return localHostname; private checkAndCreateApplication(instance: string): Promise<AppData> {
} const alreadyRegisteredApps = this.getAllSavedApps();
const instanceApps = alreadyRegisteredApps.filter(x => x.instance === instance);
private getAllSavedApps(): AppInfo[] { if (instanceApps.length !== 0) {
const snapshot = <RegisteredAppsStateModel>this.store.snapshot().registeredapps; console.log('instance already registered');
return snapshot.apps; return Promise.resolve(instanceApps[0].app);
} } else {
console.log('instance not registered');
const redirect_uri = this.getLocalHostname() + '/register';
return this.authService.createNewApplication(instance, 'Sengi', redirect_uri, 'read write follow', 'https://github.com/NicolasConstant/sengi')
.then((appData: AppData) => {
return this.saveNewApp(instance, appData)
.then(() => { return appData; });
})
}
}
private saveNewApp(instance: string, app: AppData): Promise<any> { private getLocalHostname(): string {
const appInfo = new AppInfo(); let localHostname = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');
appInfo.instance = instance; return localHostname;
appInfo.app = app; }
return this.store.dispatch([ private getAllSavedApps(): AppInfo[] {
new AddRegisteredApp(appInfo) const snapshot = <RegisteredAppsStateModel>this.store.snapshot().registeredapps;
]).toPromise(); return snapshot.apps;
} }
private redirectToInstanceAuthPage(username: string, instance: string, app: AppData) { private saveNewApp(instance: string, app: AppData): Promise<any> {
const appDataTemp = new CurrentAuthProcess(username, instance); const appInfo = new AppInfo();
localStorage.setItem('tempAuth', JSON.stringify(appDataTemp)); appInfo.instance = instance;
appInfo.app = app;
let instanceUrl = `https://${instance}/oauth/authorize?scope=${encodeURIComponent('read write follow')}&response_type=code&redirect_uri=${encodeURIComponent(app.redirect_uri)}&client_id=${app.client_id}`; return this.store.dispatch([
new AddRegisteredApp(appInfo)
]).toPromise();
}
window.location.href = instanceUrl; private redirectToInstanceAuthPage(username: string, instance: string, app: AppData) {
} const appDataTemp = new CurrentAuthProcess(username, instance);
localStorage.setItem('tempAuth', JSON.stringify(appDataTemp));
let instanceUrl = `https://${instance}/oauth/authorize?scope=${encodeURIComponent('read write follow')}&response_type=code&redirect_uri=${encodeURIComponent(app.redirect_uri)}&client_id=${app.client_id}`;
window.location.href = instanceUrl;
}
} }
class CurrentAuthProcess { class CurrentAuthProcess {
constructor(public username: string, public instance: string) { } constructor(public username: string, public instance: string) { }
} }