-
Notifications
You must be signed in to change notification settings - Fork 10
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
esaminu
wants to merge
37
commits into
main
Choose a base branch
from
add-otp-cloud-functions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 ebdba09
feat: update push workflow trigger
esaminu db8334c
fix: cloud function workflow
esaminu f39ecee
test: log dir structure to debug workflow
esaminu 7ec4ca2
chore: change source
esaminu c3a47e1
feat: add dep and config
esaminu 3095df0
chore: set config
esaminu 57d7ac8
chore: change to install
esaminu 916a1d4
chore: post build
esaminu f7702b1
chore: logs
esaminu 73f640c
chore: remove logs
esaminu 88ca1b1
feat: complete 2fa implementation
esaminu 721e40b
chore: update cloud function
esaminu 422ba57
fix: e2e tests
esaminu 654b842
fix: lint
esaminu 46831a9
fix: tests
esaminu d7d6347
fix: unique otps
esaminu 27fc269
fix: tests
esaminu bcbdb34
feat: email copy
esaminu 2867df7
fix: email content
esaminu 04a7006
fix: email copy + regex
esaminu 3c64273
fix: set record after emailing and create acc on specific error
esaminu ef0b15d
fix: complete_authentication before redirect
esaminu 8e02d95
fix: cloud functions workflow
esaminu 62dd3b6
fix: remove enable cloud
esaminu 0f0162c
feat: remove service account flag
esaminu 987e4de
feat: add service account
esaminu 0d714b1
Update deploy-cloud-functions-testnet.yml
rtsainear 762fa51
Update deploy-cloud-functions-testnet.yml
rtsainear 6275a5a
Update deploy-cloud-functions-testnet.yml
rtsainear dc42cca
Update deploy-cloud-functions-testnet.yml
rtsainear 1317078
Update deploy-cloud-functions-testnet.yml
rtsainear de89487
Update deploy-cloud-functions-testnet.yml
rtsainear 8c212bc
Update deploy-cloud-functions-testnet.yml
rtsainear 6754bad
Update deploy-cloud-functions-testnet.yml
rtsainear 5507ba4
Update deploy-cloud-functions-testnet.yml
rtsainear 9754163
Update deploy-cloud-functions-testnet.yml
rtsainear File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"projects": { | ||
"default": "pagoda-oboarding-dev" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
] | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'], | ||
}, | ||
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"include": [ | ||
".eslintrc.js" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
{ | ||
"extends": "./tsconfig.json", | ||
"include": ["src/**/*.ts", "src/**/*.js", ".eslintrc.js"] | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.