Skip to content

Commit 3110550

Browse files
authored
Merge pull request #6 from oslabs-beta/renderNextjs
Fixed bug exit bug & fixed GitHub OAuth
2 parents 08e5ada + c1f34e3 commit 3110550

File tree

7 files changed

+128
-72
lines changed

7 files changed

+128
-72
lines changed

app/electron/main.js

Lines changed: 35 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const {
1212
dialog,
1313
BrowserWindow,
1414
session,
15-
ipcMain,
15+
ipcMain
1616
} = require('electron');
1717
// The splash screen is what appears while the app is loading
1818
// const { initSplashScreen, OfficeTemplate } = require('electron-splashscreen');
@@ -21,7 +21,7 @@ const { resolve } = require('app-root-path');
2121
// to install react dev tool extension
2222
const {
2323
default: installExtension,
24-
REACT_DEVELOPER_TOOLS,
24+
REACT_DEVELOPER_TOOLS
2525
} = require('electron-devtools-installer');
2626
const debug = require('electron-debug');
2727

@@ -31,7 +31,8 @@ const Protocol = require('./protocol');
3131
const MenuBuilder = require('./menu');
3232

3333
// mode that the app is running in
34-
const isDev = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';
34+
const isDev =
35+
process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';
3536
const port = 8080;
3637
const selfHost = `http://localhost:${port}`;
3738

@@ -44,9 +45,9 @@ let menuBuilder;
4445
// this function will be called when Electron has initialized itself
4546
async function createWindow() {
4647
// install react dev tools if we are in development mode
47-
// this will happen before creating the browser window. it returns a Boolean whether the protocol of scheme 'app://' was successfully registered and a file (index-prod.html) was sent as the response
48-
protocol.registerBufferProtocol(Protocol.scheme, Protocol.requestHandler);
49-
48+
// this will happen before creating the browser window. it returns a Boolean whether the protocol of scheme 'app://' was successfully registered and a file (index-prod.html) was sent as the response
49+
protocol.registerBufferProtocol(Protocol.scheme, Protocol.requestHandler);
50+
5051
// Create the browser window.
5152
win = new BrowserWindow({
5253
// full screen
@@ -61,7 +62,7 @@ async function createWindow() {
6162
show: false,
6263
webPreferences: {
6364
zoomFactor: 0.7,
64-
// enable devtools when in development mode
65+
// enable devtools when in development mode
6566
devTools: true,
6667
// crucial security feature - blocks rendering process from having access to node modules
6768
nodeIntegration: false,
@@ -77,8 +78,8 @@ async function createWindow() {
7778
enableRemoteModule: false,
7879
// path of preload script. preload is how the renderer page will have access to electron functionality
7980
preload: path.join(__dirname, 'preload.js'),
80-
nativeWindowOpen: true,
81-
},
81+
nativeWindowOpen: true
82+
}
8283
});
8384

8485
// Splash screen that appears while loading
@@ -118,12 +119,12 @@ async function createWindow() {
118119
});
119120
}
120121

121-
// Emitted when the window is closed.
122+
// Emitted when the window is closed.
122123
win.on('closed', () => {
123124
// Dereference the window object, usually you would store windows
124125
// in an array if your app supports multi windows, this is the time
125126
// when you should delete the corresponding element.
126-
win = null;
127+
app.quit();
127128
});
128129

