Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add otp functions #265

Open
wants to merge 37 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
c29401f
feat: add cloud functions
esaminu Jul 17, 2024
ebdba09
feat: update push workflow trigger
esaminu Jul 17, 2024
db8334c
fix: cloud function workflow
esaminu Jul 17, 2024
f39ecee
test: log dir structure to debug workflow
esaminu Jul 17, 2024
7ec4ca2
chore: change source
esaminu Jul 17, 2024
c3a47e1
feat: add dep and config
esaminu Jul 18, 2024
3095df0
chore: set config
esaminu Jul 18, 2024
57d7ac8
chore: change to install
esaminu Jul 18, 2024
916a1d4
chore: post build
esaminu Jul 18, 2024
f7702b1
chore: logs
esaminu Jul 18, 2024
73f640c
chore: remove logs
esaminu Jul 18, 2024
88ca1b1
feat: complete 2fa implementation
esaminu Jul 29, 2024
721e40b
chore: update cloud function
esaminu Jul 29, 2024
422ba57
fix: e2e tests
esaminu Jul 30, 2024
654b842
fix: lint
esaminu Jul 30, 2024
46831a9
fix: tests
esaminu Jul 30, 2024
d7d6347
fix: unique otps
esaminu Jul 31, 2024
27fc269
fix: tests
esaminu Aug 1, 2024
bcbdb34
feat: email copy
esaminu Aug 1, 2024
2867df7
fix: email content
esaminu Aug 1, 2024
04a7006
fix: email copy + regex
esaminu Aug 1, 2024
3c64273
fix: set record after emailing and create acc on specific error
esaminu Aug 5, 2024
ef0b15d
fix: complete_authentication before redirect
esaminu Aug 6, 2024
8e02d95
fix: cloud functions workflow
esaminu Aug 6, 2024
62dd3b6
fix: remove enable cloud
esaminu Aug 6, 2024
0f0162c
feat: remove service account flag
esaminu Aug 6, 2024
987e4de
feat: add service account
esaminu Aug 6, 2024
0d714b1
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 6, 2024
762fa51
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 6, 2024
6275a5a
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 6, 2024
dc42cca
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 6, 2024
1317078
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 7, 2024
de89487
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 7, 2024
8c212bc
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 7, 2024
6754bad
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 7, 2024
5507ba4
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 7, 2024
9754163
Update deploy-cloud-functions-testnet.yml
rtsainear Aug 7, 2024
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
5 changes: 5 additions & 0 deletions .firebaserc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add a cron job to clean up old OTPs?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Old otps that are left in our db will happen when someone requests codes to multiple emails and does not verify any of them. We create one record per email (we override the record for multiple requests to the same email) and we delete the record once the user is verified and gets a token. We can add a daily cron job to handle expired otps older than a month or so IMO but they serve as a log for people trying to login and unable to get access, we can inspect the db and verify that we sent them a code - we did something similar for wallet

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking about the expired ones. But it makes sense to leave it there for logging purpose.

