Installing Packages
npm init -y
npm i express express-session ejs dotenv google-auth-library
Directory Structure
.env
1 2 3 4 |
GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= GOOGLE_REDIRECT_URI=http://localhost:3000/auth/google/callback SESSION_SECRET=secret |
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
const express = require('express'); const session = require('express-session'); const { OAuth2Client } = require('google-auth-library'); const path = require('path'); require('dotenv').config(); const app = express(); const PORT = 3000; // Initialize Google OAuth Client const client = new OAuth2Client( process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET, process.env.GOOGLE_REDIRECT_URI ); // Middleware for handling sessions app.use( session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true, }) ); // Set EJS as the template engine app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Home Route app.get('/', (req, res) => { if (req.session.user) { res.render('profile', { user: req.session.user }); } else { res.render('index'); } }); // Google Login Route app.get('/auth/google', (req, res) => { const url = client.generateAuthUrl({ access_type: 'offline', scope: ['profile', 'email'], }); res.redirect(url); }); // Google OAuth Callback Route app.get('/auth/google/callback', async (req, res) => { const code = req.query.code; if (!code) { return res.status(400).send('Invalid request. No authorization code provided.'); } try { // Exchange authorization code for access token const { tokens } = await client.getToken(code); // Verify the token and get user information const ticket = await client.verifyIdToken({ idToken: tokens.id_token, audience: process.env.GOOGLE_CLIENT_ID, }); const payload = ticket.getPayload(); // Save user info in session req.session.user = { name: payload.name, email: payload.email, picture: payload.picture, }; res.redirect('/'); } catch (error) { console.error('Error during Google OAuth callback:', error); res.status(500).send('Authentication failed.'); } }); // Logout Route app.get('/auth/logout', (req, res) => { req.session.destroy((err) => { if (err) { return res.status(500).send('Failed to logout.'); } res.redirect('/'); }); }); // Start the server app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); |
views/index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google Login</title> </head> <body> <h1>Welcome to the Google Login Demo</h1> <a href="/auth/google">Login with Google</a> </body> </html> |
views/profile.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profile</title> <style> .profile-picture { width: 100px; height: 100px; border-radius: 50%; object-fit: cover; } </style> </head> <body> <h1>Welcome, <%= user.name %></h1> <p>Email: <%= user.email %></p> <img src="<%= user.picture %>" alt="Profile Picture" class="profile-picture" /> <br /> <a href="/auth/logout">Logout</a> </body> </html> |