<commit_before>/**
 * React Starter Kit for Firebase
 * https://github.com/kriasoft/react-firebase-starter
 * Copyright (c) 2015-present Kriasoft | MIT License
 */

/* @flow */

import cookie from 'cookie';
import firebase from 'firebase-admin';
import request from 'request-promise-native';
import { config } from 'firebase-functions';

const apiKey = process.env.FIREBASE_API_KEY || config().api.key;
const tokenUrl = `https://securetoken.googleapis.com/v1/token?key=${apiKey}`;

const sessKey = '__session';
const sessOpt = {
  httpOnly: true,
  maxAge: 60 * 60 * 24 * 365 * 10 /* 10 years */,
  secure: !!process.env.GCP_PROJECT,
};

/**
 * Authentication middleware for Express.js
 */
export default async function authenticate(req, res, next) {
  // Try to obtain Firebase ID and refresh tokens from the session cookie
  const cookies = req.headers.cookie || '';
  const tokens = (cookie.parse(cookies)[sessKey] || '').split(':');

  // Check if the provided Firebase ID token is valid
  if (tokens[0]) {
    try {
      req.user = await firebase.auth().verifyIdToken(tokens[0]);
    } catch (err) {
      if (err.message.includes('auth/id-token-expired') && tokens[1]) {
        try {
          const { id_token: idToken } = await request.post({
            url: tokenUrl,
            form: {
              grant_type: 'refresh_token',
              refresh_token: tokens[1],
            },
            json: true,
          });
          req.user = await firebase.auth().verifyIdToken(idToken);
          res.cookie(sessKey, `${idToken}:${tokens[1]}`, sessOpt);
        } catch (e) {
          console.error(e);
        }
      } else {
        console.error(err);
      }
    }
  }

  req.user = req.user || null;
  req.signIn = async (idToken, refreshToken) => {
    res.cookie(sessKey, `${idToken}:${refreshToken}`, sessOpt);
  };
  req.signOut = () => {
    res.clearCookie(sessKey, sessOpt);
  };

  next();
}<commit_msg>Add header.referer to the Token Service API request (#293)<commit_after>/**
 * React Starter Kit for Firebase
 * https://github.com/kriasoft/react-firebase-starter
 * Copyright (c) 2015-present Kriasoft | MIT License
 */

/* @flow */

import cookie from 'cookie';
import firebase from 'firebase-admin';
import request from 'request-promise-native';
import { config } from 'firebase-functions';

const apiKey = process.env.FIREBASE_API_KEY || config().api.key;
const tokenUrl = `https://securetoken.googleapis.com/v1/token?key=${apiKey}`;

const sessKey = '__session';
const sessOpt = {
  httpOnly: true,
  maxAge: 60 * 60 * 24 * 365 * 10 /* 10 years */,
  secure: !!process.env.GCP_PROJECT,
};

/**
 * Authentication middleware for Express.js
 */
export default async function authenticate(req, res, next) {
  // Try to obtain Firebase ID and refresh tokens from the session cookie
  const cookies = req.headers.cookie || '';
  const tokens = (cookie.parse(cookies)[sessKey] || '').split(':');

  // Check if the provided Firebase ID token is valid
  if (tokens[0]) {
    try {
      req.user = await firebase.auth().verifyIdToken(tokens[0]);
    } catch (err) {
      if (err.message.includes('auth/id-token-expired') && tokens[1]) {
        try {
          const { id_token: idToken } = await request.post({
            url: tokenUrl,
            form: {
              grant_type: 'refresh_token',
              refresh_token: tokens[1],
            },
            json: true,
            headers: {
              Referer: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
            },
          });
          req.user = await firebase.auth().verifyIdToken(idToken);
          res.cookie(sessKey, `${idToken}:${tokens[1]}`, sessOpt);
        } catch (e) {
          console.error(e);
        }
      } else {
        console.error(err);
      }
    }
  }

  req.user = req.user || null;
  req.signIn = async (idToken, refreshToken) => {
    res.cookie(sessKey, `${idToken}:${refreshToken}`, sessOpt);
  };
  req.signOut = () => {
    res.clearCookie(sessKey, sessOpt);
  };

  next();
}
{'fraction_non_alphanumeric': 0.15550595238095238, 'fraction_numerical': 0.012152777777777778, 'mean_word_length': 2.6797445255474455, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2182469', 'n_tokens_mistral': 1323, 'n_tokens_neox': 1268, 'n_words': 299}