From b6f205092f879bde2dcd7b5c5861aa2b85cad61f Mon Sep 17 00:00:00 2001 From: PreciousIfeaka Date: Fri, 7 Jun 2024 09:53:39 +0100 Subject: [PATCH] reconciled auth conflict --- server/package-lock.json | 169 +++++++++++++++++++++++++ server/package.json | 2 + server/public/home_page.html | 47 +++++-- server/public/login_page.html | 5 +- server/public/styles/home_page.css | 49 ++++++- server/public/styles/login_page.css | 3 + server/public/styles/register_page.css | 2 +- server/src/app.js | 89 ++++++------- server/src/config/JWT.js | 21 +-- server/src/config/auth.js | 24 ++-- server/src/config/googleOAuth.js | 24 +++- server/src/models/userModel.js | 6 +- server/src/routes/homeRouter.js | 4 +- server/src/routes/loginRouter.js | 24 +--- server/src/routes/registerRouter.js | 5 +- 15 files changed, 349 insertions(+), 125 deletions(-) diff --git a/server/package-lock.json b/server/package-lock.json index 153a1a4..5987df8 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -11,9 +11,11 @@ "dependencies": { "bcrypt": "^5.1.1", "connect-mongo": "^5.1.0", + "connect-mongodb-session": "^5.0.0", "cookie": "^0.6.0", "cookie-parser": "^1.4.6", "crypto": "^1.0.1", + "ejs": "^3.1.10", "express": "^4.19.2", "express-session": "^1.18.0", "fs": "^0.0.1-security", @@ -163,6 +165,20 @@ "node": ">=8" } }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", @@ -181,6 +197,27 @@ "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" }, + "node_modules/archetype": { + "version": "0.13.0", + "resolved": "https://registry.npmjs.org/archetype/-/archetype-0.13.0.tgz", + "integrity": "sha512-ts/rng/A4UQPw1ZuQWWZvR2T0q2S5+zQGBH0RPsSlmyIAsZuIGEm1rgRga2NJnHODBbW/jVWMZIWbtlEyrS7JQ==", + "dependencies": { + "lodash.clonedeep": "4.x", + "lodash.set": "4.x", + "mpath": "0.8.x" + }, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/archetype/node_modules/mpath": { + "version": "0.8.4", + "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.8.4.tgz", + "integrity": "sha512-DTxNZomBcTWlrMW76jy1wvV37X/cNNxPW1y2Jzd4DZkAaC5ZGsm8bfGfNOthcDuRJujXLqiuS6o3Tpy0JEoh7g==", + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/are-we-there-yet": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", @@ -226,6 +263,11 @@ "node": ">=0.8" } }, + "node_modules/async": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==" + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -383,6 +425,40 @@ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/chokidar": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", @@ -415,6 +491,22 @@ "node": ">=10" } }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, "node_modules/color-support": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", @@ -476,6 +568,15 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, + "node_modules/connect-mongodb-session": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/connect-mongodb-session/-/connect-mongodb-session-5.0.0.tgz", + "integrity": "sha512-Yxr09hsafOvMgwiqeMi6fk5VudMXm2z5/IaJJp4EO6/tzajqsCUJTX4x9541URNwBL43lB8wSR7q77JpIdddSA==", + "dependencies": { + "archetype": "0.13.x", + "mongodb": "5.x || 6.x" + } + }, "node_modules/console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", @@ -660,6 +761,20 @@ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -815,6 +930,33 @@ "node": "^12.20 || >= 14.13" } }, + "node_modules/filelist": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", @@ -1277,6 +1419,23 @@ "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==" }, + "node_modules/jake": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.1.tgz", + "integrity": "sha512-61btcOHNnLnsOdtLgA5efqQWjnSi/vow5HbI7HMdKKWqvrKR1bLK3BPlJn9gcSaP2ewuamUSMB5XEy76KUIS2w==", + "dependencies": { + "async": "^3.2.3", + "chalk": "^4.0.2", + "filelist": "^1.0.4", + "minimatch": "^3.1.2" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", @@ -1375,6 +1534,11 @@ "node": ">8" } }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==" + }, "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", @@ -1410,6 +1574,11 @@ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" }, + "node_modules/lodash.set": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/lodash.set/-/lodash.set-4.3.2.tgz", + "integrity": "sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg==" + }, "node_modules/make-dir": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", diff --git a/server/package.json b/server/package.json index 0376d26..47aa136 100644 --- a/server/package.json +++ b/server/package.json @@ -17,9 +17,11 @@ "dependencies": { "bcrypt": "^5.1.1", "connect-mongo": "^5.1.0", + "connect-mongodb-session": "^5.0.0", "cookie": "^0.6.0", "cookie-parser": "^1.4.6", "crypto": "^1.0.1", + "ejs": "^3.1.10", "express": "^4.19.2", "express-session": "^1.18.0", "fs": "^0.0.1-security", diff --git a/server/public/home_page.html b/server/public/home_page.html index d716dce..610a6ba 100644 --- a/server/public/home_page.html +++ b/server/public/home_page.html @@ -14,10 +14,30 @@

