Skip to content

Commit 043e656

Browse files
committed
Integrate passport GoogleStrategy login successfully
1 parent 84f5550 commit 043e656

File tree

11 files changed

+193
-41
lines changed

11 files changed

+193
-41
lines changed

config/passport-setup.js

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
1-
const passport = require('passport');
2-
const GoogleStrategy = require('passport-google-oauth20');
3-
const User = require('../models/user-models');
1+
import passport from 'passport';
2+
import GoogleStrategy from 'passport-google-oauth20';
3+
import { User } from '../models/user-models.js';
4+
5+
import { keys } from './keys.js';
6+
47
// const keys = require ('./keys');
58
import { GoogleclientID, GoogleclientSecret } from './../index.js';
69

710
// serialize user structure in the mongodb
8-
passport.serializeUser((user, done) => {
11+
const serialize = passport.serializeUser((user, done) => {
912
done(null, user.id);
1013
});
1114

12-
passport.deserializeUser((id, done) => {
15+
const deserialize = passport.deserializeUser((id, done) => {
1316
try {
1417
User.findById(id).then((user) => {
1518
done(null, user);
@@ -28,11 +31,11 @@ try {
2831
*
2932
* Go to https://console.cloud.google.com/ to create your own clientID and clientSecret.
3033
*/
31-
passport.use(new GoogleStrategy({
34+
const googleStrategy = passport.use(new GoogleStrategy({
3235
// options for google strategy
3336
callbackURL: '/auth/google/redirect',
34-
clientID: GoogleclientID,
35-
clientSecret: GoogleclientSecret
37+
clientID: keys.google.clientID, //GoogleclientID,
38+
clientSecret: keys.google.clientSecret //GoogleclientSecret
3639
}, (accessToken, refreshToken, profile, done) => {
3740
// passport callback function
3841
// console.log('accessToken: ' + accessToken);
@@ -60,4 +63,6 @@ passport.use(new GoogleStrategy({
6063
}
6164
})
6265

63-
}));
66+
}));
67+
68+
export { serialize, deserialize, googleStrategy };

index.js

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ import * as dotenv from 'dotenv';
22
import request from 'request';
33
import express from 'express';
44
import bodyParser from 'body-parser';
5+
import cookieSession from 'cookie-session';
6+
import passport from 'passport';
7+
import mongoose from 'mongoose';
8+
import { compile } from 'ejs';
9+
import { serialize, deserialize, googleStrategy } from './config/passport-setup.js';
510
import {encryptAES, decryptAES} from './crypto.js';
611

712
// dev env
@@ -16,25 +21,27 @@ let WEATHERBIT_KEY;
1621
let WEATHERBIT_URI='https://api.weatherbit.io/v2.0/';
1722
let GoogleclientID;
1823
let GoogleclientSecret;
24+
let MongoDBConString;
25+
let CookieKey = 'c93da061ab7f984267e36c8431645035d611bc892c58f0e64614c68a4384a179126e7ed0b5829e460f292f72e9ef4facb68a0894cb2425ba046b82a3bae0b529';
26+
1927
if (process.env.NODE_ENV === "production") {
2028
EXCHANGE_RATE_APIKEY = process.env.EXCHANGE_RATE_APIKEY;
2129
WEATHERBIT_KEY = process.env.WEATHERBIT_KEY;
2230
GoogleclientID = process.env.GoogleclientID;
2331
GoogleclientSecret = process.env.GoogleclientSecret;
24-
32+
MongoDBConString = process.env.MONGODB_URI;
2533
} else {
2634
// dynamically importing keys.js using promise:
2735
import('./config/keys.js').then((secrets) => {
2836
EXCHANGE_RATE_APIKEY = secrets.keys.exchangerateapi.EXCHANGE_APIKEY;
2937
WEATHERBIT_KEY = secrets.keys.weatherbitapi.WEATHERBIT_APIKEY;
3038
GoogleclientID = secrets.keys.google.clientID;
3139
GoogleclientSecret = secrets.keys.google.clientSecret;
40+
MongoDBConString = secrets.keys.mongodb.connectionString;
3241
});
33-
3442
}
3543

3644

37-
3845
// Create network routing
3946
const app = express();
4047

@@ -48,6 +55,8 @@ import { router as weatherbitRoutes } from './routes/weatherbit-routes.js';
4855
// routes handler for OAuth20 methods
4956
import { router as oauth20Routes } from './routes/auth-routes.js';
5057

58+
// routes handler for profile
59+
import { router as profileRoutes } from './routes/profile-routes.js';
5160

5261
// EJS is accessed by default in the views directory.
5362
app.set('view engine', 'ejs');
@@ -58,6 +67,29 @@ app.use(express.static('public'));
5867
// Parse incoming request bodies in a middleware before your handlers, available under the `req.body` property.
5968
app.use(bodyParser.urlencoded({ extended: true }));
6069

70+
71+
72+
// cookie!
73+
app.use(cookieSession({
74+
maxAge: 24 * 60 * 60 * 1000,
75+
keys: [CookieKey]
76+
}));
77+
78+
79+
// Initialize passport
80+
app.use(passport.initialize());
81+
app.use(passport.session());
82+
83+
84+
// connect to mongodb
85+
mongoose.connect(MongoDBConString, () => {
86+
console.log('Connected to MongoDB.');
87+
});
88+
89+
90+
91+
92+
6193
// Set up all routes related to currency exchange rate methods
6294
app.use('/exchange', currencyExchangeRoutes);
6395

@@ -67,14 +99,17 @@ app.use('/weatherbit', weatherbitRoutes);
6799
// Set up all routes related to oauth2 methods
68100
app.use('/auth', oauth20Routes);
69101

102+
// set up routes for user info after logged in
103+
app.use('/profile', profileRoutes);
104+
70105
// Homepage: get the locale from the client-side via the ejs form
71106
app.get('/', (req, res) => {
72-
res.render('index', {xkey: 'hey'});
107+
res.render('index', {user: req.user, xkey: 'hey'});
73108
})
74109

75110
// about page
76111
app.get('/about', function(req, res) {
77-
res.render('pages/about');
112+
res.render('pages/about', {user: req.user});
78113
});
79114

80115

package-lock.json

Lines changed: 9 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
"ejs": "^3.1.8",
2424
"express": "^4.18.1",
2525
"mongoose": "^6.7.2",
26-
"passport": "^0.6.0",
26+
"passport": "^0.5.3",
2727
"passport-google-oauth20": "^2.0.0",
2828
"request": "^2.88.2"
2929
},

routes/auth-routes.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import express from 'express';
22
import passport from 'passport';
3+
import { User } from '../models/user-models.js';
34

45

56
const router = express.Router();
67

78
// auth login
89
router.get('/login', (req, res) => {
9-
res.render('login', {user: req.user});
10+
res.render('pages/login', {user: req.user});
1011
});
1112

1213
// auth logout

routes/currency-exchange-routes.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const router = express.Router();
1010
router.get('/', (req, res) => {
1111
// console.log(currencyCodes);
1212
let cdat = JSON.stringify(currencyCodes);
13-
res.render('pages/exchangeRate', { Cdata: cdat });
13+
res.render('pages/exchangeRate', { user: req.user, Cdata: cdat });
1414
});
1515

1616
router.post('/', (req, res) => {
@@ -27,7 +27,7 @@ router.post('/', (req, res) => {
2727

2828
promiseData.then ( (data) => {
2929
// console.log("Exchange data: " + data.conversion_result);
30-
res.render('pages/exchangeRate', { Cdata: cdat, amount: amnt, frC: Fc, toC: Tc, exchange: data});
30+
res.render('pages/exchangeRate', { user: req.user, Cdata: cdat, amount: amnt, frC: Fc, toC: Tc, exchange: data});
3131
});
3232
});
3333

routes/profile-routes.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
const router = require('express').Router();
1+
import express from 'express';
2+
3+
const router = express.Router();
4+
25

36
// make sure the user has not already logged in.
47
const authCheck = (req, res, next) => {
@@ -7,15 +10,17 @@ const authCheck = (req, res, next) => {
710
res.redirect('/auth/login');
811
} else {
912
// if logged in
13+
console.log("You are already logged in.");
1014
next();
1115
}
1216
}
1317

1418
// final check with middleware authCheck.
1519
router.get('/', authCheck, (req, res) => {
1620
// Okay, user is legit. Let display views/profile.ejs
17-
res.render('profile', {user: req.user});
21+
console.log(req.user);
22+
res.render('pages/profile', {user: req.user});
1823

1924
});
2025

21-
module.exports = router;
26+
export { router };

routes/weatherbit-routes.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const router = express.Router();
1717
// }
1818

1919
router.get('/', (req, res) => {
20-
res.render('pages/weatherbit');
20+
res.render('pages/weatherbit', {user: req.user});
2121
});
2222

2323
// Posting data to the client-side requires multiple API calls.
@@ -36,7 +36,11 @@ router.post('/', (req, res) => {
3636
}
3737

3838
promisedData.then( (data) => {
39-
res.render('pages/weatherbit', data);
39+
// const data2 = {user: req.user};
40+
Object.assign(data, {user: req.user});
41+
42+
console.log(data);
43+
res.render('pages/weatherbit', data);
4044
})
4145
});
4246

@@ -250,7 +254,7 @@ function getWeatherAlerts(city){
250254
aData = null;
251255
}
252256
// combine 3 promises into a huge rendering passing paramters:
253-
let combinedData = { locale: city, alertStatus: aStatus, alertData: aData, curStatus: 200, curData: currentConditions, foreStatus: 200, foreData: dailyForecast, airqStatus: 200, airqData: airQuality.data[currentHour], error: null };
257+
let combinedData = { locale: city, alertStatus: aStatus, alertData: aData, curStatus: 200, curData: currentConditions, foreStatus: 200, foreData: dailyForecast, airqStatus: 200, airqData: airQuality.data[currentHour], error: null};
254258
return combinedData;
255259
} else {
256260
return { locale: city, alertStatus: 400, alertData: null, curStatus: 400, curData: null, foreStatus: 400, foreData: null, airqStatus: 400, airqData: null, error: null };

views/pages/login.ejs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<%- include('../partials/head'); %>
6+
</head>
7+
8+
9+
<body class="container">
10+
<header>
11+
<%- include('../partials/header'); %>
12+
</header>
13+
14+
<main >
15+
<div class="row">
16+
<div class="col-sm-10">
17+
<div class="jumbotron jumbotron-fluid">
18+
<header>
19+
<h3>Log in to your account with:</h3>
20+
</header>
21+
<main>
22+
<li><a class="btn btn-sm btn-outline-success ghost-button" href="/auth/google">Google+</a></li>
23+
</main>
24+
</div>
25+
</div>
26+
27+
<div class="col-sm-2">
28+
<div class="well">
29+
<h3>Reserved Ad space</h3>
30+
</div>
31+
</div>
32+
</div>
33+
</main>
34+
35+
<footer>
36+
<%- include('../partials/footer'); %>
37+
</footer>
38+
39+
</body>
40+
41+
</html>

views/pages/profile.ejs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<%- include('../partials/head'); %>
6+
</head>
7+
8+
9+
<body class="container">
10+
<header>
11+
<%- include('../partials/header'); %>
12+
</header>
13+
14+
<main >
15+
<div class="row">
16+
<div class="col-sm-10">
17+
<div class="jumbotron jumbotron-fluid">
18+
<header>
19+
<h3>Welcome <strong style="color:goldenrod"><%= user.username %></strong></h3>
20+
</header>
21+
<main>
22+
<img src="<%= user.thumbnail %>" />
23+
<p>What do you want to do today?</p>
24+
<ul>
25+
<li>Raise an ant farm and sneak it in captain Underpant.</li>
26+
<li>Pondering where the darkness comes from. (We know the physical source of light, but we donot know the source of darkness).</li>
27+
<li>Write a mobile app to detect liyng politicians and enrourage everyone to point the app at political rallies.</li>
28+
<li>Discover why Mars cannot have water in liquid form.</li>
29+
<li>Invent ways to collect all plastic wastes and use it to pave roads.</li>
30+
<li>Send a message to the aliens on the Betelgeuse star system. We can supply them with earth's oligarchs as food source.</li>
31+
</ul>
32+
</main>
33+
34+
</div>
35+
</div>
36+
37+
<div class="col-sm-2">
38+
<div class="well">
39+
<h3>Reserved Ad space</h3>
40+
</div>
41+
</div>
42+
</div>
43+
</main>
44+
45+
<footer>
46+
<%- include('../partials/footer'); %>
47+
</footer>
48+
49+
</body>
50+
51+
</html>

0 commit comments

Comments
 (0)