Skip to content

Commit

Permalink
Merge pull request #6 from yeatmanlab/cloud-function-docs
Browse files Browse the repository at this point in the history
Cloud Function Documentation
  • Loading branch information
ksmontville committed May 1, 2024
2 parents f9f065b + 2b6dab3 commit 1fc3827
Show file tree
Hide file tree
Showing 64 changed files with 2,388 additions and 573 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ docs/.vuepress/.temp
# VuePress default cache directory
docs/.vuepress/.cache
# VuePress default build output directory
docs/.vuepress/dist
docs/.vuepress/dist

.idea/
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "roar-firebase-functions"]
path = roar-firebase-functions
url = ../roar-firebase-functions.git
2 changes: 1 addition & 1 deletion docs/.vuepress/childPageScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import fs from "fs";

export default function (path) {
const parentPath = path.split("/").slice(-1).join("/");
const parentPath = path.split("/").slice(2).join("/");
var files = fs.readdirSync(path);
var list = [];
for (var i in files) {
Expand Down
19 changes: 17 additions & 2 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ export default defineUserConfig({
base: "roar-docs",

title: "ROAR Developer Documentation",
description: "Documentation for ROAR Developers",
description: "Documentation for developers working on the ROAR - Rapid Online Assessment of Reading Project for Yeatmanlab at Stanford University.",

theme: defaultTheme({
logo: "https://vuejs.press/images/hero.png",
navbar: ["/databases/", "/workflows/", "/cloud-functions/","/internationalization/"],
nextLinks: true,
prevLinks: true,
sidebar: [
{
text: "Databases",
Expand All @@ -37,7 +39,20 @@ export default defineUserConfig({
text: "Cloud Functions",
link: "/cloud-functions/",
collapsable: false,
children: getChildren("./docs/cloud-functions"),
children: [
{
text: "gse-roar-admin",
link: "/cloud-functions/gse-roar-admin/",
collapsable: false,
children: getChildren("./docs/cloud-functions/gse-roar-admin")
},
{
text: "gse-roar-assessment",
link: "/cloud-functions/gse-roar-assessment/",
collapsable: false,
children: getChildren("./docs/cloud-functions/gse-roar-assessment"),
},
],
},
{
text: "Internationalization",
Expand Down
5 changes: 0 additions & 5 deletions docs/cloud-functions/append-to-admin-claims.md

This file was deleted.

5 changes: 0 additions & 5 deletions docs/cloud-functions/associate-assessment-uid.md

This file was deleted.

5 changes: 0 additions & 5 deletions docs/cloud-functions/create-administrator-account.md

This file was deleted.

5 changes: 0 additions & 5 deletions docs/cloud-functions/create-guest-docs-for-google-users.md

This file was deleted.

5 changes: 0 additions & 5 deletions docs/cloud-functions/create-new-family.md

This file was deleted.

5 changes: 0 additions & 5 deletions docs/cloud-functions/create-student-account.md

This file was deleted.

7 changes: 7 additions & 0 deletions docs/cloud-functions/gse-roar-admin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Admin Database

ROAR maintains two separate Firestore databases. The "admin" Firestore contains personally identifiable information (PII), whereas the "assessment" Firestore contains deidentified assessment data. User data in the two databases are linked to by a shared ROAR unique identifier (UID).

In the context of ROAR's Firebase cloud functions, `gse-roar-admin` is a project that provides backend functionality for the administrative side of the ROAR platform. This project is responsible for managing user roles, permissions, and data synchronization between different Firestore collections. The functions in this project handle various administrative tasks, such as creating new user accounts, updating user roles, and synchronizing data across different Firestore collections and databases.

Most of the ROAR Firebase cloud functions are housed in the project and these functions in this project may also access the "assessment" Firestore. When choosing the project in which to write new cloud functions, developers should default to the `gse-roar-admin` project and choose the `gse-roar-assessment` project only when necessary, for example, to use Firestore triggers on data that is stored in the assessment Firestore.
38 changes: 38 additions & 0 deletions docs/cloud-functions/gse-roar-admin/append-to-admin-claims.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# appendToAdminClaims()

#### [appendToAdminClaims](https://github.com/yeatmanlab/roar-firebase-functions/blob/main/gse-roar-admin/functions/src/index.ts#L120)

### Function Name
`appendtoadminclaims`

### Trigger
This Cloud Function is triggered by a direct call (onCall). It expects to be invoked typically through a client-side request.

### Inputs
The function expects a JSON payload with the following structure:
- **requesterUid**: The UID of the user making the request. Extracted from `request.auth.uid`, indicating this function is protected and can only be called by authenticated users.
- **targetUid**: The UID of the user whose admin claims are being updated.
- **districtId**: The ID of the district to append to the user's claims.
- **schoolId**: The ID of the school to append to the user's claims.
- **classId**: The ID of the class to append to the user's claims.
- **familyId**: The ID of the family to append to the user's claims.
- **groupId**: The ID of the group to append to the user's claims.

The input also contains an **action** key, which is statically set to `"append"`. This function is designed to add organizational affiliations to a user's administrative permissions.

### Outputs
The function outputs the result of the `appendOrRemoveAdminOrgs` function, which is a method handling the database update logic.

### Description
The `appendtoadminclaims` function is responsible for appending organization-specific claims to a specified user's administrative profile. This operation facilitates the dynamic management of user access within various organizational structures like schools, classes, and groups. By modifying admin claims, the system can control access to certain resources or administrative functionalities.

### Error Handling
While explicit error handling is not shown in the snippet, it should be implemented within the `appendOrRemoveAdminOrgs` function or be part of a higher-level error management strategy. Errors might include unauthorized access attempts, invalid UID entries, or failures in database operations. These should be logged and, where appropriate, returned to the caller in a format that aids in debugging but does not expose sensitive system details.

### Security Considerations
- **Authentication**: The function checks that the request is made by an authenticated user (`request.auth.uid` must exist).
- **Authorization**: It should be verified that the requester has the appropriate rights to modify admin claims, especially if targeting another user’s claims. This might involve additional checks against `userClaims` to confirm administrative privileges.
- **Data Validation**: The function should validate the input data to ensure that all IDs are in a proper format and refer to existing entities in the system. This prevents injection of invalid data into the system.

### Deployment
This function is deployed automatically using GitHub actions, whenever changes are merged into the `main` branch.
47 changes: 47 additions & 0 deletions docs/cloud-functions/gse-roar-admin/associate-assessment-uid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# associateassessmentuid()

#### [associateassessmentuid](https://github.com/yeatmanlab/roar-firebase-functions/blob/e784650492722d24069aa9b0704d1873ea5dafee/gse-roar-admin/functions/src/index.ts#L187)

### Function Name
`associateassessmentuid`

### Trigger
This Cloud Function is triggered by a direct call (onCall). It expects to be invoked typically through a client-side request within your application.

### Inputs
The function expects a JSON payload containing the following keys:
- **adminUid**: A string that represents the unique identifier of an administrator. This UID is intended to specify which administrator is performing the operation or whose data is being accessed or modified.
- **assessmentUid**: A string that represents the unique identifier of an assessment. This UID is used to associate a specific assessment with an administrator.

Example JSON input:
```json
{
"adminUid": "admin123",
"assessmentUid": "assessment456"
}
```

### Outputs
The function returns the result of the `associateAssessmentUid` operation. This output can be:
- A success message or object indicating that the association was successfully created or updated.
- An error message or object indicating that the operation failed, which may include reasons for the failure (e.g., invalid UIDs, permission issues, database errors).

### Description
The `associateassessmentuid` function is designed to create or update the association between a user's authentication UID in the "admin" and "assessment" Firebase projects. This is part of managing access to ROAR two separate Firebase projects: `gse-roar-admin` and `gse-roar-assessment`. The function takes the UIDs for both admin and assessment projects and updates relevant records in the database.

### Error Handling
This function should include error handling to manage and log various failure scenarios, such as:
- Non-existent `adminUid` or `assessmentUid`
- Database connection issues
- Permission errors if the requestor does not have the right to associate these UIDs
- Any unexpected exceptions

Errors should be logged appropriately and, where feasible, detailed error information should be returned to the caller to facilitate troubleshooting without exposing sensitive system details.

### Security Considerations
- **Authentication**: The function checks that the request is made by an authenticated user.
- **Authorization**: The function should verify that the requester has the appropriate administrative rights to associate an administrator UID with an assessment UID.
- **Data Validation**: Ensure that both `adminUid` and `assessmentUid` are valid and formatted correctly before attempting any operations with them.

### Deployment
This function is deployed automatically using GitHub actions, whenever changes are merged into the `main` branch.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# createAdministratorAccount()

#### [createAdministratorAccount](https://github.com/yeatmanlab/roar-firebase-functions/blob/e784650492722d24069aa9b0704d1873ea5dafee/gse-roar-admin/functions/src/index.ts#L193)

### Function Name
`createAdministratorAccount`

### Trigger
This Cloud Function is triggered by an `onCall` event, meaning it is directly invoked by client applications.

### Inputs
The function expects a JSON payload with the following parameters:
- **email** (string): The email address for the new administrator account.
- **name** (string): The full name of the new administrator.
- **orgs** (array of strings): A list of organization IDs that the administrator is a member of.
- **adminOrgs** (array of strings): A list of organization IDs that the administrator will have administrator privileges to.
- **isTestData** (boolean, optional): A flag to indicate whether this account is being created for testing purposes. Defaults to `false` if not specified.
- **requesterAdminUid** (string): The UID of the administrator making the request, derived from `request.auth.uid`.

Example JSON input:
```json
{
"email": "new.admin@example.com",
"name": "John Doe",
"orgs": ["org1", "org2"],
"adminOrgs": ["adminOrg1"],
"isTestData": false
}
```

### Outputs
The function returns the result from the `createAdminUser` function, which could be:
- A success message or data object indicating that the account has been successfully created.
- An error message or object indicating that the operation failed due to reasons such as invalid input data, database errors, or permission issues.

### Description
The `createAdministratorAccount` function facilitates the creation of new administrator accounts within the system. It is designed to handle the input of essential user details and organizational affiliations, ensuring that new administrators are properly set up with the correct access rights. This function is particularly useful in setups where administrative privileges need to be dynamically managed based on organizational structures.

### Error Handling
Effective error handling should be implemented to manage and log various failure scenarios, including:
- Invalid email format or missing information.
- Database failures, such as connection issues or write failures.
- Permission errors if the requestor does not have adequate rights to create new administrator accounts.
- Handling of any unexpected exceptions.

Errors should be logged with sufficient detail to aid in troubleshooting while avoiding the exposure of sensitive information.

### Security Considerations
- **Authentication**: Ensure that the request is made by an authenticated and authorized user, typically verified through Firebase Authentication.
- **Authorization**: The function should validate that the requester has administrative privileges sufficient to create new administrator accounts, especially in regard to the specified organizational affiliations (`adminOrgs`).
- **Data Validation**: All inputs should be validated for correctness and integrity before processing, including checks for valid email formats and non-null essential fields.

### Deployment
This function is deployed automatically using GitHub actions, whenever changes are merged into the `main` branch.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# createGuestDocsForGoogleUsers()

#### [createGuestDocsForGoogleUsers](https://github.com/yeatmanlab/roar-firebase-functions/blob/e784650492722d24069aa9b0704d1873ea5dafee/gse-roar-admin/functions/src/index.ts#L1058)

### Function Name
`createGuestDocsForGoogleUsers`

### Trigger
This Cloud Function is triggered by the `beforeUserCreated` event. This trigger allows the function to execute just before a new user record is created in Firebase Authentication.

### Inputs
The function does not require any direct input from a caller because it operates based on the event data provided by Firebase when a new user account is being created.

### Event Data
- **user** (object): The user object contains details about the user being created.
- **providers** (array of strings): Extracted from `user.providerData`, this array contains identifiers for each authentication provider associated with the user. For instance, `"google.com"` for users signing in through Google.

### Behavior
The function checks if the new user is signing up using Google as an authentication provider. If the user's provider data includes `"google.com"`, it proceeds to execute a helper function named `createGuestDocs`:

- **createGuestDocs**: This helper function is tasked with creating necessary guest documents for the new user. These documents might include initial settings, permissions, or other introductory data necessary for guest users in the system.

### Outputs
This function does not return any data but completes the creation of guest documents if the conditions are met.

### Error Handling
Effective error handling should be implemented to manage potential issues, such as:
- Problems with accessing `user.providerData`.
- Failures within the `createGuestDocs` function, such as database write errors.
- Handling unexpected data structures or missing data.

Errors should be logged appropriately, providing enough detail for troubleshooting while ensuring that sensitive user data is not exposed.

### Security Considerations
- **Authentication**: The function inherently relies on the authentication process handled by Firebase; thus, it operates under the assumption that the user data is valid and authenticated.
- **Validation**: Check the consistency and validity of the `providerData` to ensure the function operates only for users authenticated through Google.
- **Data Handling**: Secure handling and logging of user data to prevent any leaks or unauthorized access.

### Deployment
This function is deployed automatically using GitHub actions, whenever changes are merged into the `main` branch.

### Maintenance and Monitoring
- **Monitoring**: Set up monitoring on this function to track its execution and any errors that occur. Firebase provides integrated monitoring tools that can be utilized.
- **Updates**: As authentication flows or provider information changes (e.g., changes in provider IDs or authentication methods), this function may require updates to ensure compatibility.
64 changes: 64 additions & 0 deletions docs/cloud-functions/gse-roar-admin/create-levante-group.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# createLevanteGroup()

#### [createLevanteGroup](https://github.com/yeatmanlab/roar-firebase-functions/blob/e784650492722d24069aa9b0704d1873ea5dafee/gse-roar-admin/functions/src/index.ts#L1153), [createGroup](https://github.com/yeatmanlab/roar-firebase-functions/blob/e784650492722d24069aa9b0704d1873ea5dafee/gse-roar-admin/functions/src/LEVANTE/create-group.ts#L8)

### Function Name
`createLevanteGroup`

#### 1. **createLevanteGroup**
This callable Cloud Function acts as an interface for client applications to request the creation of new groups. It verifies user authentication, extracts the necessary data from the request, and delegates the group creation task to the `createGroup` function.

##### Trigger
- **Type**: Callable function
- **Authentication**: Requires users to be authenticated; accesses the user's UID through `request.auth.uid`.

##### Parameters
- **request**: The client request containing the data necessary for group creation:
- `groupData`: Data for the new group (e.g., name, description).

##### Operation
- Extracts user ID and group data from the incoming request.
- Calls the `createGroup` function with the extracted information.

#### 2. **createGroup**
A backend utility function that performs the actual creation of the group document in Firestore and manages related security operations such as updating custom claims and Firestore documents to reflect new group memberships.

##### Parameters
- **requestingUid**: The UID of the user requesting the creation of the group.
- **groupData**: The data for the new group.

##### Operation
- Verifies that the user has administrative privileges.
- Creates a new document in the `groups` collection with the provided `groupData`.
- Updates Firebase Authentication custom claims and the Firestore `userClaims` document to reflect the new group membership.

### Detailed Workflow

1. **User Authentication and Authorization**:
- Verifies that the user making the request has appropriate administrative privileges (`super_admin` or `admin`).
- Retrieves and checks existing custom claims to confirm the user's rights to create a group.

2. **Group Document Creation**:
- Initializes a new document in the `groups` collection.
- Sets the group data into this new document, handling errors that might occur during this process.

3. **Custom Claims and Firestore Document Updates**:
- Retrieves the user's current authentication claims.
- Adds the new group's ID to the user's list of administered groups in both their Firebase Authentication custom claims and their Firestore `userClaims` document.
- Ensures that these updates are atomically committed to maintain data consistency.

### Error Handling and Security Considerations

- **Error Handling**:
- Catches and logs errors at each critical operation, such as retrieving user claims, creating group documents, and updating claims.
- Provides detailed error messages to help diagnose issues, particularly focusing on permission errors and database operation failures.

- **Security**:
- Ensures all operations are performed under strict authentication and authorization checks to prevent unauthorized access or modifications.
- Uses secure methods to update Firestore and Firebase Authentication, protecting against potential data breaches or unauthorized data alterations.

### Deployment and Maintenance

- **Deployment**: These functions should be deployed using the Firebase CLI or through the Firebase Console, ensuring they are configured with the necessary permissions and resources to handle expected traffic and data sizes.

- **Maintenance**: Regularly monitor these functions for performance issues and errors. Update the security policies and logic as necessary, especially in response to changes in organizational roles or user privileges.
Loading

0 comments on commit 1fc3827

Please sign in to comment.