diff --git a/.gitattributes b/.gitattributes index 6673000..d501c5f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ # Shell scripts must use LF — CRLF breaks Alpine entrypoints ("No such file or directory"). *.sh text eol=lf +# Windows OpenSSH askpass is a cmd script. LF-only cmd files fail on the staging PC. +*.cmd text eol=crlf +*.ps1 text eol=crlf diff --git a/.gitignore b/.gitignore index 6cd048a..0785bc4 100644 --- a/.gitignore +++ b/.gitignore @@ -76,6 +76,7 @@ Desktop.ini *.crt .secrets/ secrets/ +infrastructure/scripts/copy-prod-backup-askpass.exe # === Database files === *.sqlite diff --git a/AGENTS.md b/AGENTS.md index 3692b5f..fa9c97a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,6 +96,8 @@ Errors: `AppException` + `ErrorCode` → frontend `getUserFacingError()`. Unexpe **AdminJS:** Manual resource allowlist in `backend/src/admin/resources.ts`. **Whenever `schema.prisma` changes**, update AdminJS resources in the same task (new/renamed/removed models, hide secrets). Models with only composite `@@id` must not be registered (list 500) — including `LabCaseAttachment`. Single-id models such as `StaffWorkingHoursSchedule` / `StaffWorkingHoursBlock` **are** registered. `LabCase.listedAt` is trigger-maintained (list/filter/show only; never write). Rule: `.cursor/rules/adminjs.mdc`. +**Database backups:** Production dumps three times a day on the Linux server and keeps them for 3 days. The Mac copies them once at 17:00. The Windows staging PC copies each dump 30 minutes later and keeps them for 30 days (task **Nudentic copy prod backup**). Runbook: [`infrastructure/BACKUP.md`](infrastructure/BACKUP.md). + ## Git & commits - **Do not commit or push** unless the user explicitly asks. diff --git a/backend/.env.example b/backend/.env.example index 2ed749d..79001be 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -41,7 +41,8 @@ COOKIE_SECURE=false # FACEBOOK_CLIENT_SECRET=your-facebook-app-secret # FACEBOOK_CALLBACK_URL=http://localhost:3000/auth/facebook/callback -# Email (configure for production) +# Email verification. Leave SMTP_HOST empty to print the code in the API log (local dev). +# Production and staging need a real mailbox or new signups cannot receive a code. SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your_email@gmail.com diff --git a/backend/package-lock.json b/backend/package-lock.json index e2d0109..8d64e8e 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -39,6 +39,7 @@ "express-session": "^1.19.0", "helmet": "^8.1.0", "multer": "^2.1.1", + "nodemailer": "^10.0.16", "passport": "^0.7.0", "passport-jwt": "^4.0.1", "passport-local": "^1.0.0", @@ -62,6 +63,7 @@ "@types/jest": "^30.0.0", "@types/multer": "^2.1.0", "@types/node": "^22.10.7", + "@types/nodemailer": "^8.0.2", "@types/pg": "^8.16.0", "@types/styled-components": "^5.1.36", "@types/supertest": "^6.0.2", @@ -6576,6 +6578,16 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/nodemailer": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz", + "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/parse-json": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", @@ -12974,6 +12986,15 @@ "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==", "license": "MIT" }, + "node_modules/nodemailer": { + "version": "10.0.16", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.16.tgz", + "integrity": "sha512-VL9xKErxN+el77o8eBOuYKUPMyEx7F9hfnDCuiUKJRp9v3wnWMOudYgP/SWbwSHy8rUL4cylobuXtki1LpQS7A==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", diff --git a/backend/package.json b/backend/package.json index 329ed25..c9fa7af 100644 --- a/backend/package.json +++ b/backend/package.json @@ -61,6 +61,7 @@ "express-session": "^1.19.0", "helmet": "^8.1.0", "multer": "^2.1.1", + "nodemailer": "^10.0.16", "passport": "^0.7.0", "passport-jwt": "^4.0.1", "passport-local": "^1.0.0", @@ -84,6 +85,7 @@ "@types/jest": "^30.0.0", "@types/multer": "^2.1.0", "@types/node": "^22.10.7", + "@types/nodemailer": "^8.0.2", "@types/pg": "^8.16.0", "@types/styled-components": "^5.1.36", "@types/supertest": "^6.0.2", diff --git a/backend/prisma/migrations/20261008120000_account_email_verification/migration.sql b/backend/prisma/migrations/20261008120000_account_email_verification/migration.sql new file mode 100644 index 0000000..743ba42 --- /dev/null +++ b/backend/prisma/migrations/20261008120000_account_email_verification/migration.sql @@ -0,0 +1,26 @@ +-- AlterTable +ALTER TABLE "users" ADD COLUMN "emailVerifiedAt" TIMESTAMP(3); + +-- Existing accounts stay usable. New rows leave this null until the inbox is confirmed. +UPDATE "users" SET "emailVerifiedAt" = "createdAt" WHERE "emailVerifiedAt" IS NULL; + +-- CreateTable +CREATE TABLE "email_verification_codes" ( + "id" TEXT NOT NULL, + "userId" TEXT, + "email" TEXT NOT NULL, + "codeHash" TEXT NOT NULL, + "purpose" TEXT NOT NULL, + "payload" JSONB, + "expiresAt" TIMESTAMP(3) NOT NULL, + "verifiedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "email_verification_codes_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "email_verification_codes_email_purpose_createdAt_idx" ON "email_verification_codes"("email", "purpose", "createdAt"); + +-- AddForeignKey +ALTER TABLE "email_verification_codes" ADD CONSTRAINT "email_verification_codes_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 3ed1ffe..e9cd2b5 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -16,8 +16,9 @@ model User { googleId String? @unique facebookId String? @unique name String - language String @default("en") - trialUsedAt DateTime? + language String @default("en") + trialUsedAt DateTime? + emailVerifiedAt DateTime? memberships Membership[] ownedOrganizations Organization[] @relation("OrganizationOwner") @@ -30,6 +31,7 @@ model User { labCaseComments LabCaseComment[] labCaseActivities LabCaseActivity[] phoneVerificationCodes PhoneVerificationCode[] + emailVerificationCodes EmailVerificationCode[] userNotifications UserNotification[] actedUserNotifications UserNotification[] @relation("UserNotificationActor") billingSheetTargets BillingSheetTarget[] @@ -43,6 +45,23 @@ model User { @@map("users") } +model EmailVerificationCode { + id String @id @default(uuid()) + userId String? + email String + codeHash String + purpose String + payload Json? + expiresAt DateTime + verifiedAt DateTime? + createdAt DateTime @default(now()) + + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@index([email, purpose, createdAt]) + @@map("email_verification_codes") +} + model PhoneVerificationCode { id String @id @default(uuid()) userId String? diff --git a/backend/src/admin/resources.ts b/backend/src/admin/resources.ts index 617261c..07f38cc 100644 --- a/backend/src/admin/resources.ts +++ b/backend/src/admin/resources.ts @@ -80,6 +80,10 @@ export function buildAdminResources(prisma: PrismaService): AdminResource[] { navigation: { name: 'Identity', icon: 'User' }, properties: hide('codeHash'), }), + resource(prisma, 'EmailVerificationCode', { + navigation: { name: 'Identity', icon: 'User' }, + properties: hide('codeHash', 'payload'), + }), // Orgs & access resource(prisma, 'Organization', { diff --git a/backend/src/common/errors/error-codes.ts b/backend/src/common/errors/error-codes.ts index 552d3f8..7c2c455 100644 --- a/backend/src/common/errors/error-codes.ts +++ b/backend/src/common/errors/error-codes.ts @@ -18,6 +18,8 @@ export const ErrorCode = { AUTH_PASSWORD_RESET_EXPIRED: 'AUTH_PASSWORD_RESET_EXPIRED', AUTH_VERIFICATION_CODE_INVALID: 'AUTH_VERIFICATION_CODE_INVALID', AUTH_VERIFICATION_RATE_LIMIT: 'AUTH_VERIFICATION_RATE_LIMIT', + AUTH_EMAIL_NOT_VERIFIED: 'AUTH_EMAIL_NOT_VERIFIED', + AUTH_EMAIL_SEND_FAILED: 'AUTH_EMAIL_SEND_FAILED', AUTH_SELECT_ORG_FIRST: 'AUTH_SELECT_ORG_FIRST', AUTH_CREATE_ORG_OWNER_ONLY: 'AUTH_CREATE_ORG_OWNER_ONLY', AUTH_PASSWORD_CURRENT_REQUIRED: 'AUTH_PASSWORD_CURRENT_REQUIRED', diff --git a/backend/src/configs/configurations.ts b/backend/src/configs/configurations.ts index cc4c5eb..d1b1d98 100644 --- a/backend/src/configs/configurations.ts +++ b/backend/src/configs/configurations.ts @@ -73,6 +73,12 @@ export interface Config { apiKey: string | null; templateId: number; }; + smtp: { + host: string | null; + port: number; + user: string | null; + password: string | null; + }; voice: VoiceConfig; } @@ -164,6 +170,12 @@ export default (): Config => { apiKey: process.env.SMS_IR_API_KEY?.trim() || null, templateId: getEnvVarAsNumber('SMS_IR_TEMPLATE_ID', 123456), }, + smtp: { + host: process.env.SMTP_HOST?.trim() || null, + port: getEnvVarAsNumber('SMTP_PORT', 587), + user: process.env.SMTP_USER?.trim() || null, + password: process.env.SMTP_PASSWORD?.trim() || null, + }, voice: buildVoiceConfig(getEnvVarWithDefault, getEnvVarAsNumber), }; }; diff --git a/backend/src/modules/auth/auth.controller.ts b/backend/src/modules/auth/auth.controller.ts index c29ec9b..b0b4367 100644 --- a/backend/src/modules/auth/auth.controller.ts +++ b/backend/src/modules/auth/auth.controller.ts @@ -29,14 +29,17 @@ import { ConfigService } from '@nestjs/config'; import { JwtService } from '@nestjs/jwt'; import { AppException, ErrorCode } from '../../common/errors'; import { LoginDto } from './dto/login.dto'; -import { RegisterDto } from './dto/register.dto'; +import { RegisterSendCodeDto } from './dto/register-send-code.dto'; +import { RegisterVerifyDto } from './dto/register-verify.dto'; import { CreateOrganizationDto } from './dto/create-organization.dto'; import { JwtAuthGuard } from './guards/jwt-auth.guard'; import { LocalAuthGuard } from './guards/local-auth.guard'; import { UpdateLanguageDto } from './dto/update-language.dto'; import { ForgotPasswordSendCodeDto, + ForgotPasswordSendEmailCodeDto, ForgotPasswordVerifyDto, + ForgotPasswordVerifyEmailDto, } from './dto/forgot-password.dto'; import { ChangePasswordDto } from './dto/change-password.dto'; import { UpdateParticipationDto } from './dto/update-participation.dto'; @@ -94,20 +97,25 @@ export class AuthController { // ========================= // REGISTER // ========================= - @Post('register') - @ApiOperation({ summary: 'Register a new user' }) - @ApiBody({ type: RegisterDto }) + @Post('register/send-code') + @HttpCode(HttpStatus.OK) + @ApiOperation({ summary: 'Email a verification code for a new account' }) + @ApiBody({ type: RegisterSendCodeDto }) + async sendRegisterCode(@Body() registerDto: RegisterSendCodeDto) { + return this.authService.sendRegisterCode(registerDto); + } + + @Post('register/verify') + @ApiOperation({ summary: 'Confirm the emailed code and create the account' }) + @ApiBody({ type: RegisterVerifyDto }) @ApiResponse({ status: 201, description: 'User registered successfully' }) @ApiBadRequestResponse({ description: 'Invalid input data' }) - async register( - @Body() registerDto: RegisterDto, - @Res({ passthrough: true }) res: Response + async verifyRegisterCode( + @Body() dto: RegisterVerifyDto, + @Res({ passthrough: true }) res: Response, ) { - console.log('Register endpoint hit'); + const result = await this.authService.verifyRegisterCode(dto); - const result = await this.authService.register(registerDto); - - // ✅ SET COOKIES HERE this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken); return { @@ -280,11 +288,40 @@ export class AuthController { result.data.accessToken, result.data.refreshToken, ); + this.markPasswordResetVerified(res); - res.cookie('passwordResetVerified', '1', { - ...this.baseCookieOptions(), - maxAge: AuthController.PASSWORD_RESET_MAX_AGE_MS, - }); + return { + success: true, + data: { + user: result.data.user, + organizations: result.data.organizations, + redirectTo: '/settings/account', + }, + }; + } + + @Post('forgot-password/send-email-code') + @HttpCode(HttpStatus.OK) + @ApiOperation({ summary: 'Send forgot-password email verification code' }) + async sendForgotPasswordEmailCode(@Body() dto: ForgotPasswordSendEmailCodeDto) { + return this.authService.sendForgotPasswordEmailCode(dto); + } + + @Post('forgot-password/verify-email') + @HttpCode(HttpStatus.OK) + @ApiOperation({ summary: 'Verify email code and sign in for password reset' }) + async verifyForgotPasswordEmailCode( + @Body() dto: ForgotPasswordVerifyEmailDto, + @Res({ passthrough: true }) res: Response, + ) { + const result = await this.authService.verifyForgotPasswordEmailCode(dto); + + this.setAuthCookies( + res, + result.data.accessToken, + result.data.refreshToken, + ); + this.markPasswordResetVerified(res); return { success: true, @@ -406,6 +443,13 @@ export class AuthController { }; } + private markPasswordResetVerified(res: Response) { + res.cookie('passwordResetVerified', '1', { + ...this.baseCookieOptions(), + maxAge: AuthController.PASSWORD_RESET_MAX_AGE_MS, + }); + } + private setAuthCookies( res: Response, accessToken: string, diff --git a/backend/src/modules/auth/auth.module.ts b/backend/src/modules/auth/auth.module.ts index de68deb..38738cb 100644 --- a/backend/src/modules/auth/auth.module.ts +++ b/backend/src/modules/auth/auth.module.ts @@ -10,12 +10,14 @@ import { LocalStrategy } from './strategies/local.strategy'; import { JwtStrategy } from './strategies/jwt.strategy'; import { SmsModule } from '../sms/sms.module'; import { StaffModule } from '../staff/staff.module'; +import { EmailVerificationModule } from '../email-verification/email-verification.module'; @Module({ imports: [ PassportModule, SmsModule, StaffModule, + EmailVerificationModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ diff --git a/backend/src/modules/auth/auth.service.ts b/backend/src/modules/auth/auth.service.ts index bdc836e..f3aec86 100644 --- a/backend/src/modules/auth/auth.service.ts +++ b/backend/src/modules/auth/auth.service.ts @@ -9,9 +9,16 @@ import { JwtService } from '@nestjs/jwt'; import type { JwtSignOptions } from '@nestjs/jwt'; import { ConfigService } from '@nestjs/config'; import * as bcrypt from 'bcrypt'; +import { Prisma } from '@prisma/client'; import { PrismaService } from '../../../prisma/prisma.service'; import { LoginDto } from './dto/login.dto'; import { RegisterDto } from './dto/register.dto'; +import { RegisterSendCodeDto } from './dto/register-send-code.dto'; +import { RegisterVerifyDto } from './dto/register-verify.dto'; +import { + EMAIL_VERIFICATION_PURPOSE, + EmailVerificationService, +} from '../email-verification/email-verification.service'; import { CreateOrganizationDto } from './dto/create-organization.dto'; import { SUPPORTED_USER_LANGUAGES, @@ -27,7 +34,9 @@ import { UpdateParticipationDto } from './dto/update-participation.dto'; import { SmsService } from '../sms/sms.service'; import { ForgotPasswordSendCodeDto, + ForgotPasswordSendEmailCodeDto, ForgotPasswordVerifyDto, + ForgotPasswordVerifyEmailDto, } from './dto/forgot-password.dto'; import { normalizeIranMobile } from '../../common/utils/mobile.util'; import { @@ -38,6 +47,54 @@ import { sessionExpiresAtFromNow } from '../../common/jwt-duration'; import { AppException, ErrorCode } from '../../common/errors'; import * as crypto from 'crypto'; +const loginUserInclude = { + memberships: { + include: { + organization: { + include: { + type: true, + plan: true, + }, + }, + permissions: { + include: { + permission: true, + }, + }, + }, + }, +} satisfies Prisma.UserInclude; + +type RegisterCodePayload = { + passwordHash: string; + name: string; + mobile: string; + organizationName: string; + organizationType: 'CLINIC' | 'LAB'; +}; + +function parseRegisterCodePayload(value: Prisma.JsonValue | null): RegisterCodePayload | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const row = value as Record; + const organizationType = row.organizationType; + if ( + typeof row.passwordHash !== 'string' || + typeof row.name !== 'string' || + typeof row.mobile !== 'string' || + typeof row.organizationName !== 'string' || + (organizationType !== 'CLINIC' && organizationType !== 'LAB') + ) { + return null; + } + return { + passwordHash: row.passwordHash, + name: row.name, + mobile: row.mobile, + organizationName: row.organizationName, + organizationType, + }; +} + const FORGOT_PASSWORD_PURPOSE = 'forgot_password'; const VERIFICATION_CODE_TTL_MS = 10 * 60 * 1000; const SEND_CODE_COOLDOWN_MS = 60 * 1000; @@ -85,6 +142,7 @@ export class AuthService { private configService: ConfigService, private smsService: SmsService, private staffWorkingHoursService: StaffWorkingHoursService, + private emailVerification: EmailVerificationService, ) { } private accessJwtSignOptions(): JwtSignOptions { @@ -157,6 +215,10 @@ export class AuthService { return null; } + if (!user.emailVerifiedAt) { + throw new AppException(ErrorCode.AUTH_EMAIL_NOT_VERIFIED, HttpStatus.FORBIDDEN); + } + // Remove sensitive data const { passwordHash, ...result } = user; return result; @@ -173,6 +235,10 @@ export class AuthService { */ async login(loginDto: LoginDto, user: any) { try { + if (!user?.emailVerifiedAt) { + throw new AppException(ErrorCode.AUTH_EMAIL_NOT_VERIFIED, HttpStatus.FORBIDDEN); + } + // Generate access token (short-lived) const accessPayload: JwtPayload = { sub: user.id, @@ -235,71 +301,74 @@ export class AuthService { } } - /** - * Register a new user - * @param registerDto - Registration data (email, password, name) - * @returns Created user info without password - */ - async register(registerDto: RegisterDto) { - const { password, name, organizationName, organizationType } = registerDto; - const email = registerDto.email.trim().toLowerCase(); - const trimmedOrganizationName = organizationName.trim(); + async sendRegisterCode(registerDto: RegisterSendCodeDto) { + const prepared = this.prepareRegistration(registerDto); + await this.assertRegistrationAvailable(this.prisma, prepared.email, prepared.mobile); + const passwordHash = await bcrypt.hash(prepared.password, 10); - if (!RegisterDto.isValidMobile(registerDto.mobile)) { - throw new AppException(ErrorCode.AUTH_REGISTRATION_MOBILE_INVALID, HttpStatus.BAD_REQUEST); - } - - const mobile = normalizeIranMobile(registerDto.mobile); - - // 1. Check existing user - const existingUser = await this.prisma.user.findFirst({ - where: { - OR: [{ email }, { mobile }], + await this.emailVerification.sendCode({ + email: prepared.email, + purpose: EMAIL_VERIFICATION_PURPOSE.register, + locale: registerDto.locale, + payload: { + passwordHash, + name: prepared.name, + mobile: prepared.mobile, + organizationName: prepared.organizationName, + organizationType: prepared.organizationType, }, }); - if (existingUser) { - if (existingUser.email === email) { - throw new AppException(ErrorCode.AUTH_REGISTRATION_EMAIL_EXISTS, HttpStatus.CONFLICT); + return { + success: true, + message: 'Verification code sent.', + }; + } + + async verifyRegisterCode(dto: RegisterVerifyDto) { + const email = dto.email.trim().toLowerCase(); + + await this.prisma.$transaction(async (tx) => { + const consumed = await this.emailVerification.consumeCode(tx, { + email, + purpose: EMAIL_VERIFICATION_PURPOSE.register, + code: dto.code, + }); + const payload = parseRegisterCodePayload(consumed.payload); + if (!payload) { + throw new AppException(ErrorCode.AUTH_VERIFICATION_CODE_INVALID, HttpStatus.UNAUTHORIZED); } - throw new AppException(ErrorCode.AUTH_REGISTRATION_MOBILE_EXISTS, HttpStatus.CONFLICT); - } - // 2. Hash password - const hashedPassword = await bcrypt.hash(password, 10); + await this.assertRegistrationAvailable(tx, email, payload.mobile); - // 3. Transaction (IMPORTANT) - const result = await this.prisma.$transaction(async (tx) => { - // Create user const user = await tx.user.create({ data: { email, - mobile, - passwordHash: hashedPassword, - name, + mobile: payload.mobile, + passwordHash: payload.passwordHash, + name: payload.name, trialUsedAt: new Date(), + emailVerifiedAt: new Date(), }, }); - // Create organization const organization = await tx.organization.create({ data: { - name: trimmedOrganizationName, + name: payload.organizationName, owner: { connect: { id: user.id }, }, plan: { - connect: { name: 'trial' }, // make sure this exists in DB + connect: { name: 'trial' }, }, type: { connect: { - name: organizationType, // 'CLINIC' | 'LAB' + name: payload.organizationType, }, }, }, }); - // Create membership (owner) await tx.membership.create({ data: { userId: user.id, @@ -307,18 +376,54 @@ export class AuthService { isOwner: true, }, }); - - return { user, organization }; }); - // 4. Generate tokens (reuse login logic) - const validatedUser = await this.validateUser(email, password); + const user = await this.prisma.user.findUnique({ + where: { email }, + include: loginUserInclude, + }); - if (!validatedUser) { + if (!user) { throw new AppException(ErrorCode.AUTH_REGISTRATION_FAILED, HttpStatus.UNAUTHORIZED); } - return this.login({ email, password } as any, validatedUser); + return this.login({ email, password: '' } as LoginDto, user); + } + + private prepareRegistration(registerDto: RegisterDto) { + const email = registerDto.email.trim().toLowerCase(); + + if (!RegisterDto.isValidMobile(registerDto.mobile)) { + throw new AppException(ErrorCode.AUTH_REGISTRATION_MOBILE_INVALID, HttpStatus.BAD_REQUEST); + } + + return { + email, + mobile: normalizeIranMobile(registerDto.mobile), + name: registerDto.name, + organizationName: registerDto.organizationName.trim(), + organizationType: registerDto.organizationType, + password: registerDto.password, + }; + } + + private async assertRegistrationAvailable( + db: PrismaService | Prisma.TransactionClient, + email: string, + mobile: string, + ) { + const existingUser = await db.user.findFirst({ + where: { + OR: [{ email }, { mobile }], + }, + }); + + if (!existingUser) return; + + if (existingUser.email === email) { + throw new AppException(ErrorCode.AUTH_REGISTRATION_EMAIL_EXISTS, HttpStatus.CONFLICT); + } + throw new AppException(ErrorCode.AUTH_REGISTRATION_MOBILE_EXISTS, HttpStatus.CONFLICT); } async createOrganization( @@ -773,17 +878,98 @@ export class AuthService { }; } + async sendForgotPasswordEmailCode(dto: ForgotPasswordSendEmailCodeDto) { + const email = dto.email.trim().toLowerCase(); + const user = await this.prisma.user.findUnique({ + where: { email }, + select: { id: true, emailVerifiedAt: true }, + }); + + if (!user?.emailVerifiedAt) { + return { + success: true, + message: 'If this email is registered, a verification code has been sent.', + }; + } + + const code = await this.emailVerification.sendCode({ + email, + purpose: EMAIL_VERIFICATION_PURPOSE.forgotPassword, + userId: user.id, + locale: dto.locale, + }); + + const isDevelopment = this.configService.get('NODE_ENV') === 'development'; + if (isDevelopment) { + console.log(`[dev] forgot-password code for ${email}: ${code}`); + } + + return { + success: true, + message: 'If this email is registered, a verification code has been sent.', + ...(isDevelopment ? { data: { devCode: code } } : {}), + }; + } + + async verifyForgotPasswordEmailCode(dto: ForgotPasswordVerifyEmailDto) { + const email = dto.email.trim().toLowerCase(); + + await this.prisma.$transaction(async (tx) => { + await this.emailVerification.consumeCode(tx, { + email, + purpose: EMAIL_VERIFICATION_PURPOSE.forgotPassword, + code: dto.code, + }); + }); + + const user = await this.prisma.user.findUnique({ + where: { email }, + include: loginUserInclude, + }); + + if (!user?.emailVerifiedAt) { + throw new AppException(ErrorCode.AUTH_VERIFICATION_CODE_INVALID, HttpStatus.UNAUTHORIZED); + } + + const loginResult = await this.login( + { email, password: '' } as LoginDto, + user, + ); + + return { + success: true, + data: { + accessToken: loginResult.data.accessToken, + refreshToken: loginResult.data.refreshToken, + user: loginResult.data.user, + organizations: loginResult.data.organizations, + passwordResetVerified: true, + }, + }; + } + async hasRecentPasswordResetVerification(userId: string): Promise { - const recent = await this.prisma.phoneVerificationCode.findFirst({ + const since = new Date(Date.now() - PASSWORD_RESET_WINDOW_MS); + const recentPhone = await this.prisma.phoneVerificationCode.findFirst({ where: { userId, purpose: FORGOT_PASSWORD_PURPOSE, - verifiedAt: { gt: new Date(Date.now() - PASSWORD_RESET_WINDOW_MS) }, + verifiedAt: { gt: since }, + }, + orderBy: { verifiedAt: 'desc' }, + }); + if (recentPhone) return true; + + const recentEmail = await this.prisma.emailVerificationCode.findFirst({ + where: { + userId, + purpose: EMAIL_VERIFICATION_PURPOSE.forgotPassword, + verifiedAt: { gt: since }, }, orderBy: { verifiedAt: 'desc' }, }); - return Boolean(recent); + return Boolean(recentEmail); } private generateVerificationCode(): string { diff --git a/backend/src/modules/auth/dto/forgot-password.dto.ts b/backend/src/modules/auth/dto/forgot-password.dto.ts index 1dcc935..dae07e0 100644 --- a/backend/src/modules/auth/dto/forgot-password.dto.ts +++ b/backend/src/modules/auth/dto/forgot-password.dto.ts @@ -1,4 +1,4 @@ -import { IsString, Matches, Length, MinLength } from 'class-validator'; +import { IsEmail, IsIn, IsOptional, IsString, Matches, Length } from 'class-validator'; import { isValidIranMobile } from '../../../common/utils/mobile.util'; import { ErrorCode } from '../../../common/errors'; @@ -21,3 +21,21 @@ export class ForgotPasswordVerifyDto { @Length(5, 6, { message: ErrorCode.VALIDATION_FIELD_REQUIRED }) code: string; } + +export class ForgotPasswordSendEmailCodeDto { + @IsEmail({}, { message: ErrorCode.VALIDATION_EMAIL_INVALID }) + email!: string; + + @IsOptional() + @IsIn(['en', 'fa', 'nl'], { message: ErrorCode.VALIDATION_LANGUAGE_INVALID }) + locale?: 'en' | 'fa' | 'nl'; +} + +export class ForgotPasswordVerifyEmailDto { + @IsEmail({}, { message: ErrorCode.VALIDATION_EMAIL_INVALID }) + email!: string; + + @IsString() + @Length(5, 6, { message: ErrorCode.VALIDATION_FIELD_REQUIRED }) + code!: string; +} diff --git a/backend/src/modules/auth/dto/register-send-code.dto.ts b/backend/src/modules/auth/dto/register-send-code.dto.ts new file mode 100644 index 0000000..1df843a --- /dev/null +++ b/backend/src/modules/auth/dto/register-send-code.dto.ts @@ -0,0 +1,9 @@ +import { IsIn, IsOptional } from 'class-validator'; +import { ErrorCode } from '../../../common/errors'; +import { RegisterDto } from './register.dto'; + +export class RegisterSendCodeDto extends RegisterDto { + @IsOptional() + @IsIn(['en', 'fa', 'nl'], { message: ErrorCode.VALIDATION_LANGUAGE_INVALID }) + locale?: 'en' | 'fa' | 'nl'; +} diff --git a/backend/src/modules/auth/dto/register-verify.dto.ts b/backend/src/modules/auth/dto/register-verify.dto.ts new file mode 100644 index 0000000..4ebad83 --- /dev/null +++ b/backend/src/modules/auth/dto/register-verify.dto.ts @@ -0,0 +1,11 @@ +import { IsEmail, IsString, Length } from 'class-validator'; +import { ErrorCode } from '../../../common/errors'; + +export class RegisterVerifyDto { + @IsEmail({}, { message: ErrorCode.VALIDATION_EMAIL_INVALID }) + email!: string; + + @IsString() + @Length(5, 6, { message: ErrorCode.VALIDATION_FIELD_REQUIRED }) + code!: string; +} diff --git a/backend/src/modules/email-verification/dto/send-invite-email-code.dto.ts b/backend/src/modules/email-verification/dto/send-invite-email-code.dto.ts new file mode 100644 index 0000000..c8e83c6 --- /dev/null +++ b/backend/src/modules/email-verification/dto/send-invite-email-code.dto.ts @@ -0,0 +1,12 @@ +import { IsIn, IsOptional, IsString, MinLength } from 'class-validator'; +import { ErrorCode } from '../../../common/errors'; + +export class SendInviteEmailCodeDto { + @IsString() + @MinLength(1, { message: ErrorCode.VALIDATION_TOKEN_REQUIRED }) + token!: string; + + @IsOptional() + @IsIn(['en', 'fa', 'nl'], { message: ErrorCode.VALIDATION_LANGUAGE_INVALID }) + locale?: 'en' | 'fa' | 'nl'; +} diff --git a/backend/src/modules/email-verification/email-verification.module.ts b/backend/src/modules/email-verification/email-verification.module.ts new file mode 100644 index 0000000..bafb0ab --- /dev/null +++ b/backend/src/modules/email-verification/email-verification.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { MailModule } from '../mail/mail.module'; +import { EmailVerificationService } from './email-verification.service'; + +@Module({ + imports: [MailModule], + providers: [EmailVerificationService], + exports: [EmailVerificationService], +}) +export class EmailVerificationModule {} diff --git a/backend/src/modules/email-verification/email-verification.service.ts b/backend/src/modules/email-verification/email-verification.service.ts new file mode 100644 index 0000000..e179715 --- /dev/null +++ b/backend/src/modules/email-verification/email-verification.service.ts @@ -0,0 +1,115 @@ +import { HttpStatus, Injectable } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { createHash, randomInt } from 'crypto'; +import { AppException, ErrorCode } from '../../common/errors'; +import { PrismaService } from '../../../prisma/prisma.service'; +import { EmailLocale, MailService } from '../mail/mail.service'; + +export const EMAIL_VERIFICATION_PURPOSE = { + register: 'register', + staffInvite: 'staff_invite', + orgInvite: 'org_invite', + forgotPassword: 'forgot_password', +} as const; + +export type EmailVerificationPurpose = + (typeof EMAIL_VERIFICATION_PURPOSE)[keyof typeof EMAIL_VERIFICATION_PURPOSE]; + +const VERIFICATION_CODE_TTL_MS = 10 * 60 * 1000; +const SEND_CODE_COOLDOWN_MS = 60 * 1000; + +type CodeDb = PrismaService | Prisma.TransactionClient; + +@Injectable() +export class EmailVerificationService { + constructor( + private readonly prisma: PrismaService, + private readonly mailService: MailService, + ) {} + + async sendCode(params: { + email: string; + purpose: EmailVerificationPurpose; + userId?: string | null; + payload?: Prisma.InputJsonValue; + locale?: string | null; + }): Promise { + const email = params.email.trim().toLowerCase(); + const recent = await this.prisma.emailVerificationCode.findFirst({ + where: { + email, + purpose: params.purpose, + createdAt: { gt: new Date(Date.now() - SEND_CODE_COOLDOWN_MS) }, + }, + orderBy: { createdAt: 'desc' }, + }); + + if (recent) { + throw new AppException(ErrorCode.AUTH_VERIFICATION_RATE_LIMIT, HttpStatus.BAD_REQUEST); + } + + const code = String(randomInt(10000, 100000)); + const codeHash = this.hashCode(code); + const row = await this.prisma.emailVerificationCode.create({ + data: { + email, + purpose: params.purpose, + userId: params.userId ?? null, + payload: params.payload, + codeHash, + expiresAt: new Date(Date.now() + VERIFICATION_CODE_TTL_MS), + }, + }); + + try { + await this.mailService.sendVerificationCode(email, code, this.normalizeLocale(params.locale)); + } catch (error) { + await this.prisma.emailVerificationCode.delete({ where: { id: row.id } }); + throw error; + } + + return code; + } + + async consumeCode( + db: CodeDb, + params: { email: string; purpose: EmailVerificationPurpose; code: string }, + ): Promise<{ payload: Prisma.JsonValue | null }> { + const email = params.email.trim().toLowerCase(); + const verification = await db.emailVerificationCode.findFirst({ + where: { + email, + purpose: params.purpose, + verifiedAt: null, + expiresAt: { gt: new Date() }, + }, + orderBy: { createdAt: 'desc' }, + }); + + if (!verification || !this.isCodeValid(params.code, verification.codeHash)) { + throw new AppException(ErrorCode.AUTH_VERIFICATION_CODE_INVALID, HttpStatus.UNAUTHORIZED); + } + + await db.emailVerificationCode.update({ + where: { id: verification.id }, + data: { verifiedAt: new Date() }, + }); + + return { payload: verification.payload }; + } + + private normalizeLocale(locale?: string | null): EmailLocale { + if (locale === 'fa' || locale === 'nl' || locale === 'en') return locale; + return 'en'; + } + + private hashCode(code: string): string { + return createHash('sha256').update(code.trim()).digest('hex'); + } + + private isCodeValid(code: string, codeHash: string): boolean { + const incoming = this.hashCode(code); + if (incoming.length !== codeHash.length) return false; + return incoming === codeHash; + } +} diff --git a/backend/src/modules/mail/mail.module.ts b/backend/src/modules/mail/mail.module.ts new file mode 100644 index 0000000..1ea1d72 --- /dev/null +++ b/backend/src/modules/mail/mail.module.ts @@ -0,0 +1,8 @@ +import { Module } from '@nestjs/common'; +import { MailService } from './mail.service'; + +@Module({ + providers: [MailService], + exports: [MailService], +}) +export class MailModule {} diff --git a/backend/src/modules/mail/mail.service.spec.ts b/backend/src/modules/mail/mail.service.spec.ts new file mode 100644 index 0000000..f340638 --- /dev/null +++ b/backend/src/modules/mail/mail.service.spec.ts @@ -0,0 +1,52 @@ +import { HttpStatus, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { AppException, ErrorCode } from '../../common/errors'; +import { MailService } from './mail.service'; + +function config(nodeEnv: string): ConfigService { + const values: Record = { + NODE_ENV: nodeEnv, + 'smtp.host': null, + 'smtp.user': null, + 'smtp.password': null, + 'smtp.port': 587, + }; + return { get: (key: string) => values[key] } as ConfigService; +} + +describe('MailService', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('logs the code in development when SMTP is unset', async () => { + const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined); + const service = new MailService(config('development')); + + await expect(service.sendVerificationCode('a@example.com', '12345', 'en')).resolves.toBeUndefined(); + + expect(warn).toHaveBeenCalledWith(expect.stringContaining('12345')); + }); + + it('refuses to send in production when SMTP is unset and does not log the code', async () => { + const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined); + const error = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined); + const service = new MailService(config('production')); + + let thrown: unknown; + try { + await service.sendVerificationCode('a@example.com', '12345', 'en'); + } catch (err) { + thrown = err; + } + + expect(thrown).toBeInstanceOf(AppException); + expect((thrown as AppException).getStatus()).toBe(HttpStatus.BAD_GATEWAY); + expect((thrown as AppException).getResponse()).toEqual({ + code: ErrorCode.AUTH_EMAIL_SEND_FAILED, + details: undefined, + }); + expect(warn).not.toHaveBeenCalled(); + expect(JSON.stringify(error.mock.calls)).not.toContain('12345'); + }); +}); diff --git a/backend/src/modules/mail/mail.service.ts b/backend/src/modules/mail/mail.service.ts new file mode 100644 index 0000000..2843fe7 --- /dev/null +++ b/backend/src/modules/mail/mail.service.ts @@ -0,0 +1,185 @@ +import { HttpStatus, Injectable, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import nodemailer from 'nodemailer'; +import { AppException, ErrorCode } from '../../common/errors'; + +export type EmailLocale = 'en' | 'fa' | 'nl'; + +export type InvitationLinkKind = 'staff' | 'organization'; + +const COPY: Record string }> = { + en: { + subject: 'Your Nudentic verification code', + text: (code) => + `Your verification code is ${code}. It expires in 10 minutes.`, + }, + fa: { + subject: 'کد تأیید نودنتیک', + text: (code) => `کد تأیید شما: ${code}\nاین کد تا ۱۰ دقیقه معتبر است.`, + }, + nl: { + subject: 'Uw Nudentic-verificatiecode', + text: (code) => + `Uw verificatiecode is ${code}. De code verloopt over 10 minuten.`, + }, +}; + +const INVITE_LINK_COPY: Record< + EmailLocale, + Record< + InvitationLinkKind, + { + subject: (organizationName: string) => string; + text: (organizationName: string, url: string) => string; + openLabel: string; + copyLabel: string; + } + > +> = { + en: { + staff: { + subject: (organizationName) => `Invitation to join ${organizationName}`, + text: (organizationName, url) => + `You are invited to join ${organizationName} on Nudentic.\n\nOpen this link:\n${url}\n\nOr copy it into your browser:\n${url}`, + openLabel: 'Open this link', + copyLabel: 'Or copy it into your browser', + }, + organization: { + subject: (organizationName) => `Invitation to connect ${organizationName}`, + text: (organizationName, url) => + `You are invited to connect ${organizationName} on Nudentic.\n\nOpen this link:\n${url}\n\nOr copy it into your browser:\n${url}`, + openLabel: 'Open this link', + copyLabel: 'Or copy it into your browser', + }, + }, + fa: { + staff: { + subject: (organizationName) => `دعوت برای پیوستن به ${organizationName}`, + text: (organizationName, url) => + `شما برای پیوستن به ${organizationName} در نودنتیک دعوت شده‌اید.\n\nاین پیوند را باز کنید:\n${url}\n\nیا آن را در مرورگر کپی کنید:\n${url}`, + openLabel: 'این پیوند را باز کنید', + copyLabel: 'یا آن را در مرورگر کپی کنید', + }, + organization: { + subject: (organizationName) => `دعوت برای اتصال به ${organizationName}`, + text: (organizationName, url) => + `شما برای اتصال به ${organizationName} در نودنتیک دعوت شده‌اید.\n\nاین پیوند را باز کنید:\n${url}\n\nیا آن را در مرورگر کپی کنید:\n${url}`, + openLabel: 'این پیوند را باز کنید', + copyLabel: 'یا آن را در مرورگر کپی کنید', + }, + }, + nl: { + staff: { + subject: (organizationName) => `Uitnodiging om lid te worden van ${organizationName}`, + text: (organizationName, url) => + `U bent uitgenodigd om lid te worden van ${organizationName} op Nudentic.\n\nOpen deze link:\n${url}\n\nOf kopieer deze in uw browser:\n${url}`, + openLabel: 'Open deze link', + copyLabel: 'Of kopieer deze in uw browser', + }, + organization: { + subject: (organizationName) => `Uitnodiging om ${organizationName} te koppelen`, + text: (organizationName, url) => + `U bent uitgenodigd om ${organizationName} te koppelen op Nudentic.\n\nOpen deze link:\n${url}\n\nOf kopieer deze in uw browser:\n${url}`, + openLabel: 'Open deze link', + copyLabel: 'Of kopieer deze in uw browser', + }, + }, +}; + +export function normalizeEmailLocale(locale?: string | null): EmailLocale { + if (locale === 'fa' || locale === 'nl' || locale === 'en') return locale; + return 'en'; +} + +function escapeHtml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +@Injectable() +export class MailService { + private readonly logger = new Logger(MailService.name); + + constructor(private readonly configService: ConfigService) {} + + async sendVerificationCode(email: string, code: string, locale: EmailLocale): Promise { + const copy = COPY[locale] ?? COPY.en; + await this.send({ + email, + subject: copy.subject, + text: copy.text(code), + devLog: `SMTP is not configured — verification code for ${email}: ${code}`, + failureLog: `Failed to send verification email to ${email}`, + }); + } + + async sendInvitationLink(params: { + email: string; + url: string; + organizationName: string; + kind: InvitationLinkKind; + locale?: string | null; + }): Promise { + const locale = normalizeEmailLocale(params.locale); + const copy = INVITE_LINK_COPY[locale][params.kind]; + const safeUrl = escapeHtml(params.url); + const intro = escapeHtml(copy.text(params.organizationName, params.url).split('\n\n')[0]); + const html = `

${intro}

${escapeHtml(copy.openLabel)}

${escapeHtml(copy.copyLabel)}:

${safeUrl}

`; + + await this.send({ + email: params.email, + subject: copy.subject(params.organizationName), + text: copy.text(params.organizationName, params.url), + html, + devLog: `SMTP is not configured — invitation link for ${params.email}: ${params.url}`, + failureLog: `Failed to send invitation link to ${params.email}`, + }); + } + + private async send(message: { + email: string; + subject: string; + text: string; + html?: string; + devLog: string; + failureLog: string; + }): Promise { + const host = this.configService.get('smtp.host'); + const user = this.configService.get('smtp.user'); + const password = this.configService.get('smtp.password'); + const port = this.configService.get('smtp.port') ?? 587; + + if (!host || !user || !password) { + if (this.configService.get('NODE_ENV') === 'development') { + this.logger.warn(message.devLog); + return; + } + + this.logger.error('SMTP is not configured'); + throw new AppException(ErrorCode.AUTH_EMAIL_SEND_FAILED, HttpStatus.BAD_GATEWAY); + } + + const transporter = nodemailer.createTransport({ + host, + port, + secure: port === 465, + auth: { user, pass: password }, + }); + + try { + await transporter.sendMail({ + from: user, + to: message.email, + subject: message.subject, + text: message.text, + html: message.html, + }); + } catch (error) { + this.logger.error(message.failureLog, error); + throw new AppException(ErrorCode.AUTH_EMAIL_SEND_FAILED, HttpStatus.BAD_GATEWAY); + } + } +} diff --git a/backend/src/modules/organization/dto/accept-organization-invite.dto.ts b/backend/src/modules/organization/dto/accept-organization-invite.dto.ts index 398e768..b49b7b5 100644 --- a/backend/src/modules/organization/dto/accept-organization-invite.dto.ts +++ b/backend/src/modules/organization/dto/accept-organization-invite.dto.ts @@ -1,4 +1,4 @@ -import { IsEnum, IsString, MinLength } from 'class-validator'; +import { IsEnum, IsOptional, IsString, Length, MinLength } from 'class-validator'; import { ErrorCode } from '../../../common/errors'; export class AcceptOrganizationInviteDto { @@ -20,4 +20,9 @@ export class AcceptOrganizationInviteDto { @IsString() @MinLength(8, { message: ErrorCode.VALIDATION_PASSWORD_TOO_SHORT }) password!: string; + + @IsOptional() + @IsString() + @Length(5, 6, { message: ErrorCode.VALIDATION_FIELD_REQUIRED }) + code?: string; } diff --git a/backend/src/modules/organization/organization.controller.ts b/backend/src/modules/organization/organization.controller.ts index 548dd3c..b2daf5a 100644 --- a/backend/src/modules/organization/organization.controller.ts +++ b/backend/src/modules/organization/organization.controller.ts @@ -16,6 +16,7 @@ import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dt import { CreateConnectionRequestDto } from './dto/create-connection-request.dto'; import { InviteOrganizationDto } from './dto/invite-organization.dto'; import { PreviewOrganizationInviteDto } from './dto/preview-organization-invite.dto'; +import { SendInviteEmailCodeDto } from '../email-verification/dto/send-invite-email-code.dto'; import { RespondConnectionRequestDto } from './dto/respond-connection-request.dto'; import { OrganizationService } from './organization.service'; import { ListLabCasesDto } from '../cases/dto/cases.dto'; @@ -53,6 +54,12 @@ export class OrganizationController { return this.organizationService.acceptInvite(dto); } + @Post('invitations/send-email-code') + @ApiOperation({ summary: 'Email a verification code for a new organization invite (public)' }) + sendInviteEmailCode(@Body() dto: SendInviteEmailCodeDto) { + return this.organizationService.sendInviteEmailCode(dto.token, dto.locale); + } + @Get('search') @UseGuards(JwtAuthGuard) @ApiOperation({ diff --git a/backend/src/modules/organization/organization.module.ts b/backend/src/modules/organization/organization.module.ts index 723212e..994e2c8 100644 --- a/backend/src/modules/organization/organization.module.ts +++ b/backend/src/modules/organization/organization.module.ts @@ -3,11 +3,13 @@ import { PrismaService } from '../../../prisma/prisma.service'; import { CasesModule } from '../cases/cases.module'; import { LabCaseCommentsModule } from '../lab-case-comments/lab-case-comments.module'; import { NotificationsModule } from '../notifications/notifications.module'; +import { EmailVerificationModule } from '../email-verification/email-verification.module'; +import { MailModule } from '../mail/mail.module'; import { OrganizationController } from './organization.controller'; import { OrganizationService } from './organization.service'; @Module({ - imports: [CasesModule, LabCaseCommentsModule, NotificationsModule], + imports: [CasesModule, LabCaseCommentsModule, NotificationsModule, EmailVerificationModule, MailModule], controllers: [OrganizationController], providers: [OrganizationService, PrismaService], }) diff --git a/backend/src/modules/organization/organization.service.ts b/backend/src/modules/organization/organization.service.ts index 936b098..66e75ca 100644 --- a/backend/src/modules/organization/organization.service.ts +++ b/backend/src/modules/organization/organization.service.ts @@ -1,4 +1,4 @@ -import { HttpStatus, Injectable } from '@nestjs/common'; +import { HttpStatus, Injectable, Logger } from '@nestjs/common'; import { AppException, ErrorCode } from '../../common/errors'; import { LinkStatus, UserNotificationType } from '@prisma/client'; import * as bcrypt from 'bcrypt'; @@ -13,6 +13,11 @@ import { CasesService } from '../cases/cases.service'; import { LabCaseCommentsService } from '../lab-case-comments/lab-case-comments.service'; import { CreateLabCaseCommentDto } from '../lab-case-comments/dto/lab-case-comment.dto'; import { UserNotificationService } from '../notifications/user-notification.service'; +import { MailService, normalizeEmailLocale } from '../mail/mail.service'; +import { + EMAIL_VERIFICATION_PURPOSE, + EmailVerificationService, +} from '../email-verification/email-verification.service'; import { canConnectOrganizationTypes } from '../../common/linked-organizations'; import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto'; import { CreateConnectionRequestDto } from './dto/create-connection-request.dto'; @@ -36,11 +41,15 @@ import { RespondConnectionRequestDto } from './dto/respond-connection-request.dt */ @Injectable() export class OrganizationService { + private readonly logger = new Logger(OrganizationService.name); + constructor( private readonly prisma: PrismaService, private readonly casesService: CasesService, private readonly commentsService: LabCaseCommentsService, private readonly userNotifications: UserNotificationService, + private readonly emailVerification: EmailVerificationService, + private readonly mailService: MailService, ) {} getOrganizationIdFromUser(user: { organizationId?: string }) { @@ -518,6 +527,7 @@ export class OrganizationService { id: true, acceptedAt: true, revokedAt: true, + invitedOwnerEmail: true, }, }); if (!invitation) { @@ -540,11 +550,26 @@ export class OrganizationService { }, }); + const invitationUrl = this.buildInviteUrl(plainToken); + const inviterOrg = await this.prisma.organization.findUnique({ + where: { id: organizationId }, + select: { name: true }, + }); + if (inviterOrg) { + await this.emailInviteLink({ + inviterUserId: userId, + email: invitation.invitedOwnerEmail, + url: invitationUrl, + organizationName: inviterOrg.name, + kind: 'organization', + }); + } + return { success: true, data: { invitationId: invitation.id, - invitationUrl: this.buildInviteUrl(plainToken), + invitationUrl, }, }; } @@ -658,12 +683,27 @@ export class OrganizationService { }); }); + const invitationUrl = this.buildInviteUrl(plainToken); + const inviterOrg = await this.prisma.organization.findUnique({ + where: { id: organizationId }, + select: { name: true }, + }); + if (inviterOrg) { + await this.emailInviteLink({ + inviterUserId: userId, + email: ownerEmail, + url: invitationUrl, + organizationName: inviterOrg.name, + kind: 'organization', + }); + } + // Plain token is only available here and after getInvitationLink; UI may cache it in localStorage. return { success: true, data: { invitationId: invitation.id, - invitationUrl: this.buildInviteUrl(plainToken), + invitationUrl, status: 'PENDING', }, }; @@ -671,6 +711,10 @@ export class OrganizationService { async previewInvite(token: string) { const invitation = await this.findValidInvitation(token); + const owner = await this.prisma.user.findUnique({ + where: { email: invitation.invitedOwnerEmail }, + select: { emailVerifiedAt: true }, + }); return { success: true, data: { @@ -680,10 +724,35 @@ export class OrganizationService { inviterOrganizationName: invitation.inviterOrganization.name, expiresAt: invitation.expiresAt.toISOString(), status: invitation.acceptedAt ? 'ACCEPTED' : 'PENDING', + emailVerificationRequired: !invitation.acceptedAt && !owner?.emailVerifiedAt, }, }; } + async sendInviteEmailCode(token: string, locale?: string) { + const invitation = await this.findValidInvitation(token); + if (invitation.acceptedAt) { + throw new AppException(ErrorCode.ORG_INVITE_ALREADY_ACCEPTED, HttpStatus.BAD_REQUEST); + } + + const owner = await this.prisma.user.findUnique({ + where: { email: invitation.invitedOwnerEmail }, + select: { id: true, emailVerifiedAt: true }, + }); + if (owner?.emailVerifiedAt) { + return { success: true, data: { sent: false } }; + } + + await this.emailVerification.sendCode({ + email: invitation.invitedOwnerEmail, + purpose: EMAIL_VERIFICATION_PURPOSE.orgInvite, + userId: owner?.id, + locale, + }); + + return { success: true, data: { sent: true } }; + } + /** Public signup completion: activates trial org and the pre-created OrganizationLink. */ async acceptInvite(dto: AcceptOrganizationInviteDto) { const invitation = await this.findValidInvitation(dto.token); @@ -703,6 +772,15 @@ export class OrganizationService { const ownerEmail = invitation.invitedOwnerEmail; let owner = await tx.user.findUnique({ where: { email: ownerEmail } }); + if (!owner?.emailVerifiedAt) { + await this.emailVerification.consumeCode(tx, { + email: ownerEmail, + purpose: EMAIL_VERIFICATION_PURPOSE.orgInvite, + code: dto.code ?? '', + }); + } + + const verifiedAt = new Date(); if (!owner) { owner = await tx.user.create({ data: { @@ -710,6 +788,7 @@ export class OrganizationService { name: dto.ownerName.trim(), passwordHash, trialUsedAt: new Date(), + emailVerifiedAt: verifiedAt, }, }); } else if (!owner.passwordHash) { @@ -719,8 +798,14 @@ export class OrganizationService { passwordHash, name: dto.ownerName.trim(), trialUsedAt: owner.trialUsedAt ?? new Date(), + emailVerifiedAt: owner.emailVerifiedAt ?? verifiedAt, }, }); + } else if (!owner.emailVerifiedAt) { + owner = await tx.user.update({ + where: { id: owner.id }, + data: { emailVerifiedAt: verifiedAt }, + }); } await assertOwnerOrganizationNameAvailable(tx, owner.id, organizationName, { @@ -903,6 +988,30 @@ export class OrganizationService { return d; } + private async emailInviteLink(params: { + inviterUserId: string; + email: string; + url: string; + organizationName: string; + kind: 'staff' | 'organization'; + }): Promise { + const inviter = await this.prisma.user.findUnique({ + where: { id: params.inviterUserId }, + select: { language: true }, + }); + try { + await this.mailService.sendInvitationLink({ + email: params.email, + url: params.url, + organizationName: params.organizationName, + kind: params.kind, + locale: normalizeEmailLocale(inviter?.language), + }); + } catch (error) { + this.logger.error(`Failed to email invitation link to ${params.email}`, error); + } + } + private buildInviteUrl(token: string): string { const appUrl = process.env.FRONTEND_URL || 'http://localhost:3001'; return `${appUrl}/accept-organization-invite?token=${encodeURIComponent(token)}`; diff --git a/backend/src/modules/staff/dto/accept-staff-invite.dto.ts b/backend/src/modules/staff/dto/accept-staff-invite.dto.ts index 8a5cd45..139909d 100644 --- a/backend/src/modules/staff/dto/accept-staff-invite.dto.ts +++ b/backend/src/modules/staff/dto/accept-staff-invite.dto.ts @@ -1,4 +1,4 @@ -import { IsString, MinLength } from 'class-validator'; +import { IsOptional, IsString, Length, MinLength } from 'class-validator'; import { ErrorCode } from '../../../common/errors'; export class AcceptStaffInviteDto { @@ -13,4 +13,9 @@ export class AcceptStaffInviteDto { @IsString() @MinLength(1, { message: ErrorCode.VALIDATION_NAME_TOO_SHORT }) name: string; + + @IsOptional() + @IsString() + @Length(5, 6, { message: ErrorCode.VALIDATION_FIELD_REQUIRED }) + code?: string; } diff --git a/backend/src/modules/staff/staff.controller.ts b/backend/src/modules/staff/staff.controller.ts index 1f54804..2926af5 100644 --- a/backend/src/modules/staff/staff.controller.ts +++ b/backend/src/modules/staff/staff.controller.ts @@ -16,6 +16,7 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { AcceptStaffInviteDto } from './dto/accept-staff-invite.dto'; import { InviteStaffDto } from './dto/invite-staff.dto'; import { PreviewStaffInviteDto } from './dto/preview-staff-invite.dto'; +import { SendInviteEmailCodeDto } from '../email-verification/dto/send-invite-email-code.dto'; import { UpdateStaffMemberDto } from './dto/update-staff-member.dto'; import { UpsertWorkingHoursDto } from './dto/upsert-working-hours.dto'; import { StaffService } from './staff.service'; @@ -42,6 +43,12 @@ export class StaffController { return this.staffService.acceptInvite(dto); } + @Post('invitations/send-email-code') + @ApiOperation({ summary: 'Email a verification code for a new staff invite (public)' }) + sendInviteEmailCode(@Body() dto: SendInviteEmailCodeDto) { + return this.staffService.sendInviteEmailCode(dto.token, dto.locale); + } + @Get() @UseGuards(JwtAuthGuard) @ApiOperation({ summary: 'List organization members (requires TAB_STAFF_READ or owner)' }) diff --git a/backend/src/modules/staff/staff.module.ts b/backend/src/modules/staff/staff.module.ts index 9258e96..6201fdb 100644 --- a/backend/src/modules/staff/staff.module.ts +++ b/backend/src/modules/staff/staff.module.ts @@ -1,12 +1,14 @@ import { Module } from '@nestjs/common'; import { PrismaService } from '../../../prisma/prisma.service'; import { NotificationsModule } from '../notifications/notifications.module'; +import { EmailVerificationModule } from '../email-verification/email-verification.module'; +import { MailModule } from '../mail/mail.module'; import { StaffController } from './staff.controller'; import { StaffService } from './staff.service'; import { StaffWorkingHoursService } from './staff-working-hours.service'; @Module({ - imports: [NotificationsModule], + imports: [NotificationsModule, EmailVerificationModule, MailModule], controllers: [StaffController], providers: [StaffService, StaffWorkingHoursService, PrismaService], exports: [StaffWorkingHoursService], diff --git a/backend/src/modules/staff/staff.service.ts b/backend/src/modules/staff/staff.service.ts index aa9fc59..2fd7023 100644 --- a/backend/src/modules/staff/staff.service.ts +++ b/backend/src/modules/staff/staff.service.ts @@ -1,6 +1,7 @@ import { HttpStatus, Injectable, + Logger, } from '@nestjs/common'; import { AppException, ErrorCode } from '../../common/errors'; import * as bcrypt from 'bcrypt'; @@ -16,12 +17,21 @@ import { import { InviteStaffDto } from './dto/invite-staff.dto'; import { UpdateStaffMemberDto } from './dto/update-staff-member.dto'; import { UserNotificationService } from '../notifications/user-notification.service'; +import { MailService, normalizeEmailLocale } from '../mail/mail.service'; +import { + EMAIL_VERIFICATION_PURPOSE, + EmailVerificationService, +} from '../email-verification/email-verification.service'; @Injectable() export class StaffService { + private readonly logger = new Logger(StaffService.name); + constructor( private readonly prisma: PrismaService, private readonly userNotifications: UserNotificationService, + private readonly emailVerification: EmailVerificationService, + private readonly mailService: MailService, ) {} getOrganizationIdFromUser(user: { organizationId?: string }) { @@ -213,9 +223,20 @@ export class StaffService { invitationId, inviteUrl, isPending: !existingUser, + organizationName: org.name, }; }); + if (result.inviteUrl) { + await this.emailInviteLink({ + inviterUserId: userId, + email, + url: result.inviteUrl, + organizationName: result.organizationName, + kind: 'staff', + }); + } + void this.userNotifications.notify({ organizationId, type: UserNotificationType.STAFF_INVITE, @@ -287,13 +308,28 @@ export class StaffService { }, }); + const invitationUrl = this.buildInviteUrl(plainToken); + const org = await this.prisma.organization.findUnique({ + where: { id: organizationId }, + select: { name: true }, + }); + if (org) { + await this.emailInviteLink({ + inviterUserId: userId, + email: membership.user.email, + url: invitationUrl, + organizationName: org.name, + kind: 'staff', + }); + } + return { success: true, data: { membershipId: membership.id, invitationId: invitation.id, email: membership.user.email, - invitationUrl: this.buildInviteUrl(plainToken), + invitationUrl, }, }; } @@ -312,10 +348,36 @@ export class StaffService { expiresAt: invitation.expiresAt.toISOString(), status: invitation.acceptedAt ? 'ACCEPTED' : 'PENDING', mode: invitation.membership.isActive ? 'password_setup' : 'join', + emailVerificationRequired: + !invitation.acceptedAt && + !invitation.membership.isActive && + !user.emailVerifiedAt, }, }; } + async sendInviteEmailCode(token: string, locale?: string) { + const invitation = await this.findValidInvitation(token); + if (invitation.acceptedAt) { + throw new AppException(ErrorCode.STAFF_INVITE_ALREADY_ACCEPTED, HttpStatus.BAD_REQUEST); + } + + const user = invitation.membership.user; + const required = !invitation.membership.isActive && !user.emailVerifiedAt; + if (!required) { + return { success: true, data: { sent: false } }; + } + + await this.emailVerification.sendCode({ + email: user.email, + purpose: EMAIL_VERIFICATION_PURPOSE.staffInvite, + userId: user.id, + locale, + }); + + return { success: true, data: { sent: true } }; + } + async clearPassword( actorUserId: string, organizationId: string, @@ -395,13 +457,24 @@ export class StaffService { const passwordHash = await bcrypt.hash(dto.password, 10); const now = new Date(); + const user = invitation.membership.user; + const requiresEmailCode = !invitation.membership.isActive && !user.emailVerifiedAt; await this.prisma.$transaction(async (tx) => { + if (requiresEmailCode) { + await this.emailVerification.consumeCode(tx, { + email: user.email, + purpose: EMAIL_VERIFICATION_PURPOSE.staffInvite, + code: dto.code ?? '', + }); + } + await tx.user.update({ where: { id: invitation.membership.userId }, data: { passwordHash, name: dto.name.trim(), + ...(user.emailVerifiedAt ? {} : { emailVerifiedAt: now }), }, }); @@ -656,6 +729,30 @@ export class StaffService { return d; } + private async emailInviteLink(params: { + inviterUserId: string; + email: string; + url: string; + organizationName: string; + kind: 'staff' | 'organization'; + }): Promise { + const inviter = await this.prisma.user.findUnique({ + where: { id: params.inviterUserId }, + select: { language: true }, + }); + try { + await this.mailService.sendInvitationLink({ + email: params.email, + url: params.url, + organizationName: params.organizationName, + kind: params.kind, + locale: normalizeEmailLocale(inviter?.language), + }); + } catch (error) { + this.logger.error(`Failed to email invitation link to ${params.email}`, error); + } + } + private buildInviteUrl(token: string): string { const appUrl = process.env.FRONTEND_URL || 'http://localhost:3001'; return `${appUrl}/accept-invite?token=${encodeURIComponent(token)}`; @@ -667,7 +764,7 @@ export class StaffService { include: { membership: { include: { - user: { select: { id: true, email: true, name: true } }, + user: { select: { id: true, email: true, name: true, emailVerifiedAt: true } }, organization: { select: { id: true, name: true } }, }, }, diff --git a/frontend/messages/en.json b/frontend/messages/en.json index b9f649a..e3e8863 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -150,14 +150,21 @@ "mobilePlaceholder": "0912 345 6789", "forgotPasswordTitle": "Reset your password", "forgotPasswordSubtitle": "Enter the mobile number on your account. We will send a verification code.", + "forgotPasswordEmailSubtitle": "Enter the email on your account. We will send a verification code.", + "resetBySms": "SMS", + "resetByEmail": "Email", "codeSentHint": "Enter the verification code we sent to your mobile.", + "codeSentTo": "Enter the verification code we sent to {destination}.", "sendCode": "Send verification code", "verificationCode": "Verification code", "verificationCodePlaceholder": "12345", "verifyAndContinue": "Verify and continue", "backToSignIn": "Back to sign in", "codeSendFailed": "Could not send verification code. Please try again.", - "verifyFailed": "Invalid or expired verification code." + "verifyFailed": "Invalid or expired verification code.", + "stepEmail": "Email", + "emailCodeSent": "Enter the verification code we sent to {email}.", + "resendCode": "Resend code" }, "landing": { "heroTitle": "Nudentic is a digital workflow platform for modern dentistry.", @@ -1341,6 +1348,8 @@ "AUTH_PASSWORD_RESET_EXPIRED": "Password reset verification expired. Please verify your mobile number again.", "AUTH_VERIFICATION_CODE_INVALID": "Invalid or expired verification code.", "AUTH_VERIFICATION_RATE_LIMIT": "Please wait a moment before requesting another code.", + "AUTH_EMAIL_NOT_VERIFIED": "Confirm this email before signing in. Enter the code we sent to that address.", + "AUTH_EMAIL_SEND_FAILED": "Could not send the verification email. Please try again.", "AUTH_SELECT_ORG_FIRST": "Select an organization before creating a new one.", "AUTH_CREATE_ORG_OWNER_ONLY": "Only owners of the current organization can create new organizations.", "AUTH_PASSWORD_CURRENT_REQUIRED": "Current password is required.", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index fa22b28..25865fc 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -150,14 +150,21 @@ "mobilePlaceholder": "۰۹۱۲ ۳۴۵ ۶۷۸۹", "forgotPasswordTitle": "بازیابی رمز عبور", "forgotPasswordSubtitle": "شماره موبایل ثبت‌شده در حساب خود را وارد کنید. کد تأیید برای شما ارسال می‌شود.", + "forgotPasswordEmailSubtitle": "ایمیل ثبت‌شده در حساب خود را وارد کنید. کد تأیید برای شما ارسال می‌شود.", + "resetBySms": "پیامک", + "resetByEmail": "ایمیل", "codeSentHint": "کد تأیید ارسال‌شده به موبایل خود را وارد کنید.", + "codeSentTo": "کد تأیید ارسال‌شده به {destination} را وارد کنید.", "sendCode": "ارسال کد تأیید", "verificationCode": "کد تأیید", "verificationCodePlaceholder": "۱۲۳۴۵", "verifyAndContinue": "تأیید و ادامه", "backToSignIn": "بازگشت به ورود", "codeSendFailed": "ارسال کد تأیید انجام نشد. دوباره تلاش کنید.", - "verifyFailed": "کد تأیید نامعتبر یا منقضی شده است." + "verifyFailed": "کد تأیید نامعتبر یا منقضی شده است.", + "stepEmail": "ایمیل", + "emailCodeSent": "کد تأیید ارسال‌شده به {email} را وارد کنید.", + "resendCode": "ارسال دوباره کد" }, "landing": { "heroTitle": "Nudentic یک پلتفرم گردش‌کار دیجیتال برای دندانپزشکی مدرن است.", @@ -1342,6 +1349,8 @@ "AUTH_PASSWORD_RESET_EXPIRED": "زمان بازیابی رمز عبور تمام شده است. دوباره شماره موبایل را تأیید کنید.", "AUTH_VERIFICATION_CODE_INVALID": "کد تأیید نامعتبر یا منقضی شده است.", "AUTH_VERIFICATION_RATE_LIMIT": "لطفاً کمی صبر کنید و دوباره درخواست کد دهید.", + "AUTH_EMAIL_NOT_VERIFIED": "پیش از ورود، این ایمیل را تأیید کنید. کد ارسال‌شده به این نشانی را وارد کنید.", + "AUTH_EMAIL_SEND_FAILED": "ایمیل تأیید ارسال نشد. دوباره تلاش کنید.", "AUTH_SELECT_ORG_FIRST": "قبل از ایجاد سازمان جدید، یک سازمان را انتخاب کنید.", "AUTH_CREATE_ORG_OWNER_ONLY": "فقط مالک سازمان فعلی می‌تواند سازمان جدید ایجاد کند.", "AUTH_PASSWORD_CURRENT_REQUIRED": "رمز عبور فعلی الزامی است.", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index 94771e0..cbef722 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -150,14 +150,21 @@ "mobilePlaceholder": "0612 345 678", "forgotPasswordTitle": "Wachtwoord herstellen", "forgotPasswordSubtitle": "Voer het mobiele nummer van uw account in. We sturen een verificatiecode.", + "forgotPasswordEmailSubtitle": "Voer het e-mailadres van uw account in. We sturen een verificatiecode.", + "resetBySms": "Sms", + "resetByEmail": "E-mail", "codeSentHint": "Voer de verificatiecode in die we naar uw mobiel hebben gestuurd.", + "codeSentTo": "Voer de verificatiecode in die we naar {destination} hebben gestuurd.", "sendCode": "Verificatiecode versturen", "verificationCode": "Verificatiecode", "verificationCodePlaceholder": "12345", "verifyAndContinue": "Verifiëren en doorgaan", "backToSignIn": "Terug naar inloggen", "codeSendFailed": "Verificatiecode kon niet worden verstuurd. Probeer het opnieuw.", - "verifyFailed": "Ongeldige of verlopen verificatiecode." + "verifyFailed": "Ongeldige of verlopen verificatiecode.", + "stepEmail": "E-mail", + "emailCodeSent": "Voer de verificatiecode in die we naar {email} hebben gestuurd.", + "resendCode": "Code opnieuw versturen" }, "landing": { "heroTitle": "Nudentic is een digitaal workflowplatform voor de moderne tandheelkunde.", @@ -1341,6 +1348,8 @@ "AUTH_PASSWORD_RESET_EXPIRED": "Wachtwoordherstel is verlopen. Verifieer uw mobiele nummer opnieuw.", "AUTH_VERIFICATION_CODE_INVALID": "Ongeldige of verlopen verificatiecode.", "AUTH_VERIFICATION_RATE_LIMIT": "Wacht even voordat u opnieuw een code aanvraagt.", + "AUTH_EMAIL_NOT_VERIFIED": "Bevestig dit e-mailadres voordat u inlogt. Voer de code in die we naar dat adres hebben gestuurd.", + "AUTH_EMAIL_SEND_FAILED": "De verificatie-e-mail kon niet worden verzonden. Probeer het opnieuw.", "AUTH_SELECT_ORG_FIRST": "Selecteer een organisatie voordat u een nieuwe aanmaakt.", "AUTH_CREATE_ORG_OWNER_ONLY": "Alleen eigenaren van de huidige organisatie kunnen nieuwe organisaties aanmaken.", "AUTH_PASSWORD_CURRENT_REQUIRED": "Huidig wachtwoord is verplicht.", diff --git a/frontend/src/app/[locale]/(public)/accept-invite/page.tsx b/frontend/src/app/[locale]/(public)/accept-invite/page.tsx index f69f07b..fd0ed26 100644 --- a/frontend/src/app/[locale]/(public)/accept-invite/page.tsx +++ b/frontend/src/app/[locale]/(public)/accept-invite/page.tsx @@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react'; import { Suspense } from 'react'; -import { useTranslations } from 'next-intl'; +import { useLocale, useTranslations } from 'next-intl'; import { Link, useRouter } from '@/i18n/navigation'; import { useSearchParams } from 'next/navigation'; import { Button } from '@/components/ui/shared/Button'; @@ -12,9 +12,13 @@ import { staffApi } from '@/lib/api/staff'; import { useAuth } from '@/lib/hooks/useAuth'; import { navigateIntoAppIfOrgSelected } from '@/lib/auth/postAuthRedirect'; +const autoSentStaffCodes = new Set(); + function AcceptInviteContent() { const t = useTranslations('auth'); const tErrors = useTranslations('errors'); + const tValidation = useTranslations('validation'); + const locale = useLocale(); const params = useSearchParams(); const router = useRouter(); const { login } = useAuth(); @@ -31,7 +35,10 @@ function AcceptInviteContent() { expiresAt: string; status: 'PENDING' | 'ACCEPTED'; mode: 'join' | 'password_setup'; + emailVerificationRequired: boolean; } | null>(null); + const [verificationCode, setVerificationCode] = useState(''); + const [sendingCode, setSendingCode] = useState(false); const [name, setName] = useState(''); const [password, setPassword] = useState(''); @@ -69,6 +76,24 @@ function AcceptInviteContent() { })(); }, [token, t]); + useEffect(() => { + if (!token || !inviteInfo?.emailVerificationRequired) return; + if (autoSentStaffCodes.has(token)) return; + autoSentStaffCodes.add(token); + + void (async () => { + setSendingCode(true); + try { + await staffApi.sendInviteEmailCode(token, locale); + } catch (e: unknown) { + autoSentStaffCodes.delete(token); + setError(getUserFacingError(e, tErrors, t('codeSendFailed'))); + } finally { + setSendingCode(false); + } + })(); + }, [token, inviteInfo?.emailVerificationRequired, locale, t, tErrors]); + async function onAccept() { if (!token) return; setError(''); @@ -87,6 +112,10 @@ function AcceptInviteContent() { setError(t('passwordsDoNotMatch')); return; } + if (inviteInfo?.emailVerificationRequired && !verificationCode.trim()) { + setError(tValidation('codeRequired')); + return; + } setSubmitting(true); let accepted = false; @@ -95,6 +124,7 @@ function AcceptInviteContent() { token, name: nameToSubmit || inviteInfo?.name || '', password, + ...(inviteInfo?.emailVerificationRequired ? { code: verificationCode.trim() } : {}), }); accepted = true; const email = inviteInfo?.email?.trim(); @@ -176,6 +206,42 @@ function AcceptInviteContent() { onChange={(e) => setConfirmPassword(e.target.value)} passwordToggleLabels={passwordToggleLabels} /> + {inviteInfo?.emailVerificationRequired && ( + <> +

+ {t('emailCodeSent', { email: inviteInfo.email })} +

+ setVerificationCode(e.target.value)} + inputMode="numeric" + autoComplete="one-time-code" + placeholder={t('verificationCodePlaceholder')} + /> + + + )} diff --git a/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx b/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx index b650633..22ccaca 100644 --- a/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx +++ b/frontend/src/app/[locale]/(public)/accept-organization-invite/page.tsx @@ -1,7 +1,7 @@ 'use client'; import { Suspense, useEffect, useMemo, useState } from 'react'; -import { useTranslations } from 'next-intl'; +import { useLocale, useTranslations } from 'next-intl'; import { Link, useRouter } from '@/i18n/navigation'; import { useSearchParams } from 'next/navigation'; import { useForm, type FieldErrors, type UseFormRegister, type UseFormSetValue } from 'react-hook-form'; @@ -20,6 +20,8 @@ import { organizationApi } from '@/lib/api/organization'; import { useAuth } from '@/lib/hooks/useAuth'; import { navigateIntoAppIfOrgSelected } from '@/lib/auth/postAuthRedirect'; +const autoSentOrganizationCodes = new Set(); + type AcceptOrganizationInviteForm = { ownerName: string; password: string; @@ -33,6 +35,7 @@ function AcceptOrganizationInviteContent() { const tErrors = useTranslations('errors'); const tCommon = useTranslations('common'); const tValidation = useTranslations('validation'); + const locale = useLocale(); const params = useSearchParams(); const router = useRouter(); const { login } = useAuth(); @@ -73,7 +76,10 @@ function AcceptOrganizationInviteContent() { inviterOrganizationName: string; expiresAt: string; status: 'PENDING' | 'ACCEPTED'; + emailVerificationRequired: boolean; } | null>(null); + const [verificationCode, setVerificationCode] = useState(''); + const [sendingCode, setSendingCode] = useState(false); const { register, @@ -124,6 +130,24 @@ function AcceptOrganizationInviteContent() { })(); }, [token, reset, t]); + useEffect(() => { + if (!token || !inviteInfo?.emailVerificationRequired) return; + if (autoSentOrganizationCodes.has(token)) return; + autoSentOrganizationCodes.add(token); + + void (async () => { + setSendingCode(true); + try { + await organizationApi.sendInviteEmailCode(token, locale); + } catch (e: unknown) { + autoSentOrganizationCodes.delete(token); + setError(getUserFacingError(e, tErrors, t('codeSendFailed'))); + } finally { + setSendingCode(false); + } + })(); + }, [token, inviteInfo?.emailVerificationRequired, locale, t, tErrors]); + const handleNext = async () => { const isValid = await trigger(['ownerName', 'password', 'confirmPassword']); if (isValid) { @@ -134,6 +158,10 @@ function AcceptOrganizationInviteContent() { const onSubmit = async (data: AcceptOrganizationInviteForm) => { if (!token) return; + if (inviteInfo?.emailVerificationRequired && !verificationCode.trim()) { + setError(tValidation('codeRequired')); + return; + } setError(''); setSuccess(''); setSubmitting(true); @@ -145,6 +173,7 @@ function AcceptOrganizationInviteContent() { password: data.password, organizationName: data.organizationName.trim(), organizationType: data.organizationType, + ...(inviteInfo?.emailVerificationRequired ? { code: verificationCode.trim() } : {}), }); accepted = true; const email = inviteInfo?.ownerEmail?.trim(); @@ -266,6 +295,42 @@ function AcceptOrganizationInviteContent() { organizationType={organizationType} setValue={setValue as unknown as UseFormSetValue} /> + {inviteInfo?.emailVerificationRequired && ( + <> +

+ {t('emailCodeSent', { email: inviteInfo.ownerEmail })} +

+ setVerificationCode(event.target.value)} + inputMode="numeric" + autoComplete="one-time-code" + placeholder={t('verificationCodePlaceholder')} + /> + + + )}
+ +
+ {channel === 'sms' ? ( + } + /> + ) : ( + } + /> + )} + ) : ( { + setDevCode(event.target.value); + setValue('code', event.target.value); + }} type="text" inputMode="numeric" autoComplete="one-time-code" placeholder={t('verificationCodePlaceholder')} - error={errors.code?.message} icon={} /> )} @@ -174,7 +233,7 @@ export default function ForgotPasswordPage() { )} - {step === 'mobile' ? ( + {step === 'request' ? ( + <> + +
+ + +
+ )}

diff --git a/frontend/src/app/[locale]/(public)/register/page.tsx b/frontend/src/app/[locale]/(public)/register/page.tsx index 48f9f32..cc74ca7 100644 --- a/frontend/src/app/[locale]/(public)/register/page.tsx +++ b/frontend/src/app/[locale]/(public)/register/page.tsx @@ -4,10 +4,11 @@ import { useMemo, useState } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import * as z from 'zod'; -import { useTranslations } from 'next-intl'; +import { useLocale, useTranslations } from 'next-intl'; import { Link } from '@/i18n/navigation'; -import { Mail, Lock, User, Phone } from 'lucide-react'; +import { Mail, Lock, User, Phone, ShieldCheck } from 'lucide-react'; import { getUserFacingError } from '@/components/shared/formatApiError'; +import { authApi } from '@/lib/api/auth'; import { useAuth } from '@/lib/hooks/useAuth'; import { useEnterAppWhenAuthenticated } from '@/lib/hooks/useEnterAppWhenAuthenticated'; import { AuthPageShell } from '@/components/ui/auth/AuthPageShell'; @@ -39,9 +40,13 @@ export default function RegisterPage() { const tCommon = useTranslations('common'); const tValidation = useTranslations('validation'); const tErrors = useTranslations('errors'); + const locale = useLocale(); const { registerTrial, isLoading, isAuthReady } = useAuth(); const [step, setStep] = useState(1); const [error, setError] = useState(null); + const [isSendingCode, setIsSendingCode] = useState(false); + const [pendingEmail, setPendingEmail] = useState(''); + const [verificationCode, setVerificationCode] = useState(''); useEnterAppWhenAuthenticated(); const registerSchema = useMemo( @@ -81,6 +86,7 @@ export default function RegisterPage() { formState: { errors }, trigger, setValue, + getValues, } = useForm({ resolver: zodResolver(registerSchema), mode: 'onChange', @@ -100,17 +106,36 @@ export default function RegisterPage() { } }; - const onSubmit = async (data: RegisterForm) => { + const sendCode = async (data: RegisterForm) => { + setIsSendingCode(true); try { setError(null); - await registerTrial( - data.email, - data.password, - data.name, - data.mobile, - data.organizationName, - data.organizationType, - ); + await authApi.sendRegisterCode({ + email: data.email, + password: data.password, + name: data.name, + mobile: data.mobile, + organizationName: data.organizationName, + organizationType: data.organizationType, + locale, + }); + setPendingEmail(data.email.trim()); + setStep(3); + } catch (err: unknown) { + setError(getUserFacingError(err, tErrors, t('codeSendFailed'))); + } finally { + setIsSendingCode(false); + } + }; + + const onVerify = async () => { + if (!verificationCode.trim()) { + setError(tValidation('codeRequired')); + return; + } + try { + setError(null); + await registerTrial(pendingEmail || getValues('email'), verificationCode.trim()); } catch (err: unknown) { setError(getUserFacingError(err, tErrors, t('registrationFailed'))); } @@ -149,7 +174,7 @@ export default function RegisterPage() { } >

- +

{t('trialIncludes')}

    @@ -168,7 +193,10 @@ export default function RegisterPage() {
- + event.preventDefault() : handleSubmit(sendCode)} + className="space-y-5 sm:space-y-6" + > {step === 1 && ( <> {tCommon('back')} - +
+ + )} + + {step === 3 && ( + <> +

+ {t('emailCodeSent', { email: pendingEmail })} +

+ setVerificationCode(event.target.value)} + type="text" + inputMode="numeric" + autoComplete="one-time-code" + placeholder={t('verificationCodePlaceholder')} + icon={} + /> + {error && ( +
+

{error}

+
+ )} +
+ +
+ )} diff --git a/frontend/src/components/ui/auth/RegistrationProgressSteps.tsx b/frontend/src/components/ui/auth/RegistrationProgressSteps.tsx index d841723..3bfb619 100644 --- a/frontend/src/components/ui/auth/RegistrationProgressSteps.tsx +++ b/frontend/src/components/ui/auth/RegistrationProgressSteps.tsx @@ -7,15 +7,48 @@ type RegistrationProgressStepsProps = { step: number; firstLabel?: string; secondLabel?: string; + thirdLabel?: string; }; export function RegistrationProgressSteps({ step, firstLabel, secondLabel, + thirdLabel, }: RegistrationProgressStepsProps) { const t = useTranslations('auth'); + if (thirdLabel) { + const labels = [firstLabel ?? t('stepAccount'), secondLabel ?? t('stepOrganization'), thirdLabel]; + return ( +
+ {labels.map((label, index) => ( +
+ {index > 0 && ( + + )} +
= index + 1 + ? 'bg-primary text-primary-contrast' + : 'border border-border bg-background-secondary text-text-secondary' + }`} + > + {index + 1} +
+
= index + 1 ? 'text-primary' : 'text-text-muted' + }`} + > + {label} +
+
+ ))} +
+ ); + } + return (
diff --git a/frontend/src/lib/api/auth.ts b/frontend/src/lib/api/auth.ts index 46b2d6c..59d9781 100644 --- a/frontend/src/lib/api/auth.ts +++ b/frontend/src/lib/api/auth.ts @@ -5,8 +5,13 @@ import type { SubscriptionAlertData } from '@/types/subscription'; export const authApi = { // Register a new trial organization - registerTrial: async (data: TrialRegistrationData): Promise => { - const response = await apiClient.post('/auth/register', data); + sendRegisterCode: async (data: TrialRegistrationData & { locale?: string }): Promise<{ success: boolean }> => { + const response = await apiClient.post('/auth/register/send-code', data); + return response.data; + }, + + verifyRegisterCode: async (email: string, code: string): Promise => { + const response = await apiClient.post('/auth/register/verify', { email, code }); return response.data; }, @@ -81,6 +86,22 @@ export const authApi = { return response.data; }, + sendForgotPasswordEmailCode: async ( + email: string, + locale: string, + ): Promise<{ success: boolean; message: string; data?: { devCode?: string } }> => { + const response = await apiClient.post('/auth/forgot-password/send-email-code', { email, locale }); + return response.data; + }, + + verifyForgotPasswordEmailCode: async ( + email: string, + code: string, + ): Promise => { + const response = await apiClient.post('/auth/forgot-password/verify-email', { email, code }); + return response.data; + }, + changePassword: async (data: { currentPassword?: string; newPassword: string; diff --git a/frontend/src/lib/api/client.ts b/frontend/src/lib/api/client.ts index 6222f37..a5bce8f 100644 --- a/frontend/src/lib/api/client.ts +++ b/frontend/src/lib/api/client.ts @@ -23,8 +23,10 @@ function isPublicInvitationRequest(url: string | undefined): boolean { return ( url.includes('/staff/invitations/preview') || url.includes('/staff/invitations/accept') || + url.includes('/staff/invitations/send-email-code') || url.includes('/organizations/invitations/preview') || - url.includes('/organizations/invitations/accept') + url.includes('/organizations/invitations/accept') || + url.includes('/organizations/invitations/send-email-code') ); } diff --git a/frontend/src/lib/api/organization.ts b/frontend/src/lib/api/organization.ts index 9d7be82..35ed5d1 100644 --- a/frontend/src/lib/api/organization.ts +++ b/frontend/src/lib/api/organization.ts @@ -117,6 +117,7 @@ export const organizationApi = { inviterOrganizationName: string; expiresAt: string; status: 'PENDING' | 'ACCEPTED'; + emailVerificationRequired: boolean; }; }> => { const response = await apiClient.get( @@ -131,11 +132,23 @@ export const organizationApi = { organizationType: 'CLINIC' | 'LAB'; ownerName: string; password: string; + code?: string; }): Promise<{ success: boolean; message: string; data: { organizationId: string } }> => { const response = await apiClient.post('/organizations/invitations/accept', body); return response.data; }, + sendInviteEmailCode: async ( + token: string, + locale: string, + ): Promise<{ success: boolean; data: { sent: boolean } }> => { + const response = await apiClient.post('/organizations/invitations/send-email-code', { + token, + locale, + }); + return response.data; + }, + listConnectionCases: async ( connectionId: string, params: ListLabCasesParams = {}, diff --git a/frontend/src/lib/api/staff.ts b/frontend/src/lib/api/staff.ts index deca72d..169b075 100644 --- a/frontend/src/lib/api/staff.ts +++ b/frontend/src/lib/api/staff.ts @@ -48,6 +48,7 @@ export interface PreviewInviteResponse { expiresAt: string; status: 'PENDING' | 'ACCEPTED'; mode: 'join' | 'password_setup'; + emailVerificationRequired: boolean; }; } @@ -105,11 +106,20 @@ export const staffApi = { token: string; password: string; name: string; + code?: string; }): Promise<{ success: boolean; message: string; data: { email: string } }> => { const response = await apiClient.post('/staff/invitations/accept', body); return response.data; }, + sendInviteEmailCode: async ( + token: string, + locale: string, + ): Promise<{ success: boolean; data: { sent: boolean } }> => { + const response = await apiClient.post('/staff/invitations/send-email-code', { token, locale }); + return response.data; + }, + updateMember: async ( membershipId: string, body: { name?: string; permissionNames?: string[] }, diff --git a/frontend/src/lib/hooks/useAuth.tsx b/frontend/src/lib/hooks/useAuth.tsx index 5eca7af..34d09d3 100644 --- a/frontend/src/lib/hooks/useAuth.tsx +++ b/frontend/src/lib/hooks/useAuth.tsx @@ -41,14 +41,7 @@ interface AuthContextType { isLoading: boolean; isAuthReady: boolean; apiError: ApiError | null; - registerTrial: ( - email: string, - password: string, - name: string, - mobile: string, - organizationName: string, - organizationType: 'CLINIC' | 'LAB' - ) => Promise; + registerTrial: (email: string, code: string) => Promise; login: ( email: string, password: string, @@ -258,26 +251,12 @@ export function AuthProvider({ children }: { children: React.ReactNode }) { }, []); // ✅ REGISTER - const registerTrial = useCallback(async ( - email: string, - password: string, - name: string, - mobile: string, - organizationName: string, - organizationType: 'CLINIC' | 'LAB' - ) => { + const registerTrial = useCallback(async (email: string, code: string) => { try { setIsLoading(true); setApiError(null); - const response = await authApi.registerTrial({ - email, - mobile, - password, - name, - organizationName, - organizationType, - }); + const response = await authApi.verifyRegisterCode(email, code); const userData = await applyUrlLocaleToUser(response.data.user); rememberAccessTokenExpiresAt(response.data.accessTokenExpiresAt); diff --git a/infrastructure/BACKUP.md b/infrastructure/BACKUP.md index dc5f651..453c8c9 100644 --- a/infrastructure/BACKUP.md +++ b/infrastructure/BACKUP.md @@ -1,6 +1,6 @@ # Manual database backup (nudentic.ir) -Copy-paste runbook for the production Postgres database. Use it when you need a dump in a hurry, a copy of production data on your Mac, or a restore after something has gone wrong. +Copy-paste runbook for the production Postgres database. Use it when you need a dump in a hurry, a copy of production data on your Mac or the Windows staging PC, or a restore after something has gone wrong. A **dump** is one file that contains the `dyolink_db` tables: users, patients, appointments, treatments, lab cases, billing, and so on. Taking a dump does **not** stop the site. Postgres reads a consistent snapshot while the app keeps running. @@ -17,11 +17,12 @@ The dump does **not** contain photo or case-file bytes. Those files live on disk | Dump folder on the server | `/opt/dyolink/infrastructure/database/backups` | | Same folder inside the container | `/backups` | | Copy on the Mac | `~/Documents/dental/nudentic-backups/` | +| Copy on the Windows staging PC | `C:\dyolink\nudentic-backups` | | Local Postgres container | `dyolink-postgres-dev` | The container already has `POSTGRES_USER` and `POSTGRES_DB`. Do not type the password, and do not print `database.env`. -Keep dump files private. They contain patient and account data. Do not commit them, and do not put them inside the git repo. `~/Documents/dental/nudentic-backups/` is outside the repo. +Keep dump files private. They contain patient and account data. Do not commit them, and do not put them inside the git repo. `~/Documents/dental/nudentic-backups/` and `C:\dyolink\nudentic-backups` are outside the repo. ## Do not @@ -41,7 +42,7 @@ The server keeps a new dump at three Iran times (`Asia/Tehran`, UTC+3:30). Each | 11:00 | Morning work | | 16:00 | Most of the afternoon | -The longest gap is overnight, from 16:00 to 02:00. Rows saved in that gap are only in the live database until the next file. These files sit on the same disk as the database. Copy them to the Mac with section 2 when you want copies that survive a dead server. Filenames use UTC, the same clock as the first manual dump. +The longest gap is overnight, from 16:00 to 02:00. Rows saved in that gap are only in the live database until the next file. These files sit on the same disk as the database. The Windows staging PC copies each dump off that disk 30 minutes later. The Mac copy in section 2 is the other off-site copy. Filenames use UTC, the same clock as the first manual dump. The script is [`scripts/backup-prod-db.sh`](scripts/backup-prod-db.sh). A git tag deploy does not copy it, so put it on the server once from the Mac: @@ -141,6 +142,88 @@ Output goes to `~/Documents/dental/nudentic-backups/copy.log`. --- +## Copy the dumps to the Windows staging PC + +The staging PC pulls the same folder three times a day, 30 minutes after each production dump. One run copies every `.dump` still on the server and skips a file that is already in `C:\dyolink\nudentic-backups`. If the PC is off at 11:30, that run starts when the PC is next on, and the 16:30 run still copies the 11:00 file while production is up. + +| Iran time | What it copies | +|-----------|----------------| +| 02:30 | The 02:00 dump | +| 11:30 | The 11:00 dump | +| 16:30 | The 16:00 dump | + +`nudentic_YYYYMMDD_HHMMSS.dump` files older than 30 days are deleted on the PC. `nudentic_before_restore_*.dump` is kept. This stores files only. It does not load them into the staging database, and it does not change the production server. + +The script is [`scripts/copy-prod-backup.ps1`](scripts/copy-prod-backup.ps1). It reads the production SSH password from `C:\dyolink\secrets\nudentic-ssh-password.txt`. A scheduled task has no person to type it. The password file is the full `dyolink` login. Do not commit it. + +A deploy does not install this. On the Windows PC, from a checkout of the repo: + +```powershell +New-Item -ItemType Directory -Force -Path C:\dyolink\scripts, C:\dyolink\nudentic-backups +Copy-Item infrastructure\scripts\copy-prod-backup.ps1, infrastructure\scripts\copy-prod-backup-askpass.cmd C:\dyolink\scripts\ +``` + +Put the production SSH password in `C:\dyolink\secrets\nudentic-ssh-password.txt` on one line. No quotes. + +The first run writes `C:\dyolink\scripts\copy-prod-backup-askpass.exe` next to the cmd file. Windows OpenSSH cannot start a `.cmd` as the password prompt, so that exe runs the cmd and passes the password through. It is created on the PC. It is not in git. + +Check the PC clock: + +```powershell +Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz' +``` + +If the offset is `+03:30`, register **02:30**, **11:30**, and **16:30**. The task runs as the current Windows user whether or not anyone is logged in. That user must be able to read `C:\dyolink\secrets`. The password it asks for is the Windows login, so the task can open the network connection. It is not the server password. + +```powershell +$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\dyolink\scripts\copy-prod-backup.ps1' +$triggers = @( + (New-ScheduledTaskTrigger -Daily -At '02:30'), + (New-ScheduledTaskTrigger -Daily -At '11:30'), + (New-ScheduledTaskTrigger -Daily -At '16:30') +) +$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew +$secure = Read-Host 'Windows account password (lets the task run when nobody is logged in)' -AsSecureString +$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) +$windowsPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) +[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) +Unregister-ScheduledTask -TaskName 'Nudentic copy prod backup' -Confirm:$false -ErrorAction SilentlyContinue +Register-ScheduledTask -TaskName 'Nudentic copy prod backup' -Action $action -Trigger $triggers -Settings $settings -User "$env:USERDOMAIN\$env:USERNAME" -Password $windowsPassword +``` + +If `Get-Date` shows UTC (`+00:00`), production’s jobs are 22:30, 07:30, and 12:30 UTC. Use **23:00**, **08:00**, and **13:00** in `$triggers` instead. + +### Already on the staging PC + +The task name is **Nudentic copy prod backup**. [`scripts/copy-prod-backup.ps1`](scripts/copy-prod-backup.ps1) only copies files. It does not create this task. Creating it is the `Register-ScheduledTask` block above, run once on the PC. + +On the staging PC it is already registered as `Administrator`. The clock there is Iran time (`+03:30`), and the triggers are 02:30, 11:30, and 16:30. Running that block again replaces the same task. + +See it: + +```powershell +Get-ScheduledTask -TaskName 'Nudentic copy prod backup' | Format-List TaskName, State +Get-ScheduledTaskInfo -TaskName 'Nudentic copy prod backup' | Format-List LastRunTime, LastTaskResult, NextRunTime +``` + +`State: Ready` means it is scheduled. `LastTaskResult` **267011** and a `LastRunTime` in 1999 mean it has never run. **0** means the last copy finished. + +Run it now without waiting for the next clock time: + +```powershell +Start-ScheduledTask -TaskName 'Nudentic copy prod backup' +``` + +Then read `C:\dyolink\nudentic-backups\copy.log`. A good line says `Copied nudentic_….dump`. A second run says `Already present`. The first run also stores the production host key in `known_hosts` in that folder. A `.dump` larger than a few kilobytes in `C:\dyolink\nudentic-backups` is a good file. + +You can also run the script by hand: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\dyolink\scripts\copy-prod-backup.ps1 +``` + +--- + ## 3. Load the dump into the local database This **deletes** the current local `dyolink_db` and replaces it with the dump. Production is not touched. diff --git a/infrastructure/DEPLOY.md b/infrastructure/DEPLOY.md index fea1e66..00fec58 100644 --- a/infrastructure/DEPLOY.md +++ b/infrastructure/DEPLOY.md @@ -46,7 +46,7 @@ Then `sudo systemctl restart docker` (containers restart). - `REGISTRY_PREFIX=wixur.ir:3000/` (same owner as Gitea `REGISTRY_OWNER`) - `TAG=v1.0.1` (CI overrides per release) -3. **`secrets/backend.env`:** `FRONTEND_URL=https://nudentic.ir`, `COOKIE_SECURE=true`, plus `ADMINJS_EMAIL` / `ADMINJS_PASSWORD` for `https://nudentic.ir/admin` +3. **`secrets/backend.env`:** `FRONTEND_URL=https://nudentic.ir`, `COOKIE_SECURE=true`, plus `ADMINJS_EMAIL` / `ADMINJS_PASSWORD` for `https://nudentic.ir/admin`. Set `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, and `SMTP_PASSWORD` (the user address is the From address). Verification email is refused when those are missing. 4. **SSH** — user that can run `docker` (e.g. `dyolink` in the `docker` group). Put the matching **public** key in `~/.ssh/authorized_keys`. @@ -513,7 +513,7 @@ Database dump and restore (take a backup, copy it off the server, load it locall |----------------|---------| | `/opt/dyolink/infrastructure/.env` | `DOMAIN`, `REGISTRY_PREFIX`, `TAG`, `POSTGRES_IMAGE`, `NGINX_IMAGE`, `CERTBOT_IMAGE` | | `/opt/dyolink/secrets/database.env` | Postgres credentials | -| `/opt/dyolink/secrets/backend.env` | API secrets, DATABASE_URL, JWT, SMS, `FRONTEND_URL` | +| `/opt/dyolink/secrets/backend.env` | API secrets, DATABASE_URL, JWT, SMS, SMTP, `FRONTEND_URL` | | `/opt/dyolink/infrastructure/nginx/generated/default.conf` | Auto-generated nginx SSL config | | `/opt/dyolink/infrastructure/scripts/prod-remote-deploy.sh` | Tag deploy (CI SSH) | | `/opt/dyolink/infrastructure/scripts/deploy-prod.sh` | First-time SSL + stack up | diff --git a/infrastructure/STAGING-DEPLOY.md b/infrastructure/STAGING-DEPLOY.md index 9add482..d0642d0 100644 --- a/infrastructure/STAGING-DEPLOY.md +++ b/infrastructure/STAGING-DEPLOY.md @@ -50,7 +50,7 @@ In Gitea → repo → **Settings → Actions → Variables**: - `PUBLIC_BASE_URL` = `https://wixur.ir` - `STAGING_HTTP_PORT` = `80` (optional; workflow default is 80) -On disk: `FRONTEND_URL=https://wixur.ir` and `COOKIE_SECURE=true` in `C:\dyolink\secrets\backend.staging.env`. +On disk: `FRONTEND_URL=https://wixur.ir` and `COOKIE_SECURE=true` in `C:\dyolink\secrets\backend.staging.env`. Also set `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, and `SMTP_PASSWORD` there (`SMTP_USER` is the From address). Verification email is refused when those are missing. Then run the **Registry — build, push, deploy** workflow so the frontend image is rebuilt without `:8088`. @@ -195,6 +195,7 @@ Rules: - `DATABASE_URL` password must match `POSTGRES_PASSWORD`. - `FRONTEND_URL` must match `PUBLIC_BASE_URL` (`http://wixur.ir`). - Replace JWT secrets with long random values (not `CHANGE_ME`). +- Set `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, and `SMTP_PASSWORD`. `SMTP_USER` is the From address. Verification email is refused when those are missing. ### 4. Gitea repository Variables diff --git a/infrastructure/backend.prod.env.example b/infrastructure/backend.prod.env.example index e6841ec..da35fac 100644 --- a/infrastructure/backend.prod.env.example +++ b/infrastructure/backend.prod.env.example @@ -28,6 +28,13 @@ COOKIE_SECURE=true SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY SMS_IR_TEMPLATE_ID=123456 +# Account email codes (register, staff invite, organization invite, forgot-password). +# Required. SMTP_USER is the From address. The API refuses to send when these are missing. +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USER=CHANGE_ME_SMTP_USER +SMTP_PASSWORD=CHANGE_ME_SMTP_PASSWORD + # GlitchTip (Sentry SDK). Empty = disabled. Use the dyolink-backend project DSN. # SENTRY_DSN=https://PUBLIC_KEY@errors.wixur.ir/1 # SENTRY_ENVIRONMENT=production diff --git a/infrastructure/backend.staging.env.example b/infrastructure/backend.staging.env.example index 6c72e9c..eb96673 100644 --- a/infrastructure/backend.staging.env.example +++ b/infrastructure/backend.staging.env.example @@ -25,6 +25,13 @@ COOKIE_SECURE=true SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY SMS_IR_TEMPLATE_ID=123456 +# Account email codes (register, staff invite, organization invite, forgot-password). +# Required. SMTP_USER is the From address. The API refuses to send when these are missing. +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USER=CHANGE_ME_SMTP_USER +SMTP_PASSWORD=CHANGE_ME_SMTP_PASSWORD + # GlitchTip (Sentry SDK). Empty = disabled. Use the dyolink-backend project DSN. # SENTRY_DSN=https://PUBLIC_KEY@errors.wixur.ir/1 # SENTRY_ENVIRONMENT=staging diff --git a/infrastructure/scripts/copy-prod-backup-askpass.cmd b/infrastructure/scripts/copy-prod-backup-askpass.cmd new file mode 100644 index 0000000..f471848 --- /dev/null +++ b/infrastructure/scripts/copy-prod-backup-askpass.cmd @@ -0,0 +1,4 @@ +@echo off +rem OpenSSH reads the production SSH password from stdout. Nothing else is printed. +chcp 65001 >nul +powershell.exe -NoLogo -NoProfile -NonInteractive -Command "$p = [IO.File]::ReadAllText('C:\dyolink\secrets\nudentic-ssh-password.txt'); if ($p.Length -gt 0 -and [int]$p[0] -eq 0xFEFF) { $p = $p.Substring(1) }; $p = $p.TrimEnd([char]13, [char]10); [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; [Console]::Out.Write($p)" diff --git a/infrastructure/scripts/copy-prod-backup.ps1 b/infrastructure/scripts/copy-prod-backup.ps1 new file mode 100644 index 0000000..5295935 --- /dev/null +++ b/infrastructure/scripts/copy-prod-backup.ps1 @@ -0,0 +1,235 @@ +# Run on the Windows staging PC. Reads the production SSH password from +# C:\dyolink\secrets\nudentic-ssh-password.txt and copies every dump in the +# production backup folder to C:\dyolink\nudentic-backups. Skips files already +# there. Deletes nudentic_YYYYMMDD_HHMMSS.dump older than 30 days. +# Does not delete nudentic_before_restore_*.dump. Does not save the password. +$ErrorActionPreference = 'Continue' + +$Remote = 'dyolink@185.243.48.140' +$RemoteDir = '/opt/dyolink/infrastructure/database/backups' +$Dest = 'C:\dyolink\nudentic-backups' +$PasswordFile = 'C:\dyolink\secrets\nudentic-ssh-password.txt' +$LogPath = Join-Path $Dest 'copy.log' +$AskPass = Join-Path $PSScriptRoot 'copy-prod-backup-askpass.cmd' +$KnownHosts = 'C:/dyolink/nudentic-backups/known_hosts' + +function Write-Log([string]$Message) { + $line = '[{0}] {1}' -f ([datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')), $Message + [System.IO.File]::AppendAllText($LogPath, $line + [Environment]::NewLine) + Write-Host $line +} + +function Format-ProcessArg([string]$Value) { + if ($Value -notmatch '[\s"]') { + return $Value + } + $escaped = $Value -replace '(\\+)$', '$1$1' -replace '(\\*)"', '$1$1\"' + return '"' + $escaped + '"' +} + +function Invoke-OpenSsh([string]$Exe, [string[]]$ArgumentList) { + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $Exe + $psi.Arguments = ($ArgumentList | ForEach-Object { Format-ProcessArg $_ }) -join ' ' + $psi.UseShellExecute = $false + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.CreateNoWindow = $true + + $proc = New-Object System.Diagnostics.Process + $proc.StartInfo = $psi + [void]$proc.Start() + $stdoutTask = $proc.StandardOutput.ReadToEndAsync() + $stderrTask = $proc.StandardError.ReadToEndAsync() + $finished = $proc.WaitForExit(1800000) + if (-not $finished) { + try { $proc.Kill() } catch {} + $proc.Dispose() + return [pscustomobject]@{ Code = 124; Out = ''; Err = 'timed out after 30 minutes' } + } + $stdout = $stdoutTask.Result + $stderr = $stderrTask.Result + $code = $proc.ExitCode + $proc.Dispose() + return [pscustomobject]@{ Code = $code; Out = $stdout; Err = $stderr.Trim() } +} + +function Ensure-AskpassExe([string]$CmdPath) { + # Windows OpenSSH starts SSH_ASKPASS with CreateProcess, which cannot run a .cmd. + # This exe runs the cmd and forwards its stdout unchanged. + $exePath = [System.IO.Path]::ChangeExtension($CmdPath, '.exe') + $cmdTime = (Get-Item -LiteralPath $CmdPath).LastWriteTimeUtc + if ((Test-Path -LiteralPath $exePath) -and (Get-Item -LiteralPath $exePath).LastWriteTimeUtc -ge $cmdTime) { + return $exePath + } + if (Test-Path -LiteralPath $exePath) { + Remove-Item -LiteralPath $exePath -Force + } + $source = @' +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; + +public class ProdBackupAskpass { + public static int Main() { + string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + string cmd = Path.Combine(dir, "copy-prod-backup-askpass.cmd"); + var psi = new ProcessStartInfo(); + psi.FileName = "cmd.exe"; + psi.Arguments = "/d /c \"" + cmd + "\""; + psi.UseShellExecute = false; + psi.RedirectStandardOutput = true; + psi.CreateNoWindow = true; + var proc = Process.Start(psi); + var bytes = new MemoryStream(); + proc.StandardOutput.BaseStream.CopyTo(bytes); + proc.WaitForExit(); + if (proc.ExitCode != 0) return proc.ExitCode; + var data = bytes.ToArray(); + using (var stdout = Console.OpenStandardOutput()) { + stdout.Write(data, 0, data.Length); + } + return 0; + } +} +'@ + Add-Type -TypeDefinition $source -OutputAssembly $exePath -OutputType ConsoleApplication -Language CSharp + return $exePath +} + +New-Item -ItemType Directory -Force -Path $Dest | Out-Null + +if (-not (Test-Path -LiteralPath $PasswordFile)) { + Write-Log "Backup copy failed: password file is missing ($PasswordFile)." + exit 1 +} +$passwordText = [System.IO.File]::ReadAllText($PasswordFile).TrimEnd([char]13, [char]10) +if ($passwordText.Length -gt 0 -and [int]$passwordText[0] -eq 0xFEFF) { + $passwordText = $passwordText.Substring(1) +} +if ([string]::IsNullOrWhiteSpace($passwordText)) { + Write-Log "Backup copy failed: password file is empty ($PasswordFile)." + exit 1 +} + +if (-not (Test-Path -LiteralPath $AskPass)) { + Write-Log "Backup copy failed: askpass helper is missing ($AskPass)." + exit 1 +} + +$ssh = (Get-Command ssh.exe -ErrorAction SilentlyContinue).Source +$scp = (Get-Command scp.exe -ErrorAction SilentlyContinue).Source +if (-not $ssh -or -not $scp) { + Write-Log 'Backup copy failed: ssh.exe or scp.exe is not on PATH. Install the Windows OpenSSH Client.' + exit 1 +} + +try { + $env:SSH_ASKPASS = Ensure-AskpassExe $AskPass +} catch { + Write-Log "Backup copy failed: could not prepare the password helper. $($_.Exception.Message)" + exit 1 +} +$env:SSH_ASKPASS_REQUIRE = 'force' +$env:DISPLAY = 'dummy' + +$sshOpts = @( + '-o', 'PreferredAuthentications=password', + '-o', 'PubkeyAuthentication=no', + '-o', 'NumberOfPasswordPrompts=1', + '-o', 'StrictHostKeyChecking=accept-new', + '-o', "UserKnownHostsFile=$KnownHosts", + '-o', 'ConnectTimeout=30' +) + +Write-Log 'Starting copy from production.' + +$list = Invoke-OpenSsh $ssh ($sshOpts + @($Remote, "ls -1 $RemoteDir/*.dump 2>/dev/null")) +if ($list.Code -ne 0 -and [string]::IsNullOrWhiteSpace($list.Out)) { + $detail = $list.Err + if ([string]::IsNullOrWhiteSpace($detail)) { + $detail = "ssh exit $($list.Code)" + } + if ($list.Code -eq 2) { + Write-Log "No dump found in $RemoteDir." + } else { + Write-Log "Backup copy failed: $detail" + } + exit 1 +} + +$remoteFiles = @($list.Out -split '\r?\n' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) +if ($remoteFiles.Count -eq 0) { + Write-Log "No dump found in $RemoteDir." + exit 1 +} + +$failed = $false +foreach ($remotePath in $remoteFiles) { + # Windows PowerShell 5.1 does not treat '/' as a separator in GetFileName. + $name = ($remotePath -split '/')[-1] + if ($name -notmatch '^(nudentic_\d{8}_\d{6}|nudentic_before_restore_\d{8}_\d{6})\.dump$') { + Write-Log "Skipped unexpected file: $name" + continue + } + if ($remotePath -ne "$RemoteDir/$name") { + Write-Log "Skipped unexpected path: $remotePath" + continue + } + + $localPath = Join-Path $Dest $name + if ((Test-Path -LiteralPath $localPath) -and (Get-Item -LiteralPath $localPath).Length -gt 0) { + Write-Log "Already present: $name" + continue + } + + $partial = "$localPath.partial" + if (Test-Path -LiteralPath $partial) { + Remove-Item -LiteralPath $partial -Force + } + + # A drive-letter path must use forward slashes so scp does not read "C:" as a host name. + $partialScp = $partial -replace '\\', '/' + $copied = Invoke-OpenSsh $scp ($sshOpts + @("${Remote}:${remotePath}", $partialScp)) + $partialLength = 0 + if (Test-Path -LiteralPath $partial) { + $partialLength = (Get-Item -LiteralPath $partial).Length + } + if ($copied.Code -ne 0 -or $partialLength -le 0) { + if (Test-Path -LiteralPath $partial) { + Remove-Item -LiteralPath $partial -Force + } + $detail = $copied.Err + if ([string]::IsNullOrWhiteSpace($detail)) { + $detail = "scp exit $($copied.Code)" + } + Write-Log "Backup copy failed for ${name}: $detail" + $failed = $true + continue + } + + Move-Item -LiteralPath $partial -Destination $localPath -Force + Write-Log "Copied $name ($partialLength bytes)" +} + +if ($failed) { + exit 1 +} + +$cutoff = [datetime]::UtcNow.Date.AddDays(-30) +Get-ChildItem -LiteralPath $Dest -File -Filter 'nudentic_*.dump' | ForEach-Object { + if ($_.Name -match '^nudentic_(\d{8})_\d{6}\.dump$') { + $stamp = [datetime]::SpecifyKind( + [datetime]::ParseExact($Matches[1], 'yyyyMMdd', [cultureinfo]::InvariantCulture), + [datetimekind]::Utc + ) + if ($stamp -lt $cutoff) { + Remove-Item -LiteralPath $_.FullName -Force + Write-Log "Removed $($_.Name) (older than 30 days)" + } + } +} + +Write-Log 'Copy finished.' +exit 0