Skip to content

Commit 2cf0aae

Browse files
committed
Github and Google Oauth
1 parent 5b5ebcc commit 2cf0aae

File tree

9 files changed

+170
-31
lines changed

9 files changed

+170
-31
lines changed

app/src/components/login/SignIn.tsx

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,8 @@ const SignIn: React.FC<LoginInt & RouteComponentProps> = props => {
172172
e: React.MouseEvent<HTMLButtonElement, MouseEvent>
173173
) => {
174174
e.preventDefault();
175-
window.api.github();
176-
props.history.push('/');
175+
// window.api.github();
176+
window.location.assign('http://localhost:5656/auth/github');
177177
}
178178
const responseFacebook = response => {
179179
if (response.accessToken) {
@@ -284,6 +284,18 @@ const SignIn: React.FC<LoginInt & RouteComponentProps> = props => {
284284
>
285285
Sign In With Github
286286
</Button>
287+
<Button
288+
fullWidth
289+
variant="contained"
290+
color="primary"
291+
id="SignInWithGoogle"
292+
onClick={(e)=>{
293+
e.preventDefault();
294+
window.location.assign('http://localhost:5656/auth/google');
295+
}}
296+
>
297+
Sign in With Google
298+
</Button>
287299
<Button
288300
fullWidth
289301
variant="contained"

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@
158158
"esbuild-wasm": "^0.14.51",
159159
"eslint-plugin-react-hooks": "^4.6.0",
160160
"express-graphql": "^0.12.0",
161+
"express-session": "^1.17.3",
161162
"fs": "^0.0.1-security",
162163
"graphql": "^15.8.0",
163164
"identity-obj-proxy": "^3.0.0",
@@ -169,6 +170,7 @@
169170
"node-fetch": "^2.6.1",
170171
"passport": "^0.6.0",
171172
"passport-github2": "^0.1.12",
173+
"passport-google-oauth20": "^2.0.0",
172174
"prettier": "^2.7.1",
173175
"prop-types": "^15.8.1",
174176
"radium": "^0.26.2",

server/controllers/sessionController.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ sessionController.gitHubSendToken = (req, res, next) => {
140140
// creates a session when logging in with github
141141
sessionController.githubSession = (req, res, next) => {
142142
// req.user is passed in from passport js -> serializeuser/deserializeuser
143-
const cookieId = req.user._id;
143+
const cookieId = req.user.id;
144144
Sessions.findOne({ cookieId }, (err, session) => {
145145
if (err) {
146146
return next({

server/models/Oauth-model.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const mongoose = require('mongoose');
2+
const Schema = mongoose.Schema
3+
4+
const userSchema = new Schema({
5+
username: { type: String },
6+
githubId: { type: String, unique: true },
7+
googleId: { type: String, unique: true }
8+
})
9+
10+
const User = mongoose.model('user', userSchema)
11+
12+
module.exports = User;

server/models/reactypeModels.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
const mongoose = require('mongoose');
1212
const bcrypt = require('bcryptjs');
1313
require('dotenv').config();
14-
const mongoURI = process.env.MONGO_DB_DEV;
14+
const mongoURI = 'mongodb+srv://Yoheze:[email protected]/?retryWrites=true&w=majority';
1515
const URI =
16-
process.env.NODE_ENV === 'production' ? mongoURI : process.env.MONGO_DB_DEV;
16+
process.env.NODE_ENV === 'production' ? mongoURI : 'mongodb+srv://Yoheze:[email protected]/?retryWrites=true&w=majority';
1717

1818
const SALT_WORK_FACTOR = 10;
1919
// connect to mongo db

server/routers/auth.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const router = require('express').Router();
2+
const passport = require('passport');
3+
4+
router.get(
5+
'/github',
6+
passport.authenticate('github', {
7+
scope: ['profile']
8+
})
9+
);
10+
11+
router.get(
12+
'/github/callback',
13+
passport.authenticate('github'),
14+
(req, res) => {
15+
console.log('this authenticate function is being run')
16+
console.log(req.user.id)
17+
res.cookie('ssid', req.user.id)
18+
return res.redirect('http://localhost:8080')
19+
})
20+
21+
router.get('/google', passport.authenticate('google', {
22+
scope: ['profile']
23+
}))
24+
25+
router.get('/google/callback', passport.authenticate('google'), (req, res) => {
26+
console.log('google authenicate function being run')
27+
res.cookie('ssid', req.user.id)
28+
return res.redirect('http://localhost:8080')
29+
})
30+
31+
module.exports = router;

server/routers/passport-setup.js

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
const passport = require('passport');
2+
const GitHubStrategy = require('passport-github2').Strategy
3+
const user = require('../models/Oauth-model');
4+
const GoogleStrategy = require('passport-google-oauth20')
5+
6+
passport.serializeUser((user, done) => {
7+
done(null, user.id)
8+
})
9+
10+
passport.deserializeUser((id, done) => {
11+
user.findById(id)
12+
.then(user=>{
13+
done(null, user)
14+
})
15+
})
16+
17+
passport.use(
18+
new GitHubStrategy(
19+
{
20+
clientID: 'c8e71b09f18a095c4c1e',
21+
clientSecret: '075c7b27061ccecd9258258e1d3749423309afa3',
22+
callbackURL: `http://localhost:5656/auth/github/callback`
23+
},
24+
function(accessToken, refreshToken, profile, done) {
25+
console.log(profile);
26+
user.findOne({
27+
githubId: profile.id
28+
})
29+
.then(currentUser => {
30+
if (currentUser) {
31+
console.log('user is: ', currentUser)
32+
return done(null, currentUser)
33+
} else {
34+
user.create({
35+
username: profile.displayName+'(Github)',
36+
githubId: profile.id
37+
})
38+
.then(data=>{
39+
console.log('user added successfully: ', data);
40+
return done(null, data)
41+
})
42+
.catch(data=>console.log('issue with adding user to database', data))
43+
}
44+
})
45+
}
46+
)
47+
);
48+
49+
passport.use(
50+
new GoogleStrategy(
51+
{
52+
clientID: '374131547814-d5umgbo4d5ftof4ctk2h1rfvn5v3jr10.apps.googleusercontent.com',
53+
clientSecret: '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',
54+
callbackURL: `http://localhost:5656/auth/google/callback`
55+
},
56+
function(accessToken, refreshToken, profile, done) {
57+
console.log(profile);
58+
user.findOne({
59+
googleId: profile.id
60+
})
61+
.then(currentUser => {
62+
if (currentUser) {
63+
console.log('user is: ', currentUser)
64+
return done(null, currentUser)
65+
} else {
66+
user.create({
67+
username: profile.displayName+'(Google)',
68+
googleId: profile.id
69+
})
70+
.then(data=>{
71+
console.log('user added successfully: ', data);
72+
return done(null, data)
73+
})
74+
.catch(data=>console.log('issue with adding user to database', data))
75+
}
76+
})
77+
}
78+
)
79+
);

server/server.js

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
const { ApolloServer } = require('apollo-server-express');
22
const express = require('express');
33
const cookieParser = require('cookie-parser');
4-
//const passport = require('passport');
5-
//const GitHubStrategy = require('passport-github2').Strategy;
4+
const passport = require('passport');
5+
const GitHubStrategy = require('passport-github2').Strategy;
66
const { DEV_PORT } = require('../config');
7+
const passportSetup = require('./routers/passport-setup.js')
78

89
const path = require('path');
910
const cors = require('cors');
1011
const userController = require('./controllers/userController');
1112
const cookieController = require('./controllers/cookieController');
1213
const sessionController = require('./controllers/sessionController');
1314
const projectController = require('./controllers/projectController');
15+
const mongoose = require('mongoose')
1416

1517
const app = express();
1618

@@ -41,32 +43,23 @@ app.use(
4143

4244
// NOTE from v13.0 team: GitHub OAuth works fine in Electron production app and the backend for Electron production app is deployed on Heroku at https://reactype-caret.herokuapp.com/ (get credentials from instructor )
4345

44-
// passport.use(
45-
// new GitHubStrategy(
46-
// {
47-
// clientID: process.env.GITHUB_ID,
48-
// clientSecret: process.env.GITHUB_SECRET,
49-
// callbackURL: isDev
50-
// ? `http://localhost:${DEV_PORT}/github/callback`
51-
// : `https://reactype-caret.herokuapp.com/github/callback`
52-
// },
53-
// function(accessToken, refreshToken, profile, done) {
54-
// console.log(profile);
55-
// }
56-
// )
57-
// );
46+
// V.15 Team: Github Oauth and Google Oauth works! (starts here)
47+
const session = require('express-session');
48+
const authRoutes = require('./routers/auth.js')
5849

59-
// initializes passport and passport sessions
60-
// app.use(passport.initialize());
61-
// app.use(passport.session());
50+
app.use(session({
51+
secret: 'asdsidfhbos',
52+
resave: false,
53+
saveUninitialized: true,
54+
cookie: { maxAge: 24*60*60*1000 }
55+
}))
56+
57+
app.use(passport.initialize());
58+
app.use(passport.session());
59+
60+
app.use('/auth', authRoutes)
61+
// go to other files
6262

63-
// app.get(
64-
// '/auth/github',
65-
// passport.authenticate('github', { session: false }),
66-
// (req, res) => {
67-
// res.send('github');
68-
// }
69-
// );
7063

7164
// for Oauth which is currently not working
7265
// app.get(
@@ -123,6 +116,7 @@ app.use('/user-styles', stylesRouter);
123116
// schemas used for graphQL
124117
const typeDefs = require('./graphQL/schema/typeDefs.js');
125118
const { dirname } = require('node:path');
119+
const { Mongoose } = require('mongoose');
126120

127121
// instantiate Apollo server and attach to Express server, mounted at 'http://localhost:PORT/graphql'
128122

@@ -183,6 +177,10 @@ if (process.env.NODE_ENV == 'production'){
183177
});
184178
}
185179

180+
app.get('/test', (req, res) => {
181+
res.send('test request is working');
182+
})
183+
186184
app.get('/', function(req, res) {
187185
res.send('Houston, Caret is in orbit!');
188186
});

webpack.development.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ module.exports = merge(base, {
1212
mode: 'development',
1313
devtool: 'inline-source-map',
1414
devServer: {
15+
headers: { 'Access-Control-Allow-Origin': '*' },
16+
historyApiFallback: true,
1517
host: 'localhost',
1618
port: '8080',
1719
hot: true, // Hot-reload this server if changes are detected
@@ -27,6 +29,9 @@ module.exports = merge(base, {
2729
},
2830
'/user-styles': {
2931
target: `http://localhost:${DEV_PORT}/`
32+
},
33+
'/auth/**': {
34+
target: `http://localhost:5656/`
3035
}
3136
}
3237
},

0 commit comments

Comments
 (0)