Skip to content

Instantly share code, notes, and snippets.

@Tosinkoa
Last active October 17, 2022 19:47
Show Gist options
  • Save Tosinkoa/ba4ba0bc6026ff834bf95d0c40f14ced to your computer and use it in GitHub Desktop.
Save Tosinkoa/ba4ba0bc6026ff834bf95d0c40f14ced to your computer and use it in GitHub Desktop.
-----------------------------------server.js----------------------------------------
************************************************************************************
import express from "express"
import rootRoute from "./src/root_Route.js"
import cookieParser from "cookie-parser"
import passport from "passport"
import connectPgSimple from "connect-pg-simple"
import session from "express-session"
import dotenv from "dotenv"
import cors from "cors"
import "./src/LIB/DB-Client.js"
import "./src/PASSPORT_STRATEGY/google-auth-strategy.js"
import "./src/PASSPORT_STRATEGY/facebook-auth-strategy.js"
import OpenNewEntry from "./src/Actions/OpenNewEntry.js"
import pool from "./src/LIB/DB-Client.js"
dotenv.config()
const app = express()
const connection = process.env.DATABASE_URL
app.use(
cors({
origin: ["mydomain.com"],
// origin: ["http://localhost:3000"],
credentials: true,
methods: "GET, PUT, POST, DELETE",
optionsSuccessStatus: 200,
})
)
const PgStore = connectPgSimple(session)
const store = new PgStore({ conString: connection, schemaName: "hidden", createTableIfMissing: true })
app.use(express.json())
app.use(cookieParser(process.env.SESSION_SECRET))
app.set("trust proxy", 1)
app.use(
session({
store: store,
secret: process.env.SESSION_SECRET,
saveUninitialized: true,
resave: true,
proxy: true,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
httpOnly: true,
sameSite: process.env.NODE_ENV === "production" ? 'none' : 'lax',
secure: process.env.NODE_ENV === "production" ? true : false,
},
})
)
app.use(passport.initialize())
app.use(passport.session())
app.get("/", (req, res) => {
res.send("API Running...")
})
rootRoute(app)
const PORT = process.env.PORT || 4000
app.listen(PORT, (req, res) => console.log(`Server running on PORT:${PORT}...`))
-----------------------------------GOOGLE AUTH LOGIC-----------------------------------
***************************************************************************************
import express from "express"
import passport from "passport"
const router = express.Router()
router.get(
"/auth/google",
passport.authenticate("google", {
scope: ["email", "profile"],
})
)
router.get(
"/auth/google/callback",
passport.authenticate("google", {
successRedirect: "/auth/google/success",
failureRedirect: "/auth/google/failed"
})
)
router.get("/auth/google/success", async (req, res) => {
if (!req.user) return res.redirect(`${process.env.FRONTEND_URL}/auth/login`)
req.session.regenerate(async () => {
req.session.user = req.user
return res.redirect(`${process.env.FRONTEND_URL}/profile`)
})
})
router.get("/auth/google/failed", (req, res) => {
return res.redirect(`${process.env.FRONTEND_URL}/auth/login`)
})
export default router
---------------------------------google-auth-strategy.js------------------------------
**************************************************************************************
import passport from "passport"
import theGoogleStrategy from "passport-google-oauth2"
import bcrypt from "bcryptjs"
import { v4 as uuidv4 } from 'uuid';
import pool from "../LIB/DB-Client.js"
const GoogleStrategy = theGoogleStrategy.Strategy
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: `${process.env.BACKEND_URL}/auth/google/callback`,
passReqToCallback: true,
},
async (request, accessToken, refreshToken, profile, done) => {
try {
let user
const account = profile._json
console.log(account)
const userWhoWantToSignin = await pool.query("SELECT email, google_user FROM users WHERE email = $1", [
account.email,
])
if (userWhoWantToSignin.rowCount > 0 && userWhoWantToSignin.rows[0].google_user === false) {
return done(null, false)
}
const userTokenAlreadyExist = await pool.query("SELECT token FROM verify_token WHERE token = $1", [account.sub])
const hashedPassword = bcrypt.hashSync(process.env.GOOGLE_USER_PASSWORD, 10)
if (userTokenAlreadyExist.rowCount < 1 && userWhoWantToSignin.rowCount < 1) {
const NewUser = await pool.query(
"INSERT INTO users (first_name, last_name, email, profile_image, profile_image_id, password, verified, google_user) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *",
[
account.given_name ?? account.family_name,
account.family_name ?? account.given_name,
account.email,
account.picture,
process.env.DEFAULT_PROFILE_IMAGE_ID,
hashedPassword,
true,
true,
]
)
const uniqueToken = uuidv4();
await pool.query("INSERT INTO verify_token ( user_id, token) VALUES ($1, $2) RETURNING *", [
NewUser.rows[0].id,
uniqueToken,
])
user = NewUser.rows[0].id
console.log(user)
return done(null, user)
} else {
const updatedUser = await pool.query("SELECT email, id FROM users WHERE email = $1", [account.email])
await pool.query("UPDATE verify_token SET token = $1 WHERE user_id = $2", [
account.sub,
updatedUser.rows[0].id,
])
user = updatedUser.rows[0].id
return done(null, user)
}
} catch (error) {
console.log(error)
done(error)
}
}
)
)
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser(async (user, done) => {
done(null, user)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment