A Passport.js Google OAuth2.0 strategy service.
npm install googleauthsso
const googleOAuth20Service = require('googleauthsso');
const authArgs = {
serverInstance: app, // Express app instance
passport: passport, // Passport instance
config: {
GOOGLE_CLIENT_ID: 'your-client-id',
GOOGLE_CLIENT_SECRET: 'your-client-secret',
GOOGLE_CALLBACK_URL: 'your-callback-url',
SESSION_SECRET: 'your-session-secret'
},
redirection: {
success: '/dashboard', // Successful login redirect
failure: '/' // Failed login redirect
},
dboperation: async () => {
// Database operation for finding/creating a user
}
};
googleOAuth20Service(authArgs);
Ensure the following environment variables are set
GOOGLE_CLIENT_ID
GOOGLE_CLIENT_SECRET
GOOGLE_CALLBACK_URL
SESSION_SECRET
or
you can also setup it in by creating config obj with creadentials like
let config={
GOOGLE_CLIENT_ID:"your google client id",////you can get it from google developers console login
GOOGLE_CLIENT_SECRET:"your google client secret", //you can get it from google developers console login
GOOGLE_CALLBACK_URL:"callback url", // it would be like "http://localhost:3000/auth/google/callback"
SESSION_SECRET:"user defined secret" //can be anything according to user
}
const express = require("express");
const passport = require("passport");
const googleOAuth20Service = require("googleauthsso");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
// Initialize Google OAuth 2.0 service
googleOAuth20Service({
serverInstance: app,
passport: passport,
config: {
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
GOOGLE_CALLBACK_URL: process.env.GOOGLE_CALLBACK_URL,
SESSION_SECRET: process.env.SESSION_SECRET,
},
redirection: {
success: "/dashboard",
failure: "/login",
},
//dboperation is optional field
dboperation: async () => {
// Implement your database operation here
// E.g., find or create a user in your database
return null; // Replace with actual user object
},
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
-
Customization: Make sure to replace placeholder values like
your_google_client_id
,your_google_client_secret
, andyour_session_secret
,callback url
with actual values. -
Database Operation: The
dboperation
function in the example is a placeholder for your database logic. You should implement this according to your application's requirements. -
License: If you have a specific license for your package, include it in the
LICENSE
file and reference it in the README.
Feel free to modify any sections as per your needs!
if you have any suggestion so you can email shivasoni8528@gmail
Shiva Soni
MIT