Skip to content

Instantly share code, notes, and snippets.

@gryzzly
Created October 5, 2018 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gryzzly/7b30aa75578787ed00059cf44def7f4b to your computer and use it in GitHub Desktop.
Save gryzzly/7b30aa75578787ed00059cf44def7f4b to your computer and use it in GitHub Desktop.
Electron 3 + Facebook login with `webRequest.onBeforeRequest` instead of webContents `"did-get-redirect-request"`
ipcMain.on('facebook-sign-on', function onFacebookSignOn(
event,
repromptFacebook,
) {
const options = {
client_id: FACEBOOK_CLIENT_ID,
scope: 'public_profile,email',
redirect_uri: 'https://www.facebook.com/connect/login_success.html',
auth_type: repromptFacebook ? 'rerequest' : '',
};
if (authWindow) {
authWindow.webContents.focus();
} else {
authWindow = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: false,
},
});
}
function handleNavigation(address) {
const urlParts = url.parse(address);
if (urlParts.query) {
const urlParams = qs.parse(urlParts.query);
if (urlParams.error) {
const error = urlParams.error_code === '200'
? 'User pressed cancel'
: 'Error during auth';
mainWindow.webContents.executeJavaScript(`store.dispatch({
type: 'FACEBOOK_TOKEN_ERROR',
payload: {
error: '${error}'
},
})`);
authWindow.close();
}
}
if (urlParts.hash) {
const hashWithoutHashbang = urlParts.hash.slice(1);
const hashParams = qs.parse(hashWithoutHashbang);
const accessToken = hashParams.access_token;
if (accessToken) {
mainWindow.webContents.executeJavaScript(`store.dispatch({
type: 'FACEBOOK_TOKEN_RECEIVED',
token: '${accessToken}',
})`);
authWindow.close();
}
}
}
const facebookAuthURL =
'https://www.facebook.com/v2.8/dialog/oauth' +
`?client_id=${options.client_id}&redirect_uri=${options.redirect_uri}` +
`&response_type=token&scope=${options.scope}&display=popup` +
(repromptFacebook ? `&auth_type=${options.auth_type}` : '');
authWindow && authWindow.webContents.on(
'dom-ready',
function onAuthReady() {
authWindow.show();
}
);
authWindow && authWindow.on('closed', function onAuthWindowClose() {
authWindow = null;
});
// user has selected "cancel" in fb dialog
authWindow && authWindow.webContents.on(
'will-navigate',
function onAuthWindowWillNavigate(ev, newUrl) {
handleNavigation(newUrl);
}
);
// all new windows that facebook dialog might need to open should open
// in user’s default browser
authWindow.webContents.on(
'new-window',
function onAuthWindowNewWindow(ev, newWindowUrl) {
ev.preventDefault();
shell.openExternal(newWindowUrl);
}
);
// user already authenticated
session.defaultSession.webRequest.onBeforeRequest({
urls: ['https://www.facebook.com/connect/login_success.html']
}, function onBeforeRequest(details, callback) {
handleNavigation(details.url);
callback({ cancel: true });
});
authWindow.loadURL(facebookAuthURL);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment