Skip to content

Instantly share code, notes, and snippets.

@shadow1349
Created July 6, 2020 22:53
Show Gist options
  • Save shadow1349/0823ce08804a1f830db4a3402b31ec29 to your computer and use it in GitHub Desktop.
Save shadow1349/0823ce08804a1f830db4a3402b31ec29 to your computer and use it in GitHub Desktop.
Firebase Functions Express API
import * as express from 'express';
import * as cors from 'cors';
import * as bodyParser from 'body-parser';
import * as sentry from '@sentry/node';
import * as admin from 'firebase-admin';
import { APIResponse } from '@sredmond/apiresponse';
import * as functions from 'firebase-functions';
const app = express();
const options: cors.CorsOptions = {
origin: true
};
/**
* Setup App
*/
app.use(cors(options));
app.disable('x-powered-by');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
/**********************************************************************************
* MAIN FUNCTION - Verifies that user has the correct access rights to make calls *
**********************************************************************************/
app.use('/v1', async (req: express.Request, res: express.Response, next: express.NextFunction) => {
try {
let token: string = '';
if (req.headers.authorization && req.headers.authorization.toString().startsWith('Bearer ')) {
token = req.headers.authorization.toString().split('Bearer ')[1];
sentry.addBreadcrumb({ message: 'Got Token From Request', data: token });
} else {
return new APIResponse({ success: false, status: 401 }).Send(res);
}
//Decode the token user's firebase ID
const decodedToken = await admin
.auth()
.verifyIdToken(token)
.catch(err => new APIResponse({ success: false, status: 401 }).Send(res));
sentry.addBreadcrumb({ message: 'Decoded Token', data: decodedToken });
//Check the token exists
if (decodedToken) {
req['user'] = decodedToken;
sentry.addBreadcrumb({ message: 'API - User', data: req['user'] });
const uid = decodedToken['user_id'];
if (!uid) {
return new APIResponse({ success: false, status: 401 }).Send(res);
}
//Expression has type void put it on its own line
next();
return null;
} else {
return new APIResponse({ success: false, status: 401 }).Send(res);
}
} catch (e) {
return new APIResponse({ success: false, body: e, status: 500 }).Send(res);
}
});
// You can use your custom express router like normal
import { myRouter } from './someroute';
app.use('/myroute', myRouter);
/*************************************
* Main function to use the redirect *
*************************************/
const main = express();
main.use('/api', app);
/***********************
* Export API *
***********************/
export const API = functions.https.onRequest(main);
import * as express from 'express';
const myRouter = express.Router();
// set up your router how you would normally
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment