Skip to content

Commit b2660f3

Browse files
committed
working on adding oauth
1 parent c1a919b commit b2660f3

File tree

4 files changed

+87
-35
lines changed

4 files changed

+87
-35
lines changed

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) => {

server/controllers/userController.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ const randomPassword = () => {
2323
password += getRandomLetter() + getRandomDigit() + getRandomSpecialChar();
2424
}
2525
return password;
26-
}
26+
};
2727

2828
userController.createUser = (req, res, next) => {
29-
29+
console.log('inside createUser');
3030
let email, username, password;
3131
// use this condition for Oauth login
3232
if (res.locals.signUpType === 'oauth') {
@@ -53,12 +53,14 @@ userController.createUser = (req, res, next) => {
5353
// handle error of creating a new user
5454
if (err) {
5555
if (res.locals.signUpType === 'oauth') {
56+
console.log('line 56 of userController'); // oauth enters this condition
5657
return next();
5758
}
5859
if (err.keyValue.email) {
5960
return res.status(400).json('Email Taken');
6061
}
6162
if (err.keyValue.username && res.locals.signUpType === 'oauth') {
63+
console.log('line 56 of userController');
6264
res.locals.githubPassword = password;
6365
return next();
6466
}
@@ -75,14 +77,17 @@ userController.createUser = (req, res, next) => {
7577
}
7678
// if no error found when creating a new user, send back user ID in res.locals
7779
res.locals.id = newUser.id;
80+
console.log('line 78 of userController');
7881
return next();
7982
});
8083
};
8184

8285
// verifyUser - Obtain username and password from the request body, locate
8386
// the appropriate user in the database, and then authenticate the submitted password against the password stored in the database.
8487
userController.verifyUser = (req, res, next) => {
88+
console.log('inside verifyUser');
8589
let { username, password, isFbOauth } = req.body;
90+
console.log(username, password, isFbOauth);
8691
// handle Oauth
8792
if (res.locals.signUpType === 'oauth') {
8893
username = res.locals.githubEmail;

server/server.js

Lines changed: 49 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const { ApolloServer } = require('apollo-server-express');
22
const express = require('express');
33
const cookieParser = require('cookie-parser');
44
const passport = require('passport');
5+
const GitHubStrategy = require('passport-github2').Strategy;
56

67
const path = require('path');
78
const cors = require('cors');
@@ -17,11 +18,10 @@ const isDev = process.env.NODE_ENV === 'development';
1718
const isProd = process.env.NODE_ENV === 'production';
1819
const isTest = process.env.NODE_ENV === 'test';
1920

20-
app.use(express.json({limit: '100mb'}));
21-
app.use(express.urlencoded({limit: '100mb', extended: true }))
21+
app.use(express.json({ limit: '100mb' }));
22+
app.use(express.urlencoded({ limit: '100mb', extended: true }));
2223
app.use(cookieParser());
2324

24-
2525
// Routes
2626
const stylesRouter = require('./routers/stylesRouter');
2727

@@ -30,18 +30,39 @@ const stylesRouter = require('./routers/stylesRouter');
3030
app.use(
3131
cors({
3232
origin: ['http://localhost:8080', 'app://rse'],
33-
credentials: true,
34-
}),
33+
credentials: true
34+
})
3535
);
3636

3737
// TODO: github Oauth still needs debugging
3838
// on initial login, redirect back to app is not working correctly when in production environment
3939
// subsequent logins seem to be working fine, however
4040

41+
passport.use(
42+
new GitHubStrategy(
43+
{
44+
clientID: process.env.GITHUB_ID,
45+
clientSecret: process.env.GITHUB_SECRET,
46+
callbackURL: 'http://localhost:5000/github/callback'
47+
},
48+
function(accessToken, refreshToken, profile, done) {
49+
console.log(profile);
50+
}
51+
)
52+
);
53+
4154
// initializes passport and passport sessions
4255
app.use(passport.initialize());
4356
app.use(passport.session());
4457

58+
app.get(
59+
'/auth/github',
60+
passport.authenticate('github', { session: false }),
61+
(req, res) => {
62+
res.send('github');
63+
}
64+
);
65+
4566
// for Oauth which is currently not working
4667
app.get(
4768
'/github/callback',
@@ -53,13 +74,22 @@ app.get(
5374
sessionController.startSession,
5475
(req, res) => {
5576
if (isDev) {
56-
return res.status(200).redirect(`http://localhost:8080?=${res.locals.ssid}`);
77+
return res
78+
.status(200)
79+
.redirect(`http://localhost:8080?=${res.locals.ssid}`);
5780
} else {
5881
return res.status(200).redirect(`app://rse?=${res.locals.ssid}`);
5982
}
6083
}
6184
);
6285

86+
// app.get('/github/callback', passport.authenticate('github'), function(
87+
// req,
88+
// res
89+
// ) {
90+
// console.log(req.user);
91+
// res.redirect('http://localhost:8080');
92+
// });
6393

6494
/*
6595
GraphQl Router
@@ -74,11 +104,13 @@ const Mutation = require('./graphQL/resolvers/mutation');
74104
// package resolvers into one variable to pass to Apollo Server
75105
const resolvers = {
76106
Query,
77-
Mutation,
107+
Mutation
78108
};
79109

80-
app.use('/demoRender', express.static(path.join(__dirname, './assets/renderDemo.css')));
81-
110+
app.use(
111+
'/demoRender',
112+
express.static(path.join(__dirname, './assets/renderDemo.css'))
113+
);
82114

83115
// Re-direct to route handlers:
84116
app.use('/user-styles', stylesRouter);
@@ -97,41 +129,41 @@ app.post(
97129
userController.createUser,
98130
cookieController.setSSIDCookie,
99131
sessionController.startSession,
100-
(req, res) => res.status(200).json({ sessionId: res.locals.ssid }),
132+
(req, res) => res.status(200).json({ sessionId: res.locals.ssid })
101133
);
102134

103135
app.post(
104136
'/login',
105137
userController.verifyUser,
106138
cookieController.setSSIDCookie,
107139
sessionController.startSession,
108-
(req, res) => res.status(200).json({ sessionId: res.locals.ssid }),
140+
(req, res) => res.status(200).json({ sessionId: res.locals.ssid })
109141
);
110142

111143
// user must be logged in to get or save projects, otherwise they will be redirected to login page
112144
app.post(
113145
'/saveProject',
114146
sessionController.isLoggedIn,
115147
projectController.saveProject,
116-
(req, res) => res.status(200).json(res.locals.savedProject),
148+
(req, res) => res.status(200).json(res.locals.savedProject)
117149
);
118150

119151
app.post(
120152
'/getProjects',
121153
sessionController.isLoggedIn,
122154
projectController.getProjects,
123-
(req, res) => res.status(200).json(res.locals.projects),
155+
(req, res) => res.status(200).json(res.locals.projects)
124156
);
125157

126158
app.delete(
127159
'/deleteProject',
128160
sessionController.isLoggedIn,
129161
projectController.deleteProject,
130-
(req, res) => res.status(200).json(res.locals.deleted),
162+
(req, res) => res.status(200).json(res.locals.deleted)
131163
);
132164

133-
app.get("/", function (req, res) {
134-
res.send("Houston, Caret is in orbit!");
165+
app.get('/', function(req, res) {
166+
res.send('Houston, Caret is in orbit!');
135167
});
136168

137169
// catch-all route handler
@@ -142,7 +174,7 @@ app.use((err, req, res, next) => {
142174
const defaultErr = {
143175
log: 'Express error handler caught unknown middleware',
144176
status: 500,
145-
message: { err: 'An error occurred' },
177+
message: { err: 'An error occurred' }
146178
};
147179

148180
const errorObj = Object.assign({}, defaultErr, err);

0 commit comments

Comments
 (0)