Skip to content
This repository was archived by the owner on May 6, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,14 @@ const withFirebaseUser: (
interface WithFirebaseUserOptions {
clientCertUrl?: string; // defaults to url provided in Firebase auth docs
projectId?: string; // verifies the audience and issuer of the JWT when provided
isEmulator?: boolean; // defaults to false
}
```

## Contributing

Feel free

## License

Do whatever you want with this code
15 changes: 15 additions & 0 deletions src/utils/fetchPublicKeys.ts → src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,18 @@ export function fetchPublicKeys(
});
});
}

export function decodeJwtHeader(jwt: string) {
const [base64] = jwt.split('.');
const buffer = Buffer.from(base64, 'base64');
return buffer.toString();
}

export function getBearerToken(auth?: string) {
if (auth) {
const [scheme, credentials] = auth.split(' ');
if (scheme.toLocaleLowerCase() === 'bearer') {
return credentials;
}
}
}
8 changes: 0 additions & 8 deletions src/utils/headers.ts

This file was deleted.

5 changes: 0 additions & 5 deletions src/utils/jwt.ts

This file was deleted.

38 changes: 22 additions & 16 deletions src/withFirebaseUser.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import type { NextApiRequestWithFirebaseUser, FirebaseUser } from './types';
import jwt from 'jsonwebtoken';
import { getBearerToken } from './utils/headers';
import { decodeJwtHeader } from './utils/jwt';
import { fetchPublicKeys } from './utils/fetchPublicKeys';
import jwt, { JwtPayload } from 'jsonwebtoken';
import { getBearerToken, decodeJwtHeader, fetchPublicKeys } from './utils';

const FIREBASE_AUTH_CERT_URL =
'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com';
interface WithFirebaseUserOptions {
clientCertUrl?: string;
projectId?: string;
isEmulator: boolean;
}

const FIREBASE_AUTH_CERT_URL =
'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com';

export const withFirebaseUser =
(
handler: (
Expand All @@ -22,15 +22,16 @@ export const withFirebaseUser =
) =>
async (req: NextApiRequest, res: NextApiResponse) => {
// merge options with defaults
const { projectId, clientCertUrl } = Object.assign(
const { projectId, clientCertUrl, isEmulator } = Object.assign(
{},
{
clientCertUrl: FIREBASE_AUTH_CERT_URL,
isEmulator: false,
},
options
);

// copy request object for decoration with firebase user
// copy request object
const decoratedReq: NextApiRequestWithFirebaseUser = Object.assign(
{},
req,
Expand All @@ -53,14 +54,19 @@ export const withFirebaseUser =

const publicKey = publicKeys[jwtHeader.kid];
if (publicKey) {
// decode jwt with public key
const decodedToken = jwt.verify(accessToken, publicKey, {
audience: projectId,
issuer: projectId && `https://securetoken.google.com/${projectId}`,
});
let decodedToken: string | JwtPayload | null;

if (isEmulator) {
decodedToken = jwt.decode(accessToken);
} else {
decodedToken = jwt.verify(accessToken, publicKey, {
audience: projectId,
issuer: projectId && `https://securetoken.google.com/${projectId}`,
});
}

if (typeof decodedToken === 'object') {
// create user object we decorate req with from decoded token
if (typeof decodedToken === 'object' && decodedToken !== null) {
// might want to support custom claims in the future
const user: FirebaseUser = {
user_id: decodedToken.user_id ?? decodedToken.sub,
name: decodedToken.name,
Expand All @@ -72,7 +78,7 @@ export const withFirebaseUser =
}
}
} catch (err) {
console.info('withFirebaseUser: ', err);
console.error('withFirebaseUser: ', err);
}

return handler(decoratedReq, res);
Expand Down