129130
menuBuilder = MenuBuilder(win, 'ReacType');
@@ -145,7 +146,7 @@ async function createWindow() {
145146
callback(true); // Approve permission request
146147
} else {
147148
console.error(
148-
`The application tried to request permission for '${permission}'. This permission was not whitelisted and has been blocked.`,
149+
`The application tried to request permission for '${permission}'. This permission was not whitelisted and has been blocked.`
149150
);
150151

151152
callback(false); // Deny
@@ -157,10 +158,10 @@ async function createWindow() {
157158
// we could use this over _all_ urls
158159
ses
159160
.fromPartition(partition)
160-
.webRequest.onBeforeRequest({ urls: ['http://localhost./*'] }, (listener) => {
161+
.webRequest.onBeforeRequest({ urls: ['http://localhost./*'] }, listener => {
161162
if (listener.url.indexOf('http://') >= 0) {
162163
listener.callback({
163-
cancel: true,
164+
cancel: true
164165
});
165166
}
166167
});
@@ -177,9 +178,9 @@ protocol.registerSchemesAsPrivileged([
177178
standard: true,
178179
secure: true,
179180
allowServiceWorkers: true,
180-
supportFetchAPI: true,
181-
},
182-
},
181+
supportFetchAPI: true
182+
}
183+
}
183184
]);
184185

