Exemple #1
0
export const auth = () => {
  let authWindow = new remote.BrowserWindow({
    width: 400,
    height: 650,
    show: true,
    frame: false,
    webPreferences: {
      nodeIntegration: false
    }
  });
  authWindow.loadURL(authUrl);
  authWindow.on('closed', () => {
    authWindow = null;
  });
  return new Promise((resolve, reject) => {
    authWindow.webContents.on('did-get-redirect-request', (evt, oldUrl, newUrl) => {
      if (newUrl.startsWith(redirectUri)) {
        const q = queryString.parse(newUrl.slice(newUrl.indexOf('?') + 1));
        authWindow.destroy();
        remote.session.defaultSession.clearStorageData({
          storages: ['cookies']
        }, () => {
          if (q.code) {
            resolve(requestToken({
              grant_type: 'authorization_code',
              code: q.code
            }));
          } else if (q.error) {
            reject(new Error(q.error));
          }
        });
      }
    });
  });
};
webView.addEventListener('new-window', function (event) {
  log('webview new-window', JSON.stringify(event));
  const url = urls.skipFacebookRedirect(event.url);
  event.preventDefault();

  // download url
  if (urls.isDownloadUrl(url)) {
    log('on webview new-window, downloading', url);
    webView.getWebContents().loadURL(url);
    return;
  }

  // open it externally (if preference is set)
  if (prefs.get('links-in-browser')) {
    log('on webview new-window, externally', url);
    shell.openExternal(url);
    return;
  }

  // otherwise open it in a new app window (unless it's an audio/video call)
  if (event.frameName !== 'Video Call' || event.url !== 'about:blank') {
    const options = {
      title: event.frameName || global.manifest.productName,
      darkTheme: global.manifest.darkThemes.includes(prefs.get('theme'))
    };
    log('on webview new-window, new window', url, options);
    const newWindow = new remote.BrowserWindow(options);
    newWindow.loadURL(url);
    event.newGuest = newWindow;
  }
});
Exemple #3
0
 it('works without script tag in page', function (done) {
   w = new BrowserWindow({show: false})
   ipcMain.once('pong', function () {
     done()
   })
   w.loadURL('file://' + fixtures + '/pages/webview-no-script.html')
 })
Exemple #4
0
    it('disables node integration when disabled on the parent BrowserWindow', function (done) {
      var b = undefined

      ipcMain.once('answer', function (event, typeofProcess) {
        try {
          assert.equal(typeofProcess, 'undefined')
          done()
        } finally {
          b.close()
        }
      })

      var windowUrl = require('url').format({
        pathname: `${fixtures}/pages/webview-no-node-integration-on-window.html`,
        protocol: 'file',
        query: {
          p: `${fixtures}/pages/web-view-log-process.html`
        },
        slashes: true
      })
      var preload = path.join(fixtures, 'module', 'answer.js')

      b = new BrowserWindow({
        height: 400,
        width: 400,
        show: false,
        webPreferences: {
          preload: preload,
          nodeIntegration: false,
        }
      })
      b.loadURL(windowUrl)
    })
 webview.addEventListener('new-window', (e) => {
     if (e.url.indexOf('bttvSettings') !== -1) {
         let bttvSettings = new remote.BrowserWindow({
             title: 'BetterTTV Settings',
             autoHideMenuBar: true,
             width: 810,
             height: 548,
             show: false,
             webPreferences: {
                 nodeIntegration: false,
                 webSecurity: false,
                 plugins: true,
                 partition: 'persist:twitch',
                 allowRunningInsecureContent: true,
                 preload: path.resolve(`${__dirname}/../../bttv/index.js`)
             }
         });
         bttvSettings.loadURL(e.url);
         bttvSettings.show();
         bttvSettings.openDevTools();
         bttvSettings.on('closed', () => {
             bttvSettings = null;
         });
     }
 });
