Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,096 changes: 6 additions & 2,090 deletions appwrite.json

Large diffs are not rendered by default.

53 changes: 25 additions & 28 deletions functions/create-room/src/main.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import AppwriteService from "./appwrite.js";
import LivekitService from "./livekit.js";
import RoomCreationService from "./room-creation-service.js";
import { throwIfMissing } from "./utils.js";

export default async ({ req, res, log, error }) => {
// Validate environment variables
throwIfMissing(process.env, [
"APPWRITE_API_KEY",
"MASTER_DATABASE_ID",
Expand All @@ -13,51 +15,46 @@ export default async ({ req, res, log, error }) => {
"LIVEKIT_SOCKET_URL",
]);

const appwrite = new AppwriteService();
const livekit = new LivekitService();

// Initialize services
const appwriteService = new AppwriteService();
const livekitService = new LivekitService();
const roomCreationService = new RoomCreationService(
appwriteService,
livekitService,
process.env.LIVEKIT_SOCKET_URL
);

// Parse and validate request body
let requestBody;
try {
throwIfMissing(JSON.parse(req.body), ["name", "adminUid", "tags"]);
requestBody = JSON.parse(req.body);
throwIfMissing(requestBody, ["name", "adminUid", "tags"]);
} catch (err) {
error(err.message);
return res.json({ msg: err.message }, 400);
}

// Handle room creation
try {
log(req);
const { name, description, adminUid, tags } = JSON.parse(req.body);
const { name, description, adminUid, tags } = requestBody;

// create a new room on appwrite
const newRoomdata = {
// Delegate business logic to the service
const result = await roomCreationService.createRoom({
name,
description,
adminUid,
tags,
totalParticipants: 1,
};
const appwriteRoomId = await appwrite.createRoom(newRoomdata);
log(appwriteRoomId);

// create a new livekit room
const livekitRoomOptions = {
name: appwriteRoomId, // using appwrite room doc id as livekit room name
emptyTimeout: 300, // timeout in seconds
};
const livekitRoom = await livekit.createRoom(livekitRoomOptions);
log(livekitRoom);
});

// Creating a token for the admin
const accessToken = livekit.generateToken(
appwriteRoomId,
adminUid,
true
);
log(`Room created: ${result.appwriteRoomId}`);

// Format and return response
return res.json({
msg: "Room created Successfully",
livekit_room: livekitRoom,
livekit_socket_url: `${process.env.LIVEKIT_SOCKET_URL}`,
access_token: accessToken,
livekit_room: result.livekitRoom,
livekit_socket_url: result.livekitSocketUrl,
access_token: result.accessToken,
});
} catch (e) {
error(String(e));
Expand Down
62 changes: 62 additions & 0 deletions functions/create-room/src/room-creation-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import AppwriteService from "./appwrite.js";
import LivekitService from "./livekit.js";

/**
* Service responsible for orchestrating room creation business logic.
* Handles the creation of room metadata in Appwrite and LiveKit room setup.
*/
class RoomCreationService {
constructor(appwriteService, livekitService, livekitSocketUrl) {
this.appwrite = appwriteService;
this.livekit = livekitService;
this.livekitSocketUrl = livekitSocketUrl;
}

/**
* Creates a new room with the provided details.
*
* @param {Object} roomData - Room creation parameters
* @param {string} roomData.name - Room name
* @param {string} [roomData.description] - Room description (optional)
* @param {string} roomData.adminUid - Admin user ID
* @param {string[]} roomData.tags - Room tags
* @returns {Promise<Object>} Room creation result with room details and access token
* @throws {Error} If room creation fails
*/
async createRoom({ name, description, adminUid, tags }) {
// Create room metadata in Appwrite
const roomMetadata = {
name,
description,
adminUid,
tags,
totalParticipants: 1,
};

const appwriteRoomId = await this.appwrite.createRoom(roomMetadata);

// Create LiveKit room using Appwrite room ID as the room name
const livekitRoomOptions = {
name: appwriteRoomId,
emptyTimeout: 300, // timeout in seconds
};

const livekitRoom = await this.livekit.createRoom(livekitRoomOptions);

// Generate access token for the admin
const accessToken = this.livekit.generateToken(
appwriteRoomId,
adminUid,
true // isRoomAdmin
);

return {
livekitRoom,
livekitSocketUrl: this.livekitSocketUrl,
accessToken,
appwriteRoomId,
};
}
}

export default RoomCreationService;
133 changes: 133 additions & 0 deletions functions/send-otp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# Directory used by Appwrite CLI for local development
.appwrite
6 changes: 6 additions & 0 deletions functions/send-otp/.prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true
}
102 changes: 20 additions & 82 deletions functions/send-otp/README.md
Original file line number Diff line number Diff line change
@@ -1,86 +1,24 @@
# Send OTP function
# Send OTP Function

Function to send OTPs.
This function handles the generation and delivery of a 6-digit OTP via email. It includes a **60-second backend rate-limiting** mechanism to prevent abuse.

## 🧰 Usage

### POST /

**Parameters**

| Name | Description | Location | Type | Sample Value |
| -------------- | ------------------------- | -------- | ------ | ------------------ |
| otpId | Document ID of the otp | Body | String | `jcbd...kdsn` |
| recipientEmail | Email ID of the recipient | Body | String | `[email protected]` |

**Response**

Sample `200` Response:

```json
{
"msg": "mail sent"
}
```
## 🚀 Features
- **Secure OTP Generation**: Creates a random 6-digit code for authentication.
- **Rate Limiting**: Checks the `last_otp_sent` timestamp in the database; returns a **429 Too Many Requests** if a request is made within 60 seconds of the last one.
- **Email Integration**: Delivers the OTP using SMTP with secure credentials.

## ⚙️ Configuration

| Setting | Value |
| ----------------- | ------------------------------ |
| Runtime | Node (18.0) |
| Entrypoint | `src/main.js` |
| Build Commands | `npm install && npm run start` |
| Permissions | `any` |
| Timeout (Seconds) | 15 |

## 🔒 Environment Variables

### APPWRITE_API_KEY

API Key to use Appwrite Sever SDK.

| Question | Answer |
| ------------- | ------------------------------------------------------------------------ |
| Required | Yes |
| Sample Value | `62...97` |
| Documentation | [Appwrite API Keys](https://appwrite.io/docs/advanced/platform/api-keys) |

### VERIFICATION_DATABASE_ID

Database ID of verification database in appwrite.

| Question | Answer |
| ------------- | --------------------------------------------------------------------------------------- |
| Required | Yes |
| Sample Value | `Zjc...5PH` |
| Documentation | [Resonate](https://github.com/AOSSIE-Org/Resonate/blob/master/lib/utils/constants.dart) |

### OTP_COLLECTION_ID

Collection ID of otp collection.

| Question | Answer |
| ------------- | --------------------------------------------------------------------------------------- |
| Required | Yes |
| Sample Value | `NXOi3...IBHDa` |
| Documentation | [Resonate](https://github.com/AOSSIE-Org/Resonate/blob/master/lib/utils/constants.dart) |

### SENDER_MAIL

Email of the sender.

| Question | Answer |
| ------------- | ------------------------------------------------ |
| Required | Yes |
| Sample Value | `[email protected]` |
| Documentation | [Discord](https://discord.com/invite/6mFZ2S846n) |

### SENDER_PASSWORD

Password of the sender's account.

| Question | Answer |
| ------------- | ------------------------------------------------ |
| Required | Yes |
| Sample Value | `HC1Itf...........dAAKF5o` |
| Documentation | [Discord](https://discord.com/invite/6mFZ2S846n) |
- **Runtime**: Node.js 18.0 (Updated to address security patches)
- **Entrypoint**: `src/main.js`

## 🔐 Environment Variables
The following variables must be configured in your Appwrite Function settings:

| Variable | Description |
|----------|-------------|
| `APPWRITE_API_KEY` | API key with database and document scopes. |
| `APPWRITE_FUNCTION_PROJECT_ID` | Your active project ID. |
| `VERIFICATION_DATABASE_ID` | ID for the database storing OTP metadata. |
| `OTP_COLLECTION_ID` | Collection ID for storing user-specific OTP records. |
| `SENDER_MAIL` | The SMTP email address used to send the OTP. |
| `SENDER_PASSWORD` | The SMTP password or App Password for the sender. |
Loading