@bernierllc/google-drive-oauth
v0.2.2
Published
OAuth 2.0 authentication and token management for Google Drive
Downloads
270
Readme
@bernierllc/google-drive-oauth
OAuth 2.0 authentication and token management for Google Drive.
Features
- OAuth 2.0 authorization URL generation
- Authorization code exchange for access tokens
- Automatic token refresh with refresh tokens
- Token validation and expiration checking
- Secure credential storage interfaces
- Multi-user token management
Installation
npm install @bernierllc/google-drive-oauthUsage
Basic Authentication Flow
import { GoogleDriveOAuth } from '@bernierllc/google-drive-oauth';
// Create auth instance
const driveAuth = new GoogleDriveOAuth({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'https://your-app.com/oauth/google-drive/callback'
});
// Step 1: Generate authorization URL
const { url, state } = driveAuth.getAuthorizationUrl();
// Store state in session for CSRF protection
// Redirect user to url
// Step 2: Exchange authorization code for tokens
const tokens = await driveAuth.exchangeCodeForTokens(code, state);
console.log('Access token:', tokens.accessToken);
console.log('Refresh token:', tokens.refreshToken);Token Refresh
// Manually refresh token
const newTokens = await driveAuth.refreshAccessToken(refreshToken);
// Or use automatic refresh with storage
const storage: TokenStorage = {
async store(key, tokens) {
// Store tokens in your database
await db.saveTokens(key, tokens);
},
async retrieve(key) {
// Retrieve tokens from your database
return await db.getTokens(key);
},
async delete(key) {
// Delete tokens from your database
await db.deleteTokens(key);
}
};
const authWithStorage = new GoogleDriveOAuth(config, storage);
// Automatically refreshes if token is expired
const validToken = await authWithStorage.getValidToken('user-123');Token Validation
const isValid = await driveAuth.validateToken(accessToken);
if (!isValid) {
console.log('Token is invalid or expired');
}API
GoogleDriveOAuth
Constructor
constructor(config: GoogleDriveOAuthConfig, storage?: TokenStorage)config.clientId- Google OAuth client IDconfig.clientSecret- Google OAuth client secretconfig.redirectUri- OAuth redirect URIconfig.logger- (Optional) Custom logger instancestorage- (Optional) Token storage implementation
Methods
getAuthorizationUrl(state?: string, scopes?: string[]): { url: string; state: string }
Generate OAuth authorization URL.
exchangeCodeForTokens(code: string, state: string): Promise<GoogleDriveOAuthTokens>
Exchange authorization code for access and refresh tokens.
refreshAccessToken(refreshToken: string): Promise<GoogleDriveOAuthTokens>
Refresh access token using refresh token.
validateToken(accessToken: string): Promise<boolean>
Validate access token against Google Drive API.
getValidToken(storageKey: string): Promise<string>
Get a valid access token, automatically refreshing if expired (requires storage).
storeTokens(key: string, tokens: GoogleDriveOAuthTokens): Promise<void>
Store tokens (requires storage).
revokeTokens(storageKey: string): Promise<void>
Revoke and delete tokens (requires storage).
TokenStorage Interface
interface TokenStorage {
store(key: string, tokens: GoogleDriveOAuthTokens): Promise<void>;
retrieve(key: string): Promise<GoogleDriveOAuthTokens | null>;
delete(key: string): Promise<void>;
}Implement this interface to provide persistent token storage.
Token Expiration
Tokens are automatically refreshed when:
- Less than 5 minutes remaining before expiration
getValidToken()is called with valid refresh token
Error Handling
try {
const tokens = await driveAuth.exchangeCodeForTokens(code, state);
} catch (error) {
console.error('OAuth failed:', error.message);
}All methods throw descriptive errors on failure.
Integration
Logger Integration
This package uses @bernierllc/logger for structured logging. The logger is optional and will use a no-op logger if not provided.
License
Copyright (c) 2025 Bernier LLC. See LICENSE file for details.