Exemple #6
0
 .then(response => {
   let confirmationWindow = new BrowserWindow({ width: 800, height: 600, frame: false, alwaysOnTop: true }); //eslint-disable-line
   confirmationWindow.loadURL(response.data);
   confirmationWindow.on('closed', () => {
     confirmationWindow = null;
     axios({ method: 'post', url: `${authServerURL}/auth/login`, data: { url: data } })
     .then(loginResponse => {
       const { storeName, accessToken } = loginResponse.data;
       const writeToDisk = {
         storeName,
         accessToken
       };
       mergeObjects('userKeys', writeToDisk)
       .then(() => {
         if (data) resolve(dispatch(loginShopSucess(writeToDisk)));
         dispatch(fetchDataAction(accessToken, storeName));
       })
       .catch((err) => { if (err) reject(err); });
     })
     .catch(err => {
       if (err) dispatch(loginShopError(err));
       reject(err);
     });
   });
 });
 constructor() {
   let win = new BrowserWindow({width: 800, height: 600, show: false});
   win.on('closed', () => {
     win = null;
   });
   win.loadURL('https://www.youtube.com/watch?v=psJpUPfAJDY');
   win.show();
 }
Exemple #8
0
    $scope.submit = function() {

        $scope.isDisabled = true;

        var auth_uri = "https://slack.com/oauth/authorize?" +
            $.param({
                client_id: slack_client_id,
                scope: "client"
            });

        authWin = new BrowserWindow({width: 600, height: 750, title: "Authenticate"});
        authWin.loadURL(auth_uri);
        authWin.show();

        // catch redirections in the OAuth flow and stop em before they happen.
        function handleCallback(url) {
            var raw_code = /code=([^&]*)/.exec(url) || null;
            var code = (raw_code && raw_code.length > 1) ? raw_code[1] : null;
            var error = /\?error=(.+)$/.exec(url);

            if (code) {
                var oauth_uri = "https://slack.com/api/oauth.access?" +
                    $.param({
                        client_id: slack_client_id,
                        client_secret: slack_secret,
                        code: code
                    });

                $http({
                    method: 'GET',
                    url: oauth_uri
                }).then(function successCallback(res) {
                    Lockr.set(res.data.team_name, {token:res.data.access_token, name:res.data.team_name});
                    $scope.accounts = Lockr.getAll();
                });

                // go to next step!
            } else if (error) {
                alert('Oops! Something went wrong and we couldn\'t' +
                    'log you in using Slack. Please try again.');
            }

            // we did what we had to do, now close it
            if (code || error) {
                authWin.destroy();
            }
        }

        // TODO: What if user clicks cancel ?

        // Emitted when the window is closed.
        authWin.on('closed', () => authWin = null);

        // detect redirections and handle them
        authWin.webContents.on('will-navigate', function (event, url) {
            handleCallback(url);
        });
    }
Exemple #9
0
socket.on("electron-auth", (url, pathname) => {
	if (isElectron){
		var electron = require("electron").remote;
		var mainWindow = electron.getCurrentWindow();

		var window = new electron.BrowserWindow({
			title: "shows.js",
			width: 1000,
			height: 600,
			resizable: false,
			frame: false,
			show: false,
			backgroundColor: "#282b30",
			webPreferences: {
				nodeIntegration: false
			}
		});

		window.loadURL(url);

		window.webContents.on("did-get-redirect-request", (event) => {
			console.log(window.webContents.getURL());
		});

		window.webContents.on("did-finish-load", (event) => {
			var url = window.webContents.getURL();
			window.show();

			if (url.indexOf("https://discordapp.com/oauth2/authorize") == 0){
				window.webContents.executeJavaScript(`var interval = setInterval(() => {
					if (document.getElementsByTagName("footer").length > 0){
						clearInterval(interval);

						var button = document.createElement("button");
						var text = document.createTextNode("Logout");

						button.setAttribute("type", "button");
						button.appendChild(text);

						button.addEventListener("click", (event) => {
							localStorage.removeItem("token");
							window.location.reload();
						});

						var footer = document.getElementsByTagName("footer")[0];
						footer.insertBefore(button, footer.childNodes[0]);
						
						document.getElementsByTagName("footer")[0].childNodes[1].remove();
					}
				}, 50);`);
			} else if (url.indexOf("/electron_auth?code=") > -1){
				mainWindow.loadURL(url.replace("electron_auth", "authenticate") + "&electron=1&next=" + pathname);
				window.close();
			}
		});
	}
});
Exemple #10
0
 it('inherits the zoomFactor of the parent window', function (done) {
   w = new BrowserWindow({
     show: false,
     webPreferences: {
       zoomFactor: 1.2
     }
   })
   ipcMain.once('pong', function (event, zoomFactor, zoomLevel) {
     assert.equal(zoomFactor, 1.2)
     assert.equal(zoomLevel, 1)
     done()
   })
   w.loadURL('file://' + fixtures + '/pages/webview-zoom-factor.html')
 })