Welcome!

@@ -39,10 +59,12 @@

Welcome!

-

QUIZzar!

-

Baby red chinehgd heufyuf gfuysgyd gdtytdi duyduyft - dhudyuf gdguyyuwh. uyfufgugyui ggcggc cuddutf gfgfgdu - gvfguvf vfufgyf vfuvtfytf

+

QUIZzar

+

QUIZzar is an interactive trivia quiz website where you can have + quiz sessions based on the topic area you have chosen. + On taking this quiz, you will be exposed to questions that will improve your knowledge-based. +
Happy quizing! +

@@ -51,14 +73,13 @@

QUIZzar!

QUIZzar Session Guide

- 1. Click on the take a quiz button + 1. Click on the take a Continue button 2. Select the quiz topic you want from the quiz field popup - 3. Click on the process to quiz button - 4. Select the number of questions you want to answer - 5. Click on proceed. + 3. Select the number of questions you want to answer + 4. Click on proceed.
- +
diff --git a/server/public/login_page.html b/server/public/login_page.html index 410b1c0..926077f 100644 --- a/server/public/login_page.html +++ b/server/public/login_page.html @@ -35,8 +35,11 @@

QUIZzar

+ + Google iconContinue with Google + +

New to QUIZzar? Sign up

diff --git a/server/public/styles/home_page.css b/server/public/styles/home_page.css index ce2e7a9..976e5e0 100644 --- a/server/public/styles/home_page.css +++ b/server/public/styles/home_page.css @@ -31,15 +31,56 @@ header h1 { filter: drop-shadow(0 0 5px) #09001d; } +.navbar { + display: flex; +} + .navbar a { + display: inline-block; color: white; - padding-right: 20px; - padding-bottom: 10px; + text-align: center; + padding: 10px 20px; + text-decoration: none; } -.navbar a:hover, -.navbar a.active { +.navbar a:hover { color: #1a1199; + text-decoration: underline; +} + +.drop-down { + position: relative; + display: inline-block +} + +.dropdown-content { + position:absolute; + min-width: 160px; + box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); + z-index: -1; + opacity: 0; + pointer-events: none; +} + +.dropdown-content ul { + margin-left: 20px; + list-style: circle; + padding: 12px 16px; + display: block; +} + +.about-list li { + line-height: 1.5; + padding: 8px 0; +} + +.drop-down:hover .dropdown-content, +.dropdown-content:hover { + opacity: 1; + background: #8da7fc; + display: block; + border-radius: 6px; + pointer-events: auto; } .home { diff --git a/server/public/styles/login_page.css b/server/public/styles/login_page.css index 03dc70c..b5c8fec 100644 --- a/server/public/styles/login_page.css +++ b/server/public/styles/login_page.css @@ -140,6 +140,9 @@ font-size: 16px; } + a { + text-decoration: none; + } .google-signin:hover { background-color: #d3d8f5; cursor: pointer; diff --git a/server/public/styles/register_page.css b/server/public/styles/register_page.css index 2cdfae2..f3de650 100644 --- a/server/public/styles/register_page.css +++ b/server/public/styles/register_page.css @@ -20,7 +20,7 @@ padding: 20px; background-color: #D3D3D3; border-radius: 8px; - box-shadow: 100px 0 220px rgba(0, 0, 0, 0.1); + box-shadow: 10px 0 20px rgba(0, 0, 0, 0.4); } .register_form { diff --git a/server/src/app.js b/server/src/app.js index 8f2ef1c..d882fff 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -7,9 +7,8 @@ const homeRouter = require('./routes/homeRouter'); const questionsRouter = require('./routes/questionsRouter'); const session = require("express-session"); const mongoose = require('mongoose'); -const MongoStore = require("connect-mongo"); -const cookieparser = require('cookie-parser'); -const { isLogin } = require('./config/auth'); +const MongoDBSession = require('connect-mongodb-session')(session); +// const cookieparser = require('cookie-parser'); const bodyParser = require('body-parser'); const passport = require("passport"); require("dotenv").config(); @@ -17,39 +16,38 @@ require("./config/googleOAuth"); const app = express(); -app.use(cookieparser()); + app.use(express.json()); app.use(express.static(path.join(__dirname, "..", "public"))); app.use(express.urlencoded({ extended: false })); app.use(bodyParser.urlencoded({extended: true })); +// app.use(cookieparser()); + +// mogoose connection +mongoose.connect("mongodb://localhost:27017/userData").then((connect) => console.log("Connected")); +const store = new MongoDBSession({ + uri: "mongodb://localhost:27017/userData", + collection: "sessions", +}); app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, - store: MongoStore.create({ - mongoUrl: 'mongodb://localhost:27017/userData', // Connection string to the MongoDB database - collectionName: 'sessions', // optional - ttl: 60 * 60 // Optional: time to live (TTL) for session data, in seconds (5 mins here) - }), - cookie: { - maxAge: 60 * 60 * 1000 - } + store: store, })); +// passport middleware +app.use(passport.initialize()); +app.use(passport.session()); + // root routes for user registeration and login app.use("/user", express.static(path.join(__dirname, "..", "public"))); app.use("/user", loginRouter); app.use("/user", registerRouter); -// root route for the home page -app.use("/home", isLogin, homeRouter); - -// mogoose connection -mongoose.connect("mongodb://localhost:27017/userData").then((connect) => console.log("Connected")); - app.get("/quiz-session", (req, res, next) => { res.sendFile(path.join(__dirname, "..", "public", "quiz_page.html"), (err) => { if (err) { @@ -66,41 +64,46 @@ app.get("/quiz-session/result", (req, res) => { res.sendFile(path.join(__dirname, "..", "public", "result_page.html")); }); -app.get("/logout", (req, res, next) => { - res.cookie('access-token', "", { maxAge: 1 }); +// google OAuth routes +app.use("/auth", express.static(path.join(__dirname, "..", "public"))); + +app.get('/auth/google', + passport.authenticate('google', { scope: + [ 'email', 'profile' ] + }) +); + +app.get( '/auth/google/callback', + passport.authenticate( 'google', { + successRedirect: '/auth/success', + failureRedirect: '/auth/google/failure' + }) +); + +app.get("/auth/success", (req, res) => { + res.redirect("/home"); +}); + +app.get("/auth/google/failure", (req, res) => { + res.send(`

Something went wrong. Go back to login page`); +}) + +app.get("/logout", (req, res) => { req.session.destroy((err) => { if (err) { return res.status(500).send("Failed to destroy session during logout."); } - res.clearCookie('connect.sid'); res.redirect('/user/login'); }) }); +// root route for the home page +app.use("/home", homeRouter); + + app.get('/', (req, res) => { res.redirect('/user/register'); + req.session.isAuth = true; }); -// passport middleware -app.use(passport.initialize()); -app.use(passport.session()); - -// google OAuth routes - -app.use("/auth", express.static(path.join(__dirname, "..", "public"))); -app.get('/auth/google', - passport.authenticate('google', { scope: - [ 'email', 'profile' ] } -)); - -app.get( '/auth/google/callback', - passport.authenticate( 'google', { - successRedirect: '/auth/success', - failureRedirect: '/auth/google/failure' -})); - -app.get("/auth/success", (req, res) => { - res.sendFile(path.join(__dirname, "..", "public", "home_page.html")); -}) - module.exports = app; \ No newline at end of file diff --git a/server/src/config/JWT.js b/server/src/config/JWT.js index f12d0d1..c458c30 100644 --- a/server/src/config/JWT.js +++ b/server/src/config/JWT.js @@ -1,24 +1,6 @@ -const jwt = require('jsonwebtoken'); -const cookie = require('cookie-parser'); const User = require("../models/userModel"); require("dotenv").config(); -const requiredLogin = async (req, res, next) => { - const token = req.cookies['access-token']; - if (token) { - const validateToken = await jwt.verify(token, process.env.SECRET_KEY); - if (validateToken) { - res.user = validateToken.id; - next(); - } else { - console.log("Token has expired"); - res.redirect("/user/login"); - } - } else { - console.log("Token not found") - res.redirect("/user/login"); - } -} const verifyEmail = async (req, res, next) => { try { @@ -33,9 +15,8 @@ const verifyEmail = async (req, res, next) => { console.log("Email doesn't exist"); } } catch(err) { - console.log("Not It"); console.log(err.message); } } -module.exports = { requiredLogin, verifyEmail }; \ No newline at end of file +module.exports = verifyEmail; \ No newline at end of file diff --git a/server/src/config/auth.js b/server/src/config/auth.js index 5766ee6..aa0ff9f 100644 --- a/server/src/config/auth.js +++ b/server/src/config/auth.js @@ -1,21 +1,19 @@ const User = require("../models/userModel"); -const isLogin = async(req, res, next) => { - try { - if (req.session.userId) {} - else { - return res.redirect("/") +const isLogedin = (req, res, next) => { + try{ + if (req.isAuthenticated() || req.user || req.session.isAuth) { + return next(); + } else { + res.redirect('/'); } - next(); - } catch (error) { - console.log("AGAIN"); - console.log(error.message); + } catch(err) { + console.log(err.message); } } - -const isLogout = async(req, res, next) => { +const isLogOut = async(req, res, next) => { try { - if (req.session.userId) { + if (req.session.isAuth || req.isAuthenticated()) { return res.redirect("/home"); } else {} next(); @@ -25,5 +23,5 @@ const isLogout = async(req, res, next) => { } module.exports = { - isLogin, isLogout + isLogedin, isLogOut } \ No newline at end of file diff --git a/server/src/config/googleOAuth.js b/server/src/config/googleOAuth.js index 42e8126..c2673e1 100644 --- a/server/src/config/googleOAuth.js +++ b/server/src/config/googleOAuth.js @@ -1,7 +1,7 @@ const passport = require("passport"); -require("dotenv").config(); - +const User = require("../models/userModel"); const GoogleStrategy = require('passport-google-oauth2').Strategy; +require("dotenv").config(); passport.use(new GoogleStrategy({ clientID: process.env.OAUTH_CLIENT_ID, @@ -9,9 +9,21 @@ passport.use(new GoogleStrategy({ callbackURL: "http://localhost:5001/auth/google/callback", passReqToCallback : true }, + + async (request, accessToken, refreshToken, profile, done) => { + let user = await User.findOne({ googleId: profile.id }); - (request, accessToken, refreshToken, profile, done) => { - done(null, profile); + if (!user) { + // Creating a new user if not in database + + user = new User({ + name: profile.displayName, + email: profile.emails[0].value, + googleId: profile.id + }); + await user.save(); + } + done(null, user); } )); @@ -19,6 +31,6 @@ passport.serializeUser((user, done) => { done(null, user); }); -passport.deserializeUser((user, done) => { +passport.deserializeUser(async(user, done) => { done(null, user); -}) \ No newline at end of file +}); \ No newline at end of file diff --git a/server/src/models/userModel.js b/server/src/models/userModel.js index 251a893..8a113e1 100644 --- a/server/src/models/userModel.js +++ b/server/src/models/userModel.js @@ -11,9 +11,13 @@ const userSchema = new mongoose.Schema({ required: true }, + googleId: { + type: String + }, + password: { type: String, - required: true + required: false }, emailToken: { diff --git a/server/src/routes/homeRouter.js b/server/src/routes/homeRouter.js index 75ae6fa..8eb0b48 100644 --- a/server/src/routes/homeRouter.js +++ b/server/src/routes/homeRouter.js @@ -1,10 +1,10 @@ const express = require("express"); const path = require('path'); -const { requiredLogin } = require("../config/JWT"); +const { isLogedin } = require('../config/auth'); const homeRouter = express.Router(); -homeRouter.get("/", requiredLogin, (req, res) => { +homeRouter.get("/", isLogedin, (req, res) => { res.sendFile(path.join(__dirname, "..", "..", "public", "home_page.html")); }); diff --git a/server/src/routes/loginRouter.js b/server/src/routes/loginRouter.js index b07ebbc..50f7ab1 100644 --- a/server/src/routes/loginRouter.js +++ b/server/src/routes/loginRouter.js @@ -4,20 +4,15 @@ const loginRouter = express.Router(); const User = require("../models/userModel"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); -const {isLogout} = require("../config/auth"); -const cookie = require("cookie-parser"); -const { verifyEmail } = require('../config/JWT'); +const { isLogOut } = require("../config/auth"); +const verifyEmail = require('../config/JWT'); require('dotenv').config(); -loginRouter.get('/login', isLogout, (req, res) => { - res.status(200).sendFile(path.join(__dirname, "..", "..", "public", "login_page.html")); +loginRouter.get('/login', isLogOut, async (req, res) => { + await res.sendFile(path.join(__dirname, "..", "..", "public", "login_page.html")); }); -const createToken = (id) => { - return jwt.sign({ id }, process.env.SECRET_KEY); -} - loginRouter.post('/login', verifyEmail, async (req, res) => { try { const { email, password } = req.body; @@ -26,14 +21,8 @@ loginRouter.post('/login', verifyEmail, async (req, res) => { if(findUser) { const match = await bcrypt.compare(password, findUser.password); if (match) { - // create token - const token = createToken(findUser.id); - - // store token in cookie - res.cookie('access-token', token); - console.log("Valid User"); - req.session.userId = findUser.id; - // console.log(req.session.userId); + req.session.isAuth = true; + console.log("Correct"); return res.redirect("/home"); } else { console.log("Invalid Password"); @@ -43,7 +32,6 @@ loginRouter.post('/login', verifyEmail, async (req, res) => { console.log("User is not registered"); }; } catch (err) { - console.log("it"); console.log(err); } }) diff --git a/server/src/routes/registerRouter.js b/server/src/routes/registerRouter.js index ead94c3..b4a06b3 100644 --- a/server/src/routes/registerRouter.js +++ b/server/src/routes/registerRouter.js @@ -6,10 +6,10 @@ const User = require("../models/userModel"); const jwt = require("jsonwebtoken"); const nodemailer = require("nodemailer"); const crypto = require('crypto'); -const { isLogout, isLogin } = require("../config/auth"); +const { isLogOut } = require("../config/auth"); require("dotenv").config(); -registerRouter.get('/register', isLogout, (req, res) => { +registerRouter.get('/register', isLogOut, (req, res) => { res.status(200).sendFile(path.join(__dirname, "..", "..", "public", "register_page.html")); }); @@ -62,7 +62,6 @@ registerRouter.post('/register', async (req, res) => { } }); res.send(`

Please, check your email to verify your account

`); - // res.redirect('/user/login'); } catch (err) { console.log(err); res.redirect("/user/register");