"projects": {
"default": "pagoda-oboarding-dev"
}
}
68 changes: 68 additions & 0 deletions .github/workflows/deploy-cloud-functions-testnet.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
name: Deploy Cloud Functions
on:
push:
branches: [ main, add-otp-cloud-functions ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18'

- id: 'auth'
uses: 'google-github-actions/auth@v1'
with:
credentials_json: '${{ secrets.CLOUD_FUNCTIONS_DEPLOYER_TESTNET_SERVICE_ACCOUNT }}'

- name: 'Set up Cloud SDK'
uses: 'google-github-actions/setup-gcloud@v1'
with:
version: 'latest'

- name: 'Update gcloud SDK to the latest version'
run: |
gcloud components update

- name: 'Install dependencies and build'
run: |
cd packages/functions
npm install
npm run build
echo "Directory structure after build:"
find . -type f

- name: 'Deploy Cloud Functions'
run: |
cd packages/functions
echo "Current directory contents:"
ls -R
gcloud config set project pagoda-oboarding-dev
gcloud functions deploy verifyOTP \
--no-gen2 \
--runtime nodejs18 \
--trigger-http \
--allow-unauthenticated \
--service-account=firebase-adminsdk-bygsj@pagoda-oboarding-dev.iam.gserviceaccount.com \
--entry-point=verifyOTP \
--source=lib \
--set-env-vars GMAIL_SENDER="${{ secrets.GMAIL_OTP_SENDER }}",GMAIL_PASSWORD="${{ secrets.GMAIL_OTP_SENDER_PASSWORD }}" \
--verbosity=debug \
--project pagoda-oboarding-dev \
--build-service-account=projects/pagoda-oboarding-dev/serviceAccounts/firebase-adminsdk-bygsj@pagoda-oboarding-dev.iam.gserviceaccount.com

gcloud functions deploy sendOTP \
--no-gen2 \
--runtime nodejs18 \
--trigger-http \
--allow-unauthenticated \
--service-account=firebase-adminsdk-bygsj@pagoda-oboarding-dev.iam.gserviceaccount.com \
--entry-point=sendOTP \
--source=lib \
--set-env-vars GMAIL_SENDER="${{ secrets.GMAIL_OTP_SENDER }}",GMAIL_PASSWORD="${{ secrets.GMAIL_OTP_SENDER_PASSWORD }}" \
--verbosity=debug \
--project pagoda-oboarding-dev \
--build-service-account=projects/pagoda-oboarding-dev/serviceAccounts/firebase-adminsdk-bygsj@pagoda-oboarding-dev.iam.gserviceaccount.com
19 changes: 19 additions & 0 deletions firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"functions": [
{
"source": "packages/functions",
"codebase": "default",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log",
"*.local"
],
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
]
}
]
}
10 changes: 10 additions & 0 deletions packages/functions/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Compiled JavaScript files
lib/**/*.js
lib/**/*.js.map

# TypeScript v1 declaration files
typings/

# Node.js dependency directory
node_modules/
*.local
126 changes: 126 additions & 0 deletions packages/functions/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
const eslint = require('@eslint/js');
const tseslintPlugin = require('@typescript-eslint/eslint-plugin');
const tseslintParser = require('@typescript-eslint/parser');
const importPlugin = require('eslint-plugin-import');
const airbnbBase = require('eslint-config-airbnb-base');

module.exports = [
eslint.configs.recommended,
{
files: ['**/*.ts', '**/*.tsx'],
languageOptions: {
parser: tseslintParser,
parserOptions: {
project: './tsconfig.json',
},
globals: {
process: 'readonly',
console: 'readonly',
Buffer: 'readonly',
},
},
plugins: {
'@typescript-eslint': tseslintPlugin,
import: importPlugin,
},
rules: {
...airbnbBase.rules,
...tseslintPlugin.configs.recommended.rules,
// Your existing rules here...
'linebreak-style': 0,
'import/no-extraneous-dependencies': 'off',
'import/prefer-default-export': 'off',
'prefer-destructuring': [
'error',
{
VariableDeclarator: {
array: false,
object: true,
},
AssignmentExpression: {
array: false,
object: false,
},
},
{
enforceForRenamedProperties: false,
},
],
'max-classes-per-file': 'off',
indent: [
'error',
2,
{
SwitchCase: 1,
VariableDeclarator: { var: 2, let: 2, const: 3 },
ObjectExpression: 'first',
},
],
semi: ['error', 'always'],
'comma-dangle': ['error', 'only-multiline'],
'max-len': [
'error',
120,
{
ignoreComments: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
},
],
'no-multi-spaces': [
'error',
{
exceptions: {
ExportNamedDeclaration: true,
VariableDeclarator: true,
AssignmentExpression: true,
AssignmentPattern: true,
},
},
],
'global-require': 'warn',
'one-var': ['error', 'never'],
strict: 'off',
camelcase: 'off',
'no-console': 'off',
'func-names': 'off',
'no-param-reassign': 'off',
'arrow-body-style': [
'error',
'as-needed',
{ requireReturnForObjectLiteral: true },
],
'no-underscore-dangle': 'off',
'import/extensions': ['error', { json: 'always' }],
'import/order': [
'error',
{
alphabetize: {
order: 'asc',
caseInsensitive: true,
},
'newlines-between': 'always',
groups: [
'builtin',
['external', 'internal'],
['sibling', 'parent', 'index'],
'object',
],
},
],
'arrow-parens': ['error', 'always'],
'key-spacing': ['warn', { align: 'value', mode: 'minimum' }],
'one-var-declaration-per-line': ['error', 'initializations'],
'no-shadow': 'off',
'@typescript-eslint/no-shadow': 'error',
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
},
},
{
ignores: ['node_modules/**', 'dist/**', 'lib/**', 'eslint.config.js'],
},
];
38 changes: 38 additions & 0 deletions packages/functions/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "functions",
"version": "1.0.0",
"scripts": {
"lint": "eslint .",
"build": "tsc",
"postbuild": "cp package.json lib/ && cd lib && npm install --only=production",
"build:watch": "tsc --watch",
"serve": "yarn run build && firebase emulators:start --only functions",
"shell": "yarn run build && firebase functions:shell",
"start": "yarn run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "18"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^12.1.0",
"firebase-functions": "^5.0.0",
"nodemailer": "^6.9.14",
"crypto": "^1.0.1"
},
"devDependencies": {
"@eslint/js": "^9.7.0",
"@types/nodemailer": "^6.4.15",
"@typescript-eslint/eslint-plugin": "^6.15.0",
"@typescript-eslint/parser": "^6.15.0",
"eslint": "^8.56.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-import": "^2.29.1",
"firebase-functions-test": "^3.1.0",
"typescript": "^4.9.0"
},
"private": true
}
107 changes: 107 additions & 0 deletions packages/functions/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import * as crypto from 'crypto';

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import * as nodemailer from 'nodemailer';

