Skip to content

Instantly share code, notes, and snippets.

@Ramesh-X
Created December 15, 2020 09:42
Show Gist options
  • Save Ramesh-X/69cd8a1b429996ee005bbd0add75cfdb to your computer and use it in GitHub Desktop.
Save Ramesh-X/69cd8a1b429996ee005bbd0add75cfdb to your computer and use it in GitHub Desktop.
custom-token-backend
const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors');
const admin = require('firebase-admin');
import {Request, Response} from 'express';
if (admin.apps.length === 0) admin.initializeApp();
const mockAuth = async (id: String, passcode: String): Promise<boolean> => {
await new Promise(resolve => setTimeout(resolve, 1000));
return id === 'ABC-1234' && passcode === '123456';
}
const app = express();
app.use(cors({origin: true}));
app.post('/', async (req: Request, res: Response) => {
const id: String = req.body['id'];
const passcode: String = req.body['passcode'];
const authenticated = await mockAuth(id, passcode);
if (!authenticated) {
return res.status(400).send({'msg': 'Invalid id or passcode'});
}
try {
const token = await admin.auth().createCustomToken(`MOCK-${id}`);
return res.status(200).send({
'id': id,
'customToken': token
});
} catch (e) {
return res.status(500).send(`Unexpected error while generating custom token.\n${e}`);
}
});
exports.api = functions.https.onRequest(app);
@Ramesh-X
Copy link
Author

This is example code I wrote to generate custom token from Firebase Admin SDK.

To know about its uses and practical problems that you will face while coding, read the full article here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment