Merge pull request #1 from NicolasConstant/topic-fix-electron-oauth
Topic fix electron oauth
This commit is contained in:
commit
690f57a5cf
132
main.js
132
main.js
|
@ -1,63 +1,121 @@
|
||||||
const {app, BrowserWindow, shell} = require('electron')
|
const { app, Menu, server, BrowserWindow, shell } = require('electron');
|
||||||
const path = require('path')
|
const path = require('path');
|
||||||
const url = require('url')
|
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
|
// 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.
|
// be closed automatically when the JavaScript object is garbage collected.
|
||||||
let win
|
let win
|
||||||
|
|
||||||
function createWindow () {
|
function createWindow() {
|
||||||
// Create the browser window.
|
// Create the browser window.
|
||||||
win = new BrowserWindow({ width: 395, height: 800, title: "Sengi", backgroundColor: '#FFF'});
|
win = new BrowserWindow({ width: 395, height: 800, title: "Sengi", backgroundColor: '#FFF' });
|
||||||
win.loadURL("http://localhost:4200");
|
|
||||||
win.setMenu(null);
|
|
||||||
|
|
||||||
// and load the index.html of the app.
|
var server = http.createServer(requestHandler).listen(9527);
|
||||||
// win.loadURL(url.format({
|
win.loadURL('http://localhost:9527');
|
||||||
// pathname: path.join(__dirname, 'dist/index.html'),
|
|
||||||
// protocol: 'file:',
|
|
||||||
// slashes: true
|
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.
|
// Open the DevTools.
|
||||||
win.webContents.openDevTools()
|
// win.webContents.openDevTools()
|
||||||
|
|
||||||
//open external links to browser
|
//open external links to browser
|
||||||
win.webContents.on('new-window', function(event, url){
|
win.webContents.on('new-window', function (event, url) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
shell.openExternal(url);
|
shell.openExternal(url);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Emitted when the window is closed.
|
// Emitted when the window is closed.
|
||||||
win.on('closed', () => {
|
win.on('closed', () => {
|
||||||
// Dereference the window object, usually you would store windows
|
// Dereference the window object, usually you would store windows
|
||||||
// in an array if your app supports multi windows, this is the time
|
// in an array if your app supports multi windows, this is the time
|
||||||
// when you should delete the corresponding element.
|
// when you should delete the corresponding element.
|
||||||
win = null
|
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.
|
function requestHandler(req, res) {
|
||||||
app.on('window-all-closed', () => {
|
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
|
// On macOS it is common for applications and their menu bar
|
||||||
// to stay active until the user quits explicitly with Cmd + Q
|
// to stay active until the user quits explicitly with Cmd + Q
|
||||||
if (process.platform !== 'darwin') {
|
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
|
// 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.
|
// dock icon is clicked and there are no other windows open.
|
||||||
if (win === null) {
|
if (win === null) {
|
||||||
createWindow()
|
createWindow()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// In this file you can include the rest of your app's specific main process
|
// 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.
|
// code. You can also put them in separate files and require them here.
|
||||||
|
|
|
@ -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) { }
|
||||||
}
|
}
|
Loading…
Reference in New Issue