admin.initializeApp();

const SENDER_EMAIL = process.env.GMAIL_SENDER;
const GMAIL_PASSWORD = process.env.GMAIL_PASSWORD;

if (!SENDER_EMAIL || !GMAIL_PASSWORD) {
throw new Error('Sender email and password must be set as environment variables.');
}

const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: SENDER_EMAIL,
pass: GMAIL_PASSWORD,
},
});

export const sendOTP = functions.https.onCall(
async (data: { email: string }, _context) => {
const { email } = data;

const otp = crypto.randomInt(100000, 999999).toString();
const now = new Date();
const formattedDate = now.toISOString().replace(/T/, ' ').replace(/\..+/, ' Z');
const emailContent = `Hello,<br><br>We received a request to sign in to NEAR Onboarding using this email address, at ${formattedDate}. If you want to sign in with your ${email} account, use this code:<br><br>${otp}<br><br>If you did not request this link, you can safely ignore this email.<br><br>Thanks,<br><br>Your NEAR Onboarding team`;

try {
await transporter.sendMail({
from: SENDER_EMAIL,
to: email,
subject: `Sign in to NEAR Onboarding requested at ${formattedDate}`,
html: emailContent
});

const otpDoc = admin.firestore().collection('otps').doc(email);
await otpDoc.set({
otp,
createdAt: admin.firestore.FieldValue.serverTimestamp(),
expiresAt: admin.firestore.Timestamp.fromDate(
new Date(Date.now() + 10 * 60 * 1000)
), // 10 minutes expiration
});

return { success: true, message: 'OTP sent successfully' };
} catch (error) {
console.error('Error sending OTP:', error);
throw new functions.https.HttpsError('internal', 'Failed to send OTP');
}
}
);

export const verifyOTP = functions
.runWith({ timeoutSeconds: 60 })
.https.onCall(async (data: { email: string; otp: string }, _context) => {
const { email, otp } = data;

const otpDoc = await admin.firestore().collection('otps').doc(email).get();

if (!otpDoc.exists) {
throw new functions.https.HttpsError(
'not-found',
'No OTP request found for this email'
);
}

const otpData = otpDoc.data();

if (!otpData || otpData.otp !== otp) {
throw new functions.https.HttpsError('invalid-argument', 'Invalid OTP');
}

if (otpData.expiresAt.toDate() < new Date()) {
throw new functions.https.HttpsError(
'deadline-exceeded',
'OTP has expired'
);
}

let uid: string;
try {
const userRecord = await admin.auth().getUserByEmail(email);
uid = userRecord.uid;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
if (error.code === 'auth/user-not-found') {
const newUser = await admin.auth().createUser({ email });
uid = newUser.uid;
} else {
console.error('Error getting user:', error);
throw new functions.https.HttpsError('internal', 'Error verifying user');
}
}

const customToken = await admin.auth().createCustomToken(uid);

await otpDoc.ref.delete();

return { success: true, customToken };
});
5 changes: 5 additions & 0 deletions packages/functions/tsconfig.dev.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"include": [
".eslintrc.js"
]
}
4 changes: 4 additions & 0 deletions packages/functions/tsconfig.eslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts", "src/**/*.js", ".eslintrc.js"]
}
Loading
Loading