authkit-js
Version:
Express auth toolkit (JWT, Sessions with Redis, Google/GitHub OAuth) in JavaScript
44 lines (37 loc) • 1.99 kB
JavaScript
// Facebook OAuth2 minimal implementation
// Uses global fetch when available; falls back to node-fetch
const fetch = globalThis.fetch || ((...args) => import('node-fetch').then(m => m.default(...args)));
class FacebookOAuthStrategy {
constructor({ clientId, clientSecret, redirectUri, verify }) {
if (!clientId || !clientSecret || !redirectUri) throw new Error('FacebookOAuth: missing credentials');
this.clientId = clientId; this.clientSecret = clientSecret; this.redirectUri = redirectUri;
this.verify = verify || (async (profile) => ({ id: profile.id, name: profile.name, email: profile.email }));
}
getAuthUrl(scope = ['email']) {
const u = new URL('https://www.facebook.com/v12.0/dialog/oauth');
u.searchParams.set('client_id', this.clientId);
u.searchParams.set('redirect_uri', this.redirectUri);
u.searchParams.set('response_type', 'code');
u.searchParams.set('scope', Array.isArray(scope) ? scope.join(',') : scope);
return u.toString();
}
async handleCallback(code) {
// Exchange code for access token
const tokenUrl = new URL('https://graph.facebook.com/v12.0/oauth/access_token');
tokenUrl.searchParams.set('client_id', this.clientId);
tokenUrl.searchParams.set('client_secret', this.clientSecret);
tokenUrl.searchParams.set('redirect_uri', this.redirectUri);
tokenUrl.searchParams.set('code', code);
const tokenRes = await fetch(tokenUrl.toString(), { method: 'GET' }).then(r => r.json());
if (!tokenRes.access_token) throw new Error('Facebook OAuth: no access_token');
const accessToken = tokenRes.access_token;
// Fetch user profile
const profileUrl = new URL('https://graph.facebook.com/me');
profileUrl.searchParams.set('fields', 'id,name,email');
profileUrl.searchParams.set('access_token', accessToken);
const profile = await fetch(profileUrl.toString()).then(r => r.json());
const user = await this.verify(profile, accessToken);
return { user, accessToken, profile };
}
}
module.exports = { FacebookOAuthStrategy };