Exemple #11
0
export const openFileDialog = function () {
  dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), {
    properties: ['openFile']
  }, function (file) {
    if (file) openFile(file[0])
  })
}
Exemple #12
0
        saveItem: function () {
            this.editMode.enabled = !this.editMode.enabled;
            for (var i in this.todos) {
                if (!this.todos[i].text) {
                    this.todos[i].text = 'Nothing';
                }
                if (!this.todos[i].category) {
                    this.todos[i].category = this.categoryForNew;
                }
                if (!this.todos[i].remind_date) {
                    this.todos[i].remind_date = convertDate(new Date());
                }
                if (!this.todos[i].remind_time) {
                    this.todos[i].remind_time = '00:00';
                }
            }
            loadTodosToSettings();
            updateAppSettings();

            if (windowMustBeHidden) {
                windowMustBeHidden = false;
                const { remote } = require('electron');
                remote.BrowserWindow.getFocusedWindow().minimize();
            }

        },
 $(document).on('click', "#screen-edit #button-ok", function () {
     var title = $("#screen-edit #title").val().trim();
     var body = $("#screen-edit #body").val().trim();
     if (body == '' && !vmPasswordsEditWidget.passwords.length) {
         alert('Field Body is required.');
         return;
     }
     if (!validatePasswordsEditWidget()) {
         alert('Incorrect passwords data!');
         return;
     }
     if (title == '') {
         var prefix = '#untitled ';
         if (addingFromClipboard) {
             prefix = '#clipboard ';
             addingFromClipboard = false;
         }
         title = prefix + body.substr(0, 30)+'...'.trim();
     }
     if ($("#screen-edit").attr('data-id') === undefined) {
         addNote(title, body);
     } else {
         updateNote($("#screen-edit").attr('data-id'), title, body);
     }
     if (windowMustBeHidden) {
         windowMustBeHidden = false;
         const { remote } = require('electron');
         remote.BrowserWindow.getFocusedWindow().minimize();
     }
     editorDataModified = false;
     displayEditorSaveButton();
     settings.last_editing_note_id = $("#screen-edit").attr('data-id');
 });
Exemple #14
0
        // catch redirections in the OAuth flow and stop em before they happen.
        function handleCallback(url) {
            var raw_code = /code=([^&]*)/.exec(url) || null;
            var code = (raw_code && raw_code.length > 1) ? raw_code[1] : null;
            var error = /\?error=(.+)$/.exec(url);

            if (code) {
                var oauth_uri = "https://slack.com/api/oauth.access?" +
                    $.param({
                        client_id: slack_client_id,
                        client_secret: slack_secret,
                        code: code
                    });

                $http({
                    method: 'GET',
                    url: oauth_uri
                }).then(function successCallback(res) {
                    Lockr.set(res.data.team_name, {token:res.data.access_token, name:res.data.team_name});
                    $scope.accounts = Lockr.getAll();
                });

                // go to next step!
            } else if (error) {
                alert('Oops! Something went wrong and we couldn\'t' +
                    'log you in using Slack. Please try again.');
            }

            // we did what we had to do, now close it
            if (code || error) {
                authWin.destroy();
            }
        }
Exemple #15
0
 it('is disabled when nodeIntegration is disabled', function (done) {
   w = new BrowserWindow({
     show: false,
     webPreferences: {
       nodeIntegration: false,
       preload: path.join(fixtures, 'module', 'preload-webview.js')
     },
   })
   ipcMain.once('webview', function (event, type) {
     if (type === 'undefined') {
       done()
     } else {
       done('WebView still exists')
     }
   })
   w.loadURL('file://' + fixtures + '/pages/webview-no-script.html')
 })
