Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules/
.vscode/

.env
.env.local

*.log
2 changes: 1 addition & 1 deletion backend/db.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Connecting to moongose
const mongoose=require("mongoose");

const mongoURL="mongodb://localhost:27017/task-manager";
const mongoURL=process.env.MONGODB_URI

const connecttoMongo=()=>{
mongoose.connect(mongoURL,()=>{
Expand Down
17 changes: 15 additions & 2 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
require('dotenv').config()
const express=require("express");
const connecttoMongo=require("./db");
const cors = require('cors');
connecttoMongo(); //Connecting to mongo
const passport = require('passport');
const cookieSession = require('cookie-session');
require('./passport.setup')

connecttoMongo(); //Connecting to mongo

const app=express();
const port=80;
const port= process.env.PORT || 3000;

app.use(cors())

app.use(express.json());

app.use(cookieSession({
maxAge : 24 * 60 * 60 * 1000,
keys : ['sandip@low']
}))

app.use(passport.initialize())
app.use(passport.session())

app.get('/',(req,res)=>{
res.send("Hello,Welcome to task manager");
})
Expand Down
8 changes: 8 additions & 0 deletions backend/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
provider: {
type: String,
default: "native",
},
providerId: {
type: String,
default: null
},
name: String,
email: {
type: String,
Expand Down
9 changes: 7 additions & 2 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,21 @@
"description": "backend of task manager app",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "sujal",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"cookie-session": "^2.0.0",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.1",
"express-validator": "^6.14.2",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.5.1"
"mongoose": "^6.5.1",
"passport": "0.5.0",
"passport-google-oauth20": "^2.0.0"
}
}
51 changes: 51 additions & 0 deletions backend/passport.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const User = require('./models/User')

// serialize user through out the routes
passport.serializeUser((user, cb)=> {
cb(null, user)
})

passport.deserializeUser( async (id, cb)=> {
const user = await User.findById(id)
cb(null, user)
})

// use google strategy for google oauth login
passport.use(
new GoogleStrategy( {
clientID : process.env.GOOGLE_CLIENTID,
clientSecret : process.env.GOOGLE_CLIENTSECRET,
callbackURL : "/auth/google/redirect"
},
async (accessToken, refreshToken, profile, cb) => {
// Checking if the user already in database 🧐
const dbUser = await User.findOne({ email : profile._json.email })

if (dbUser) {
// Checking whether the user used to sign in using password, if so then we set the provider to be google from now...😘
if(dbUser.provider !== "google") {
dbUser.update({
provider : "google",
providerId : profile._json.sub
})
}
// console.log("User already exists : "+dbUser)
cb(null, dbUser)
}

else {
// There is no user with that email in database so we have to create that...🤜🏽🤛🏽
let user = await User.create({
provider : "google",
providerId : profile.id,
name : profile.displayName,
email : profile.emails[0].value
})
// console.log("New User Created : "+user)
cb(null, user)
}
}
)
)
18 changes: 18 additions & 0 deletions backend/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { body, validationResult } = require('express-validator');
const bcrypt = require('bcrypt');
const fetchUser=require('../middleware/fetchUser');
const jwt = require('jsonwebtoken'); //using jwt(JSON web token for authorization)
const passport = require('passport');

const secret_key="Mynameissujal" //secret key

Expand Down Expand Up @@ -116,4 +117,21 @@ router.post('/getUser',fetchUser,async (req,res)=>{
res.status(500).send("Internal server error")
}
})

// ROUTE-4-----> Google OAuth SignIn (no login required)
router.get('/google', passport.authenticate('google', {
scope : ['profile', 'email']
}))

// ROUTE-5-----> Google OAuth Redirect URI (no need to visit...🙂)
router.get('/google/redirect', passport.authenticate('google'), (req, res)=> {
// res.json(req.user)
const data={
user:{
id:req.user.id
}
}
const token = jwt.sign(data, secret_key)
res.redirect(process.env.CLIENT_URI+"/redirect?token="+token)
})
module.exports = router
Loading