UNPKG

backend-google-login-ts

Version:

A secure and lightweight TypeScript package for handling Google OAuth2 authentication in Node.js backend applications. Simplifies the process of integrating Google login with built-in TypeScript support and zero dependencies.

91 lines (90 loc) 2.93 kB
import https from 'https'; async function exchangeAuthCodeForToken(clientId, clientSecret, redirectUrl, authCode) { const tokenEndpoint = 'https://oauth2.googleapis.com/token'; const postData = JSON.stringify({ client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUrl, grant_type: 'authorization_code', code: authCode, }); const options = { hostname: 'oauth2.googleapis.com', path: '/token', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), }, }; return new Promise((resolve, reject) => { const req = https.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { if (res.statusCode === 200) { resolve(JSON.parse(data)); } else { reject(new Error(`Error: ${data}`)); } }); }); req.on('error', (e) => { reject(e); }); req.write(postData); req.end(); }); } async function getUserInfo(accessToken) { const userInfoEndpoint = 'https://www.googleapis.com/oauth2/v2/userinfo'; const options = { hostname: 'www.googleapis.com', path: '/oauth2/v2/userinfo', method: 'GET', headers: { Authorization: `Bearer ${accessToken}`, }, }; return new Promise((resolve, reject) => { const req = https.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { if (res.statusCode === 200) { resolve(JSON.parse(data)); } else { reject(new Error(`Error fetching user info: ${data}`)); } }); }); req.on('error', (e) => { reject(e); }); req.end(); }); } // This function return userInfo or Error export async function loginWithGoogle(options) { const { clientId, clientSecret, redirectUrl, authCode } = options; if (!clientId || !clientSecret || !redirectUrl || !authCode) { throw new Error('Missing required parameters'); } try { // Get access token from google const tokenData = await exchangeAuthCodeForToken(clientId, clientSecret, redirectUrl, authCode); const accessToken = tokenData.access_token; // Use access token to get userInfo const userInfo = await getUserInfo(accessToken); return userInfo; } catch (error) { throw new Error(`Failed to login with Google: ${error.message}`); } }