in ReferenceAppKotlin/firebase/server/src/controller/functions/authentication.ts [564:613]
async function handleStreamlinedLinkOrCreate(
user_id: string, client_id: string, res: functions.Response) {
const db = firebase.app().firestore();
try {
// Generate tokens
const access_token = await generateToken(32, 'token');
const refresh_token = await generateToken(64, 'token');
// Check for existing tokens db entry
const token_snapshot = await db.collection('tokens')
.where('client_id', '==', client_id)
.where('user_id', '==', user_id)
.get();
if (token_snapshot.empty) {
// Add new db entry
await db.collection('tokens').add({
client_id: client_id,
user_id: user_id,
scope: [], // TODO (nevmital@): Introduce scoping?
refresh_token: refresh_token,
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
created_on: Date.now()
});
} else {
// Update db entry
await token_snapshot.docs[0].ref.set({
client_id: client_id,
user_id: user_id,
scope: [], // TODO (nevmital@): Introduce scoping?
refresh_token: refresh_token,
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
created_on: Date.now()
});
}
// Return tokens if database write is successful
res.status(200).send({
access_token: access_token,
expires_in: ACCESS_TOKEN_EXPIRY,
refresh_token: refresh_token,
token_type: 'Bearer'
});
} catch (err) {
// Return linking_error if database write unsuccessful
console.log(err);
res.status(401).send({error: 'linking_error', error_description: err});
}
}