UNPKG

authkit-js

Version:

Express auth toolkit (JWT, Sessions with Redis, Google/GitHub OAuth) in JavaScript

26 lines (22 loc) 1.13 kB
// Minimal Google OAuth2 flow using google-auth-library const { OAuth2Client } = require('google-auth-library'); class GoogleOAuthStrategy { constructor({ clientId, clientSecret, redirectUri, verify }) { if (!clientId || !clientSecret || !redirectUri) throw new Error('GoogleOAuth: missing credentials'); this.client = new OAuth2Client(clientId, clientSecret, redirectUri); this.verify = verify || (async (payload) => ({ id: payload.sub, email: payload.email })); } getAuthUrl(scope = ['profile', 'email']) { return this.client.generateAuthUrl({ access_type: 'offline', scope }); } async handleCallback(code) { const { tokens } = await this.client.getToken(code); this.client.setCredentials(tokens); if (!tokens.id_token) throw new Error('Missing id_token'); const ticket = await this.client.verifyIdToken({ idToken: tokens.id_token, audience: this.client._clientId }); const payload = ticket.getPayload(); const user = await this.verify(payload, tokens); return { user, tokens, profile: payload }; } } module.exports = { GoogleOAuthStrategy };