Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google auth added #93

Merged
merged 5 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
12 changes: 9 additions & 3 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import cors from "cors";
import csrf from 'csurf';
import * as dotenv from "dotenv";
dotenv.config();

import initializePassport from './src/api/middlewares/passportConfig.js'

const PORT = process.env.PORT || 5000;
const CONNECTION_URI = process.env.MONGODB_URI;
Expand All @@ -17,12 +17,18 @@ app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());


initializePassport(app)



import indexRoute from "./src/api/routes/index.js";
import testRoute from "./src/api/routes/test.js";
import user from "./src/api/routes/user.js";
import profile from "./src/api/routes/profile.js";
import event from "./src/api/routes/events.js";
import userAdmin from "./src/api/routes/userAdmin.js";
import googleAuth from "./src/api/routes/googleAuth.js"



//rate limiter
Expand All @@ -43,8 +49,8 @@ app.use("/test", testRoute)
app.use("/user", user)
app.use("/profile", profile)
app.use("/event", event)
app.use("/auth",googleAuth)

app.use("/userAdmin", userAdmin)

app.use(csrf)

Expand Down
82 changes: 81 additions & 1 deletion server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
"mongoose": "^7.4.2",
"mongoose-sanitizer": "^1.0.0",
"nodemailer": "^6.9.5",
"nodemon": "^3.0.1"
"nodemon": "^3.0.1",
"passport": "^0.6.0",
"passport-google-oauth20": "^2.0.0"
},
"devDependencies": {
"@vercel/ncc": "^0.36.1"
Expand Down
6 changes: 1 addition & 5 deletions server/src/api/controllers/changePassword.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import bcrypt from 'bcrypt'
import userAdminModel from '../models/userAdminModel.js'
import userStudentModel from '../models/userStudentModel.js'
import userFacultyModel from '../models/userFacultyModel.js'
import userStaffModel from '../models/userStaffModel.js'
import userVisitorModel from '../models/userVisitorModel.js'
import userModel from "../models/userModel.js"



Expand Down
6 changes: 1 addition & 5 deletions server/src/api/controllers/deleteUser.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import userAdminModel from "../models/userAdminModel.js"
import userStudentModel from "../models/userStudentModel.js"
import userStaffModel from "../models/userStaffModel.js"
import userFacultyModel from "../models/userFacultyModel.js"
import userVisitorModel from "../models/userVisitorModel.js"
import userModel from "../models/userModel.js"
import bcrypt from 'bcrypt'


Expand Down
6 changes: 1 addition & 5 deletions server/src/api/controllers/forgotPassword.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import userAdminModel from "../models/userAdminModel.js";
import userStudentModel from "../models/userStudentModel.js";
import userStaffModel from "../models/userStaffModel.js";
import userFacultyModel from "../models/userFacultyModel.js";
import userVisitorModel from "../models/userVisitorModel.js";
import userModel from "../models/userModel.js"
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken'
import sendEmail from '../middlewares/sendEmail.js'
Expand Down
53 changes: 53 additions & 0 deletions server/src/api/controllers/googleAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import '../middlewares/passportConfig.js'
import passport from 'passport'
import generateToken from "../middlewares/generateToken.js";



/**
* Route: /auth/google
* Desc: Open google consent screen
*/
export const authGoogle = passport.authenticate('google', { scope: [ 'email', 'profile' ]})



/**
* Route: /auth/google/callback
* Desc: handle callback from google
*/
export const callbackGoogle = passport.authenticate('google', { successRedirect: '/auth/protected', failureRedirect: '/auth/failed' })



/**
* Route /protected
* desc: reditrection after successfull
* google auth with userdata in req
*/
export const authenticated = (req, res)=>{
// let name = req.user.displayName

const SECRET = process.env.USER_SECRET
const token = generateToken(req.user, SECRET);

req.session.user = {
token: token,
user: req.user
}

res.status(200).json({
success: true,
user: req.user,
token: token
})
}


/**
* Route: /failed
* Desc: Redirection if google authentication failed
*/
export const failed = (req, res)=>{
res.status(401).send("google authentication failed")
}
73 changes: 73 additions & 0 deletions server/src/api/middlewares/passportConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import passport from 'passport'
import { Strategy as GoogleStrategy } from 'passport-google-oauth20'
import * as dotenv from "dotenv";
dotenv.config();
import userModel from '../models/userModel.js';
import session from 'express-session';


const initializePassport = (app) => {
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true
})
Comment on lines +11 to +15

Check failure

Code scanning / CodeQL

Missing CSRF middleware High

This cookie middleware is serving a
request handler
without CSRF protection.
This cookie middleware is serving a
request handler
without CSRF protection.
This cookie middleware is serving a request handler without CSRF protection.
Comment on lines +11 to +15

Check warning

Code scanning / CodeQL

Clear text transmission of sensitive cookie Medium

Sensitive cookie sent without enforcing SSL encryption.
);

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



passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.BASE_URL+'/auth/google/callback'
},
async (accessToken, refreshToken, profile, done) => {
// Handle user data and pass it to the 'done' callback
// Typically, you would save user data to your database here
try {

let User = await userModel.findOne({ googleId: profile.id });

// If user already exists, return the user
if (User) {
return done(null, User);
}

// If user does not exist, create a new user record
const result = await userModel.create({
googleId: profile.id,
name: profile.displayName,
email: profile.emails[0].value,
});
if(result){
console.log("user created"+ result)
}

let newUser = await userModel.findOne({ googleId: profile.id })

return done(null, newUser);
}
catch(err){
return done(err);
}
}
));

passport.serializeUser((user, done )=>{
done(null, user)
})

passport.deserializeUser((user, done) => {
done(null, user)
})


}



export default initializePassport;
25 changes: 0 additions & 25 deletions server/src/api/models/userFacultyModel.js

This file was deleted.

5 changes: 3 additions & 2 deletions server/src/api/models/userModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import sanitizerPlugin from 'mongoose-sanitizer'
// User schema
const userModel = mongoose.Schema({
id: { type: String },
googleId: { type: String },
name: { type: String },
collegeEmail: { type: String },
email: { type: String, required: true },
password: { type: String, required: true },
role: { type: String, default: 'faculty'},
password: { type: String },
role: { type: String },
branch: { type: String },
subjects: { type: String },
designation: { type: String },
Expand Down
Loading
Loading