Exemple #16
0
        cancelChanges: function (index) {
            this.editMode.enabled = false;
            loadTodosFromSettings(index);

            if (windowMustBeHidden) {
                windowMustBeHidden = false;
                const { remote } = require('electron');
                remote.BrowserWindow.getFocusedWindow().minimize();
            }
        },
Exemple #17
0
 bw.capturePage(function (img) {
     var data = img.toDataURL()
     fs.writeFile('/tmp/img.png', img.toPng())
     console.log(data)
     d3.select('#preview')
         .append('img')
         .attr('src', data)
         .style('border', '1px solid #000000')
     bw.close()
 })
Exemple #18
0
  const createWindow = URL => {
    let win = new BrowserWindow({
      backgroundColor: '#282c34',
      width: 570,
      height: 700,
      show: false,
      nodeIntegration: true
    })
    win.loadURL(URL)

    win.on('ready-to-show', () => {
      win.show()
      win.focus()
    })

    win.on('closed', () => {
      win = null
    })
  }
Exemple #19
0
 const windowIsOpen = URL => {
   let isWindowActive = false
   const activeWins = BrowserWindow.getAllWindows()
   Object.values(activeWins).map(activeWin => {
     if (activeWin.getURL() === URL) {
       isWindowActive = true
     }
   })
   if (isWindowActive === false) createWindow(URL)
 }
Exemple #20
0
  it('loads devtools extensions registered on the parent window', function (done) {
    this.timeout(10000)

    w = new BrowserWindow({
      show: false
    })

    BrowserWindow.removeDevToolsExtension('foo')

    var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
    BrowserWindow.addDevToolsExtension(extensionPath)

    w.loadURL('file://' + fixtures + '/pages/webview-devtools.html')

    ipcMain.once('answer', function (event, message) {
      assert.equal(message.runtimeId, 'foo')
      assert.notEqual(message.tabId, w.webContents.id)
      done()
    })
  })
Exemple #21
0
  it('inherits the parent window visibility state and receives visibilitychange events', function (done) {
    w = new BrowserWindow({
      show: false
    })

    ipcMain.once('pong', function (event, visibilityState, hidden) {
      assert.equal(visibilityState, 'hidden')
      assert.equal(hidden, true)

      w.webContents.send('ELECTRON_RENDERER_WINDOW_VISIBILITY_CHANGE', 'visible')

      ipcMain.once('pong', function (event, visibilityState, hidden) {
        assert.equal(visibilityState, 'visible')
        assert.equal(hidden, false)
        done()
      })
    })

    w.loadURL('file://' + fixtures + '/pages/webview-visibilitychange.html')
  })
Exemple #22
0
const createWindow = URL => {
  let win = new BrowserWindow({
    backgroundColor: '#282c34',
    width: 900,
    height: 700,
    show: false,
    webPreferences: {
      nodeIntegration: false
    }
  })
  win.loadURL(`${finalPath}/${URL}`)

  win.on('ready-to-show', () => {
    win.show()
    win.focus()
  })

  win.on('closed', () => {
    win = null
  })
}
Exemple #23
0
export const saveFileDialog = function (contents) {
  dialog.showSaveDialog(BrowserWindow.getFocusedWindow(), {defaultPath: store.state.currentDirectory, extensions: ['.md']}, function (fileName) {
    // No file name if we cancel the dialog
    if (fileName === undefined) return
    // If we don't specify a file extension, assign it as a markdown file
    if (fileName.split('.').length <= 1) fileName += '.md'

    store.setCurrentFile(fileName)
    store.setCurrentDirectory(fileName.split('/').slice(0, -1).join('/'))
    saveFile(fileName, contents)
  })
}
 Mousetrap.bind('esc', () => {
   if (state.reading) {
     bus.emit('reader:quit')
   } else if (state.datasources.shown) {
     bus.emit('datasources:toggle-shown')
   } else if (state.aboutshown) {
     bus.emit('about:hide')
   } else {
     const win = BrowserWindow.getFocusedWindow()
     win.setFullScreen(false)
   }
 })