185186
// This method will be called when Electron has finished
@@ -219,12 +220,12 @@ app.on('web-contents-created', (event, contents) => {
219220
'https://www.facebook.com',
220221
'https://developer.mozilla.org',
221222
'https://www.smashingmagazine.com',
222-
'https://www.html5rocks.com',
223+
'https://www.html5rocks.com'
223224
];
224225
// Log and prevent the app from navigating to a new page if that page's origin is not whitelisted
225226
if (!validOrigins.includes(parsedUrl.origin)) {
226227
console.error(
227-
`The application tried to navigate to the following address: '${parsedUrl}'. This origin is not whitelisted attempt to navigate was blocked.`,
228+
`The application tried to navigate to the following address: '${parsedUrl}'. This origin is not whitelisted attempt to navigate was blocked.`
228229
);
229230
// if the requested URL is not in the whitelisted array, then don't navigate there
230231
event.preventDefault();
@@ -248,11 +249,11 @@ app.on('web-contents-created', (event, contents) => {
248249
];
249250
// Log and prevent the app from redirecting to a new page
250251
if (
251-
!validOrigins.includes(parsedUrl.origin)
252-
&& !validOrigins.includes(parsedUrl.href)
252+
!validOrigins.includes(parsedUrl.origin) &&
253+
!validOrigins.includes(parsedUrl.href)
253254
) {
254255
console.error(
255-
`The application tried to redirect to the following address: '${navigationUrl}'. This attempt was blocked.`,
256+
`The application tried to redirect to the following address: '${navigationUrl}'. This attempt was blocked.`
256257
);
257258

258259
event.preventDefault();
@@ -286,12 +287,12 @@ app.on('web-contents-created', (event, contents) => {
286287
'https://github.com',
287288
'https://www.facebook.com',
288289
'https://www.smashingmagazine.com',
289-
'https://www.html5rocks.com',
290+
'https://www.html5rocks.com'
290291
];
291292
// Log and prevent the app from navigating to a new page if that page's origin is not whitelisted
292293
if (!validOrigins.includes(parsedUrl.origin)) {
293294
console.error(
294-
`The application tried to open a new window at the following address: '${navigationUrl}'. This attempt was blocked.`,
295+
`The application tried to open a new window at the following address: '${navigationUrl}'. This attempt was blocked.`
295296
);
296297
// if the requested URL is not in the whitelisted array, then don't navigate there
297298
event.preventDefault();
@@ -326,15 +327,15 @@ app.on('remote-get-current-web-contents', (event, webContents) => {
326327
// When a user selects "Export project", a function (chooseAppDir loaded via preload.js)
327328
// is triggered that sends a "choose_app_dir" message to the main process
328329
// when the "choose_app_dir" message is received it triggers this event listener
329-
ipcMain.on('choose_app_dir', (event) => {
330+
ipcMain.on('choose_app_dir', event => {
330331
// dialog displays the native system's dialogue for selecting files
331332
// once a directory is chosen send a message back to the renderer with the path of the directory
332333
dialog
333334
.showOpenDialog(win, {
334335
properties: ['openDirectory'],
335-
buttonLabel: 'Export',
336+
buttonLabel: 'Export'
336337
})
337-
.then((directory) => {
338+
.then(directory => {
338339
if (!directory) return;
339340
event.sender.send('app_dir_selected', directory.filePaths[0]);
340341
})
@@ -374,8 +375,8 @@ ipcMain.on('delete_cookie', event => {
374375

375376
// opens new window for github oauth when button on sign in page is clicked
376377
ipcMain.on('github', event => {
377-
// your applications credentials
378-
const githubUrl = 'https://github.com/login/oauth/authorize?';
378+
console.log('inside main.js in electron');
379+
const githubURL = 'http://localhost:5000/auth/github';
379380
const options = {
380381
client_id: process.env.GITHUB_ID,
381382
client_secret: process.env.GITHUB_SECRET,
@@ -395,8 +396,8 @@ ipcMain.on('github', event => {
395396
zoomFactor: 1.0
396397
}
397398
});
398-
const authUrl = `${githubUrl}client_id=${process.env.GITHUB_ID}`;
399-
github.loadURL(authUrl);
399+
400+
github.loadURL(githubURL);
400401
github.show();
401402
const handleCallback = url => {
402403
const raw_code = /code=([^&]\*)/.exec(url) || null;
@@ -441,6 +442,9 @@ ipcMain.on('github', event => {
441442
if (isDev) {
442443
redirectUrl = 'http://localhost:8080/';
443444
}
445+
console.log(callbackUrl === redirectUrl);
446+
console.log('callbackUrl', callbackUrl);
447+
console.log('redirectUrl', redirectUrl);
444448
if (callbackUrl === redirectUrl) {
445449
dialog.showMessageBox({
446450
type: 'info',

app/src/components/login/SignIn.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,10 @@ const SignIn: React.FC<LoginInt & RouteComponentProps> = props => {
6666
const [invalidUser, setInvalidUser] = useState(false);
6767
const [invalidPass, setInvalidPass] = useState(false);
6868

69-
7069
useEffect(() => {
7170
const githubCookie = setInterval(() => {
72-
window.api.setCookie();
73-
window.api.getCookie(cookie => {
71+
window.api?.setCookie();
72+
window.api?.getCookie(cookie => {
7473
// if a cookie exists, set localstorage item with cookie data, clear interval, go back to '/' route to load app
7574
if (cookie[0]) {
7675
window.localStorage.setItem('ssid', cookie[0].value);
@@ -80,7 +79,7 @@ const SignIn: React.FC<LoginInt & RouteComponentProps> = props => {
8079
} else if (window.localStorage.getItem('ssid')) {
8180
clearInterval(githubCookie);
8281
}
83-
});
82+
});
8483
}, 2000);
8584
}, []);
8685

@@ -157,6 +156,7 @@ const SignIn: React.FC<LoginInt & RouteComponentProps> = props => {
157156
e: React.MouseEvent<HTMLButtonElement, MouseEvent>
158157
) => {
159158
e.preventDefault();
159+
console.log('window api', window.api);
160160
window.api.github();
161161
props.history.push('/');
162162
}

app/src/components/right/LoginButton.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ export default function LoginButton() {
1212
e.preventDefault();
1313
// clear local storage
1414
window.localStorage.clear();
15+
// destroy cookie in production via electron main process
16+
window.api.delCookie();
1517
// destroys cookie by backdating expiration time
1618
// document.cookie = 'ssid=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
17-
// destroy cookie in production via electron main process
18-
// window.api.delCookie();
1919
// uses useHistory to return to the login page
2020
history.push('/login');
2121
};

server/controllers/cookieController.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const cookieController = {};
22

33
// setSSIDCookie - store the user id from database in cookie
44
cookieController.setSSIDCookie = (req, res, next) => {
5+
console.log('inside setSSIDCookie');
56
// set cookie with key 'ssid' and value to user's id
67
res.cookie('ssid', res.locals.id, {
78
httpOnly: true,

server/controllers/sessionController.js

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const fetch = require ('node-fetch');
1+
const fetch = require('node-fetch');
22

33
require('dotenv').config();
44
const { Sessions } = require('../models/reactypeModels');
@@ -33,14 +33,15 @@ sessionController.isLoggedIn = (req, res, next) => {
3333

3434
// startSession - create and save a new session into the database
3535
sessionController.startSession = (req, res, next) => {
36+
console.log('inside startSession');
3637
// first check if user is logged in already
3738
Sessions.findOne({ cookieId: res.locals.id }, (err, ses) => {
3839
if (err) {
3940
return next({
4041
log: `Error in sessionController.startSession find session: ${err}`,
4142
message: {
4243
err:
43-
'Error in sessionController.startSession find session, check server logs for details'
44+
'Error in sessionController.startSession find session, check server logs for details'
4445
}
4546
});
4647
// if session doesn't exist, create a session
@@ -58,7 +59,7 @@ sessionController.startSession = (req, res, next) => {
5859
});
5960
}
6061
res.locals.ssid = session.cookieId;
61-
return next();
62+
// return next();
6263
});
6364
// if session exists, move onto next middleware
6465
} else {
@@ -69,14 +70,19 @@ sessionController.startSession = (req, res, next) => {
6970
};
7071

7172
sessionController.gitHubResponse = (req, res, next) => {
73+
console.log('inside gitHubResponse');
7274
const { code } = req.query;
73-
if (!code)
75+
if (!code) {
76+
console.log('code not found');
7477
return next({
7578
log: 'Undefined or no code received from github.com',
7679
message: 'Undefined or no code received from github.com',
7780
status: 400
7881
});
79-
fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}&code=${code}`, {
82+
}
83+
fetch(
84+
`https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}&code=${code}`,
85+
{
8086
method: 'POST',
8187
headers: {
8288
accept: 'application/json',
@@ -85,22 +91,23 @@ sessionController.gitHubResponse = (req, res, next) => {
8591
body: JSON.stringify({
8692
client_id: process.env.GITHUB_ID,
8793
client_secret: process.env.GITHUB_SECRET,
88-
code
94+
code: code
8995
})
96+
}
97+
)
98+
.then(res => res.json())
99+
.then(token => {
100+
console.log('token:', token);
101+
res.locals.token = token['access_token'];
102+
return next();
90103
})
91-
.then(res => res.json())
92-
.then(token => {
93-
res.locals.token = token['access_token'];
94-
return next();
95-
})
96-
.catch(err => {
97-
res.status(500).json({ message: `${err.message} in gitHubResponse` })
98-
}
99-
);
100-
104+
.catch(err => {
105+
res.status(500).json({ message: `${err.message} in gitHubResponse` });
106+
});
101107
};
102108

103109
sessionController.gitHubSendToken = (req, res, next) => {
110+
console.log('inside gitHubSendToken');
104111
const { token } = res.locals;
105112
fetch(`https://api.github.com/user/public_emails`, {
106113
method: 'GET',
@@ -113,6 +120,12 @@ sessionController.gitHubSendToken = (req, res, next) => {
113120
.then(data => {
114121
res.locals.githubEmail = data[0]['email'];
115122
res.locals.signUpType = 'oauth';
123+
console.log(
124+
'github email:',
125+
res.locals.githubEmail,
126+
'signup type:',
127+
res.locals.signUpType
128+
);
116129
return next();
117130
})
118131
.catch(err => {
@@ -130,6 +143,7 @@ sessionController.gitHubSendToken = (req, res, next) => {
130143

131144
// creates a session when logging in with github
132145
sessionController.githubSession = (req, res, next) => {
146+
console.log('inside gitHubSession');
133147
// req.user is passed in from passport js -> serializeuser/deserializeuser
134148
const cookieId = req.user._id;
135149
Sessions.findOne({ cookieId }, (err, session) => {

0 commit comments

Comments
 (0)