Skip to content

Instantly share code, notes, and snippets.

@Tosinkoa
Created September 7, 2022 17:36
Show Gist options
  • Save Tosinkoa/436aa1a6b869bff4bf0bbb9d96e224ba to your computer and use it in GitHub Desktop.
Save Tosinkoa/436aa1a6b869bff4bf0bbb9d96e224ba to your computer and use it in GitHub Desktop.
// Google auth logic
const { generateFromEmail } = require("unique-username-generator")
const passport = require("passport")
const GoogleStrategy = require("passport-google-oauth2").Strategy
const bcrypt = require("bcryptjs")
const crypto = require("crypto")
const pool = require("../LIB/DB-Client")
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL,
passReqToCallback: true,
},
async (request, accessToken, refreshToken, profile, done) => {
try {
let user
const account = profile._json
const userAlreadyExist = await pool.query("SELECT email FROM users WHERE email = $1", [account.email])
if (userAlreadyExist.rowCount > 0 && userAlreadyExist.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 username = generateFromEmail(account.email, 6)
const hashedPassword = bcrypt.hashSync(process.env.GOOGLE_USER_PASSWORD, 10)
if (userTokenAlreadyExist.rowCount < 1 && userAlreadyExist.rowCount < 1) {
await pool.query(
"INSERT INTO users (first_name, last_name, email, username, profile_image, profile_image_id, password, verified, google_user) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *",
[
account.given_name ?? account.family_name,
account.family_name ?? account.given_name,
account.email,
username,
process.env.DEFAULT_PROFILE_IMAGE,
process.env.DEFAULT_PROFILE_IMAGE_ID,
hashedPassword,
true,
true,
]
)
const validUser = await pool.query("SELECT email, id FROM users WHERE email = $1", [account.email])
const uniqueToken = crypto.randomBytes(36).toString("hex")
await pool.query("INSERT INTO verify_token ( user_id, token) VALUES ($1, $2) RETURNING *", [
validUser.rows[0].id,
uniqueToken,
])
user = validUser.rows[0].id
} 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
}
done(null, user)
} catch (error) {
console.log(error)
done(error)
}
}
)
)
passport.serializeUser(function (user, done) {
done(null, user)
})
passport.deserializeUser(function (user, done) {
done(null, user)
})
// Login logic
const router = require("express").Router()
const bcrypt = require("bcryptjs")
const { validateLoginUser } = require("../../../VALIDATORS/LoginUserValidator")
const pool = require("../../../LIB/DB-Client")
router.post("/login", async (req, res) => {
const { error, value } = validateLoginUser(req.body)
if (error) return res.status(400).json({ error: error.details.map((e) => e.context.label) })
const { email, password } = req.body
try {
const data = await pool.query("SELECT id, email, verified, password FROM users WHERE email = $1", [email])
console.log("data", data)
if (data.rowCount < 1) {
return res.status(401).json({ error: "You're unauthorized" })
}
const user = data.rows[0]
console.log("user", user)
const matches = bcrypt.compareSync(password, user.password)
const googleUser = bcrypt.compareSync(password, user.password)
if (password === process.env.GOOGLE_USER_PASSWORD || googleUser)
return res.status(400).json({ error: "Pls use a valid password" })
if (!matches) return res.status(400).json({ error: "Wrong email or password" })
if (user.verified === false) return res.status(400).json({ error: "Pls check your email to verify your account." })
req.session.user = validToken.rows[0].user_id
return res.status(200).json({ data: "Logged in successfully" })
} catch (e) {
console.error(e)
return res.status(500)
}
})
module.exports = router
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment