|
| 1 | +/** |
| 2 | + * Copyright (c) 2022 Gitpod GmbH. All rights reserved. |
| 3 | + * Licensed under the GNU Affero General Public License (AGPL). |
| 4 | + * See License-AGPL.txt in the project root for license information. |
| 5 | + */ |
| 6 | + |
| 7 | +import { User } from "@gitpod/gitpod-protocol"; |
| 8 | +import { log } from "@gitpod/gitpod-protocol/lib/util/logging"; |
| 9 | +import { inject, injectable, postConstruct } from "inversify"; |
| 10 | +import { Config } from "../config"; |
| 11 | +import { Twilio } from "twilio"; |
| 12 | +import { ServiceContext } from "twilio/lib/rest/verify/v2/service"; |
| 13 | +import { WorkspaceDB } from "@gitpod/gitpod-db/lib"; |
| 14 | + |
| 15 | +@injectable() |
| 16 | +export class PhoneVerificationService { |
| 17 | + @inject(Config) protected config: Config; |
| 18 | + @inject(WorkspaceDB) protected workspaceDB: WorkspaceDB; |
| 19 | + |
| 20 | + protected verifyService: ServiceContext; |
| 21 | + |
| 22 | + @postConstruct() |
| 23 | + protected initialize(): void { |
| 24 | + if (this.config.phoneVerification) { |
| 25 | + const client = new Twilio( |
| 26 | + this.config.phoneVerification.accountSID, |
| 27 | + this.config.phoneVerification.authToken, |
| 28 | + ); |
| 29 | + this.verifyService = client.verify.v2.services(this.config.phoneVerification.serviceName); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public async needsVerification(user: User): Promise<boolean> { |
| 34 | + if (!this.config.phoneVerification) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + if (!!user.additionalData?.profile?.verifiedPhoneNumber) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + public async sendVerificationToken(phoneNumber: string): Promise<void> { |
| 44 | + if (!this.verifyService) { |
| 45 | + throw new Error("No verification service configured."); |
| 46 | + } |
| 47 | + const verification = await this.verifyService.verifications.create({ to: phoneNumber, channel: "sms" }); |
| 48 | + log.info("Verification code sent", { phoneNumber, status: verification.status }); |
| 49 | + } |
| 50 | + |
| 51 | + public async verifyVerificationToken(phoneNumber: string, oneTimePassword: string): Promise<boolean> { |
| 52 | + if (!this.verifyService) { |
| 53 | + throw new Error("No verification service configured."); |
| 54 | + } |
| 55 | + const verification_check = await this.verifyService.verificationChecks.create({ |
| 56 | + to: phoneNumber, |
| 57 | + code: oneTimePassword, |
| 58 | + }); |
| 59 | + return verification_check.status === "approved"; |
| 60 | + } |
| 61 | +} |
0 commit comments