Skip to content

Commit

Permalink
Add Google Oauth backend
Browse files Browse the repository at this point in the history
  • Loading branch information
kewal-wq committed Feb 13, 2022
1 parent 26c85d3 commit e79d293
Show file tree
Hide file tree
Showing 8 changed files with 252 additions and 23 deletions.
36 changes: 35 additions & 1 deletion server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import cors from "cors";
import customerRoutes from "./routes/customer.js";
import vendorRoutes from "./routes/vendor.js";
import mongoose from "mongoose";
import passport from "passport";
import cookieSession from "cookie-session";
import './oauth.js';
import isLoggedIn from "./middleware.js";
dotenv.config();

const app = express();
Expand All @@ -18,13 +22,43 @@ mongoose

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(cookieSession({
name: 'svs-session',
maxAge: 24*60*60*1000,
keys: [process.env.COOKIE_KEY]
}))
app.use(cors());
app.use(passport.initialize());
app.use(passport.session());

app.get("/", (req, res) => {
res.send("This is my home route!");
});

app.get("/failed", (req, res) => {
res.send("You have failed to log in");
});

app.get("/good", isLoggedIn, (req, res) => {
res.send(`Welcome, ${req.user.username}`);
})

app.get('/google',
passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/google/callback/',
passport.authenticate('google', { failureRedirect: '/failed' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/good');
});

app.get('/logout', (req, res) =>{
res.session = null;
req.logout();
res.redirect('/');
})

app.use("/customers", customerRoutes);
app.use("/vendors", vendorRoutes);

Expand Down
9 changes: 9 additions & 0 deletions server/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const isLoggedIn = async (req, res, next) => {
if(req.user)
{
return next();
}
res.status(401).json({message: "You are Unauthorized to do that"});
}

export default isLoggedIn;
12 changes: 0 additions & 12 deletions server/models/map.js

This file was deleted.

27 changes: 27 additions & 0 deletions server/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import mongoose from "mongoose";
import findOrCreate from "mongoose-findorcreate";
const Schema = mongoose.Schema;

const userSchema = new Schema({


googleId: {
type: String,
required: true
},
username: {
type: String,
// required: [true, "Name cannot be empty!"]
},
email: {
type: String,
// required: [true, "Email cannot be empty!"]
},
password: {
type: String,
// required: [true, "Password cannot be empty!"]
}
});
userSchema.plugin(findOrCreate);
const User = mongoose.model("User", userSchema);
export default User;
43 changes: 43 additions & 0 deletions server/oauth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import passport from "passport";
import {Strategy as GoogleStrategy} from "passport-google-oauth20";
import dotenv from "dotenv";
import User from "./models/user.js";
dotenv.config();

passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:4000/google/callback/",
passReqToCallback: true
},
async (req, accessToken, refreshToken, profile, cb) => {

const user = await User.findOrCreate({googleId: profile.id}, function(err, user){
console.log(user);
return cb(err, user);
})

}));

passport.serializeUser((user, cb) => {
// done(null, user.id);
// console("Serializing user", user);
cb(null, user.id);
});

passport.deserializeUser(async(id, cb)=>{
const user = await User.findOne({where: {id}}).catch((err) => {
console.log("Error in deserializing");
cb(err, null);
});

if(user)
{
cb(null, user);
}

});




7 changes: 6 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@
"author": "Vijay-Kewal",
"license": "MIT",
"dependencies": {
"cookie-session": "^2.0.0",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.2",
"express-session": "^1.17.2",
"html": "^1.0.0",
"mapbox-gl": "^2.7.0",
"mongoose": "^6.2.0",
"nodemon": "^2.0.15"
"mongoose-findorcreate": "^3.0.0",
"nodemon": "^2.0.15",
"passport": "^0.5.2",
"passport-google-oauth20": "^2.0.0"
}
}
3 changes: 2 additions & 1 deletion server/routes/customer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import express from "express";
const router = express.Router();
import { getCustomer, createCustomer, viewCustomer } from "../controllers/customers.js";
import isLoggedIn from "../middleware.js";

router.get("/", getCustomer);
router.get("/", isLoggedIn, getCustomer);
router.get("/:id", viewCustomer);

router.post("/new", createCustomer);
Expand Down
Loading

0 comments on commit e79d293

Please sign in to comment.