Created
December 15, 2020 09:42
-
-
Save Ramesh-X/69cd8a1b429996ee005bbd0add75cfdb to your computer and use it in GitHub Desktop.
custom-token-backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.