1'use strict';
2
3const functions = require('firebase-functions');
4const jws = require('jsonwebtoken');
5
6function cert_to_x5c(cert) {
7  return cert.replace(/-----[^\n]+\n?/gm, '').replace(/\n/g, '');
8}
9
10exports.requestAccessToken = functions.https.onCall((data, context) => {
11  if (!context.auth) {
12    throw new functions.https.HttpsError('failed-precondition', 'Unauthorized user');
13  }
14
15  const payload = {
16    nonce: data.nonce,
17    deviceId: data.deviceId,
18    restrictions: { 'no_debugging_features': false }
19  };
20  functions.logger.log("Payload: ", payload);
21  const config = functions.config().api_config;
22  const options = {
23    algorithm: 'RS256',
24    expiresIn: config.expiration,
25    issuer: config.issuer,
26    audience: config.audience,
27    header: { x5c: config.certificates.map(cert_to_x5c) }
28  };
29  const token = jws.sign(payload, config.key, options);
30  functions.logger.log("Signed Token: ", token);
31  return { token: token };
32});
33