next-firebase-auth-edge
Version:
Next.js Firebase Authentication for Edge and server runtimes. Compatible with latest Next.js features.
50 lines (49 loc) • 1.92 kB
JavaScript
import { ServiceAccountCredential } from '../auth/credential';
import { getApplicationDefault } from '../auth/default-credential.js';
import { cryptoSignerFromCredential } from '../auth/token-generator.js';
import { AppCheckApiClient } from './api-client.js';
import { AppCheckTokenGenerator } from './token-generator.js';
import { AppCheckTokenVerifier } from './token-verifier.js';
class AppCheck {
client;
tokenGenerator;
appCheckTokenVerifier;
constructor(credential, tenantId) {
this.client = new AppCheckApiClient(credential);
this.tokenGenerator = new AppCheckTokenGenerator(cryptoSignerFromCredential(credential, tenantId));
this.appCheckTokenVerifier = new AppCheckTokenVerifier(credential);
}
createToken = (appId, options) => {
return this.tokenGenerator
.createCustomToken(appId, options)
.then((customToken) => {
return this.client.exchangeToken(customToken, appId);
});
};
verifyToken = (appCheckToken, options) => {
return this.appCheckTokenVerifier
.verifyToken(appCheckToken, options)
.then((decodedToken) => {
return {
appId: decodedToken.app_id,
token: decodedToken
};
});
};
}
function isAppCheckOptions(options) {
const serviceAccount = options;
return (!serviceAccount.privateKey ||
!serviceAccount.projectId ||
!serviceAccount.clientEmail);
}
export function getAppCheck(serviceAccount, tenantId) {
if (!isAppCheckOptions(serviceAccount)) {
return new AppCheck(new ServiceAccountCredential(serviceAccount), tenantId);
}
const options = serviceAccount;
const credential = options.serviceAccount
? new ServiceAccountCredential(options.serviceAccount)
: getApplicationDefault();
return new AppCheck(credential, tenantId);
}