Merge pull request #1 from NicolasConstant/topic-fix-electron-oauth

Topic fix electron oauth
This commit is contained in:
Nicolas Constant 2018-09-09 18:54:49 -04:00 committed by GitHub
commit 690f57a5cf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 189 additions and 136 deletions

142
main.js
View File

@ -1,63 +1,121 @@
const {app, BrowserWindow, shell} = require('electron')
const path = require('path')
const url = require('url')
const { app, Menu, server, BrowserWindow, shell } = require('electron');
const path = require('path');
const url = require('url');
const http = require('http');
const fs = require('fs');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow () {
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow() {
// Create the browser window.
win = new BrowserWindow({ width: 395, height: 800, title: "Sengi", backgroundColor: '#FFF'});
win.loadURL("http://localhost:4200");
win.setMenu(null);
win = new BrowserWindow({ width: 395, height: 800, title: "Sengi", backgroundColor: '#FFF' });
// and load the index.html of the app.
// win.loadURL(url.format({
// pathname: path.join(__dirname, 'dist/index.html'),
// protocol: 'file:',
// slashes: true
// }))
var server = http.createServer(requestHandler).listen(9527);
win.loadURL('http://localhost:9527');
const template = [
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forcereload' },
{ type: 'separator' },
{ role: 'close' }
]
},
{
role: 'help',
submenu: [
{ role: 'toggledevtools' },
{
label: 'Open GitHub project',
click() { require('electron').shell.openExternal('https://github.com/NicolasConstant/sengi') }
}
]
}
]
const menu = Menu.buildFromTemplate(template);
win.setMenu(menu);
// Open the DevTools.
win.webContents.openDevTools()
// win.webContents.openDevTools()
//open external links to browser
win.webContents.on('new-window', function(event, url){
event.preventDefault();
shell.openExternal(url);
});
win.webContents.on('new-window', function (event, url) {
event.preventDefault();
shell.openExternal(url);
});
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
};
function requestHandler(req, res) {
var file = req.url == '/' ? '/index.html' : req.url,
root = __dirname + '/dist',
page404 = root + '/404.html';
if (file.includes('register') || file.includes('home')) file = '/index.html';
getFile((root + file), res, page404);
};
function getFile(filePath, res, page404) {
console.warn(`filePath: ${filePath}`)
fs.exists(filePath, function (exists) {
if (exists) {
fs.readFile(filePath, function (err, contents) {
if (!err) {
res.end(contents);
} else {
console.dir(err);
}
});
} else {
fs.readFile(page404, function (err, contents) {
if (!err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(contents);
} else {
console.dir(err);
}
});
}
});
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
app.quit()
}
})
app.on('activate', () => {
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
createWindow()
}
})
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

View File

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