This repository has been archived by the owner on Oct 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
163 lines (140 loc) · 4.67 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import { studies } from "./studies";
import { v4 as uuidv4 } from "uuid";
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
export const rallytoken = functions.https.onRequest(
async (request, response) => {
response.set("Access-Control-Allow-Origin", "*");
response.set("Access-Control-Allow-Headers", "Content-Type");
if (request.method === "OPTIONS") {
response.set("Access-Control-Allow-Methods", "POST");
response.set("Access-Control-Allow-Headers", "Bearer, Content-Type");
response.status(204).send("");
} else if (request.method === "POST") {
functions.logger.info(`body type: ${typeof request.body}`, {
payload: request.body,
});
try {
let idToken;
let studyId;
if (typeof request.body === "string") {
const body = JSON.parse(request.body);
idToken = body.idToken;
studyId = body.studyId;
} else {
idToken = request.body.idToken;
studyId = request.body.studyId;
}
const rallyToken = await generateToken(idToken, studyId);
functions.logger.info("OK");
response.status(200).send({ rallyToken });
} catch (ex) {
functions.logger.error(ex);
response.status(500).send();
}
} else {
response.status(500).send("Only POST and OPTIONS methods are allowed.");
}
}
);
/**
* Takes a Firebase IDToken for a Rally user, and returns a Rally Token
* for a restricted-access account (for use with studies).
*
* @param {string} idToken Firebase IDToken.
* @param {string} studyId Rally study ID.
* @return {Promise<string>} rallyToken
*/
async function generateToken(idToken: string, studyId: string) {
const decodedToken = await admin.auth().verifyIdToken(idToken);
// Firebase will create this account if it does not exist,
// when the token is first used to sign-in.
const uid = `${studyId}:${decodedToken.uid}`;
const rallyToken = await admin
.auth()
.createCustomToken(uid, { firebaseUid: decodedToken.uid, studyId });
return rallyToken;
}
exports.addRallyUserToFirestore = functions.auth
.user()
.onCreate(async (user) => {
functions.logger.info("addRallyUserToFirestore - onCreate fired for user", {
user,
});
if (user.providerData.length == 0) {
functions.logger.info("Extension users do not get user docs.");
return;
}
const newRallyId = uuidv4();
const extensionUserDoc = { rallyId: newRallyId };
admin
.firestore()
.collection("extensionUsers")
.doc(user.uid)
.set(extensionUserDoc, { merge: true });
const userDoc = {
createdOn: new Date(),
uid: user.uid,
};
admin
.firestore()
.collection("users")
.doc(user.uid)
.set(userDoc, { merge: true });
return true;
});
exports.deleteRallyUser = functions.auth.user().onDelete(async (user) => {
functions.logger.info("deleteRallyUser fired for user:", user);
// Delete the extension user document.
await admin.firestore().collection("extensionUsers").doc(user.uid).delete();
// Delete the user studies subcollection.
const collectionRef = admin
.firestore()
.collection("users")
.doc(user.uid)
.collection("studies");
// There will be one document per study here, use batching in case it ever goes over the limit.
// Work in batches of 5: https://firebase.google.com/docs/firestore/manage-data/transactions#security_rules_limits
let batch = admin.firestore().batch();
const userStudyDocs = await collectionRef.get();
for (const [count, userStudyDoc] of userStudyDocs.docs.entries()) {
batch.delete(userStudyDoc.ref);
// Count is 0-based, so commit on multiples of 4.
if (count % 4 === 0) {
await batch.commit();
batch = admin.firestore().batch();
}
}
// Do a final commit in case we ended on a partial batch.
await batch.commit();
// Finally, delete the user document.
await admin.firestore().collection("users").doc(user.uid).delete();
return true;
});
/**
*
* @param {string} index The firestore key.
* @param {object} study The study object.
*/
function addRallyStudyToFirestore(
index: string,
study: Record<string, unknown>
) {
admin
.firestore()
.collection("studies")
.doc(index)
.set(study, { merge: true });
}
export const loadFirestore = functions.https.onRequest(
async (request, response) => {
for (const [index, study] of Object.entries(studies)) {
console.info(`Loading study ${index} into Firestore`);
addRallyStudyToFirestore(index, study);
}
response.status(200).send();
}
);