Exemple #25
0
const metamodelIsActive = URL => {
  let isWindowActive = false
  const activeWins = BrowserWindow.getAllWindows()
  Object.values(activeWins).map(activeWin => {
    if (activeWin.getURL() === `${finalPath}/${URL}`) {
      isWindowActive = true
      if (activeWin.isMinimized() === true) {
        activeWin.restore()
      }
    }
  })
  if (isWindowActive === false) {
    createWindow(URL)
  }
}
Exemple #26
0
 authWindow.webContents.on('did-get-redirect-request', (evt, oldUrl, newUrl) => {
   if (newUrl.startsWith(redirectUri)) {
     const q = queryString.parse(newUrl.slice(newUrl.indexOf('?') + 1));
     authWindow.destroy();
     remote.session.defaultSession.clearStorageData({
       storages: ['cookies']
     }, () => {
       if (q.code) {
         resolve(requestToken({
           grant_type: 'authorization_code',
           code: q.code
         }));
       } else if (q.error) {
         reject(new Error(q.error));
       }
     });
   }
 });
Exemple #27
0
/* global angular */

'use strict';

require('angular');
require('angular-ui-router');
require('angular-animate');
require('angular-aria');
require('angular-messages');
require('angular-material');
require('angular-material-data-table');

const Highcharts = require('highcharts');
const { BrowserWindow, ipcRenderer, dialog } = require('electron').remote;
const focusedWindow = BrowserWindow.getFocusedWindow();

let moment = require('moment');


require('highcharts/themes/grid');
require('./node_modules/highcharts-ng/dist/highcharts-ng.js');

angular.module('app', [
  'ngMaterial', 'ui.router', 'md.data.table', 'highcharts-ng',
  'app.config.Configure',
  'app.config.Connection',
  'app.controllers.Main',
  'app.controllers.App',
  'app.controllers.Toolbar',
  'app.controllers.Emr'
])
Exemple #28
0
import config from 'config';

const { BrowserWindow } = require('electron').remote;

export default {
    expand() {
        this._resize(config.maxSize.width, config.maxSize.height);
    },

    collapse() {
        this._resize(config.minSize.width, config.minSize.height);
    },

    _resize(width, height) {
        BrowserWindow.getFocusedWindow().setSize(width, height);
    }
};
Exemple #29
0
 win.on('ready-to-show', () => {
   win.show()
   win.focus()
 })
Exemple #30
0
export function dispatchPublishGist(
  ownProps: { contentRef: ContentRef },
  store: Store<DesktopNotebookAppState, *>,
  event: Event
) {
  const state = store.getState();
  let githubToken = state.app.get("githubToken");

  // The simple case -- we have a token and can publish
  if (githubToken != null) {
    store.dispatch(actions.publishGist(ownProps));
    return;
  }

  // If the Github Token isn't set, use our oauth server to acquire a token

  // Because the remote object from Electron main <--> renderer can be "cleaned up"
  // we re-require electron here and get the remote object
  const remote = require("electron").remote;

  // Create our oauth window
  const win = new remote.BrowserWindow({
    show: false,
    webPreferences: { zoomFactor: 0.75 }
  });

  // TODO: This needs to be moved to an epic
  win.webContents.on("dom-ready", () => {
    // When we're at our callback code page, keep the page hidden
    if (win.getURL().indexOf("callback?code=") !== -1) {
      // Extract the text content
      win.webContents.executeJavaScript(
        `require('electron').ipcRenderer.send('auth', document.body.textContent);`
      );
      remote.ipcMain.on("auth", (event, auth) => {
        try {
          const accessToken = JSON.parse(auth).access_token;
          store.dispatch(actions.setGithubToken(accessToken));

          const notificationSystem = selectors.notificationSystem(state);

          notificationSystem.addNotification({
            title: "Authenticated",
            message: `🔒`,
            level: "info"
          });

          // We are now authenticated and can finally publish
          store.dispatch(actions.publishGist(ownProps));
        } catch (e) {
          store.dispatch(actions.coreError(e));
        } finally {
          win.close();
        }
      });
    } else {
      win.show();
    }
  });
  win.loadURL("https://oauth.nteract.io/github");
}