forked from admin/dyolink
Confirm new accounts and invites with an emailed code before they can sign in.
Existing users stay verified. Password reset can use email as well as SMS.
This commit is contained in:
@@ -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
|
||||
|
||||
21
backend/package-lock.json
generated
21
backend/package-lock.json
generated
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
@@ -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?
|
||||
|
||||
@@ -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', {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) => ({
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
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<string>('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<boolean> {
|
||||
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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
9
backend/src/modules/auth/dto/register-send-code.dto.ts
Normal file
9
backend/src/modules/auth/dto/register-send-code.dto.ts
Normal file
@@ -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';
|
||||
}
|
||||
11
backend/src/modules/auth/dto/register-verify.dto.ts
Normal file
11
backend/src/modules/auth/dto/register-verify.dto.ts
Normal file
@@ -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;
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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<string> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
8
backend/src/modules/mail/mail.module.ts
Normal file
8
backend/src/modules/mail/mail.module.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MailService } from './mail.service';
|
||||
|
||||
@Module({
|
||||
providers: [MailService],
|
||||
exports: [MailService],
|
||||
})
|
||||
export class MailModule {}
|
||||
52
backend/src/modules/mail/mail.service.spec.ts
Normal file
52
backend/src/modules/mail/mail.service.spec.ts
Normal file
@@ -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<string, string | number | null> = {
|
||||
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');
|
||||
});
|
||||
});
|
||||
185
backend/src/modules/mail/mail.service.ts
Normal file
185
backend/src/modules/mail/mail.service.ts
Normal file
@@ -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<EmailLocale, { subject: string; text: (code: string) => 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, '>')
|
||||
.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<void> {
|
||||
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<void> {
|
||||
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 = `<p>${intro}</p><p><a href="${safeUrl}">${escapeHtml(copy.openLabel)}</a></p><p>${escapeHtml(copy.copyLabel)}:</p><p>${safeUrl}</p>`;
|
||||
|
||||
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<void> {
|
||||
const host = this.configService.get<string | null>('smtp.host');
|
||||
const user = this.configService.get<string | null>('smtp.user');
|
||||
const password = this.configService.get<string | null>('smtp.password');
|
||||
const port = this.configService.get<number>('smtp.port') ?? 587;
|
||||
|
||||
if (!host || !user || !password) {
|
||||
if (this.configService.get<string>('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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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],
|
||||
})
|
||||
|
||||
@@ -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<void> {
|
||||
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)}`;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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)' })
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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<void> {
|
||||
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 } },
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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": "رمز عبور فعلی الزامی است.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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<string>();
|
||||
|
||||
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 && (
|
||||
<>
|
||||
<p className="text-sm text-text-secondary">
|
||||
{t('emailCodeSent', { email: inviteInfo.email })}
|
||||
</p>
|
||||
<Input
|
||||
label={t('verificationCode')}
|
||||
value={verificationCode}
|
||||
onChange={(e) => setVerificationCode(e.target.value)}
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder={t('verificationCodePlaceholder')}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
fullWidth
|
||||
isLoading={sendingCode}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setSendingCode(true);
|
||||
setError('');
|
||||
try {
|
||||
await staffApi.sendInviteEmailCode(token, locale);
|
||||
} catch (e: unknown) {
|
||||
setError(getUserFacingError(e, tErrors, t('codeSendFailed')));
|
||||
} finally {
|
||||
setSendingCode(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{t('resendCode')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button type="button" fullWidth isLoading={submitting} onClick={() => onAccept()}>
|
||||
{inviteInfo?.mode === 'password_setup' ? t('setPasswordSubmit') : t('activateAccount')}
|
||||
</Button>
|
||||
|
||||
@@ -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<string>();
|
||||
|
||||
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<OrganizationDetailsFormValues>}
|
||||
/>
|
||||
{inviteInfo?.emailVerificationRequired && (
|
||||
<>
|
||||
<p className="text-sm text-text-secondary">
|
||||
{t('emailCodeSent', { email: inviteInfo.ownerEmail })}
|
||||
</p>
|
||||
<Input
|
||||
label={t('verificationCode')}
|
||||
value={verificationCode}
|
||||
onChange={(event) => setVerificationCode(event.target.value)}
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder={t('verificationCodePlaceholder')}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
fullWidth
|
||||
isLoading={sendingCode}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setSendingCode(true);
|
||||
setError('');
|
||||
try {
|
||||
await organizationApi.sendInviteEmailCode(token, locale);
|
||||
} catch (e: unknown) {
|
||||
setError(getUserFacingError(e, tErrors, t('codeSendFailed')));
|
||||
} finally {
|
||||
setSendingCode(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{t('resendCode')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
<Button type="button" variant="outline" onClick={() => setStep(1)}>
|
||||
{tCommon('back')}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { 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, useRouter } from '@/i18n/navigation';
|
||||
import { Phone, ShieldCheck } from 'lucide-react';
|
||||
import { Mail, Phone, ShieldCheck } from 'lucide-react';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import { getUserFacingError } from '@/components/shared/formatApiError';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
@@ -15,8 +14,11 @@ import { BrandLockup } from '@/components/ui/shared/BrandLockup';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
|
||||
type ResetChannel = 'sms' | 'email';
|
||||
|
||||
type ForgotPasswordForm = {
|
||||
mobile: string;
|
||||
email: string;
|
||||
code: string;
|
||||
};
|
||||
|
||||
@@ -29,53 +31,63 @@ function normalizeIranMobile(input: string): string {
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const t = useTranslations('auth');
|
||||
const tCommon = useTranslations('common');
|
||||
const tValidation = useTranslations('validation');
|
||||
const tErrors = useTranslations('errors');
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const { refreshSession } = useAuth();
|
||||
const [step, setStep] = useState<'mobile' | 'code'>('mobile');
|
||||
const [channel, setChannel] = useState<ResetChannel>('sms');
|
||||
const [step, setStep] = useState<'request' | 'code'>('request');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isVerifying, setIsVerifying] = useState(false);
|
||||
const [sentMobile, setSentMobile] = useState('');
|
||||
|
||||
const schema = useMemo(
|
||||
() =>
|
||||
z.object({
|
||||
mobile: z
|
||||
.string()
|
||||
.min(1, tValidation('mobileRequired'))
|
||||
.refine((value) => /^9\d{9}$/.test(normalizeIranMobile(value)), {
|
||||
message: tValidation('mobileInvalid'),
|
||||
}),
|
||||
code: z.string(),
|
||||
}),
|
||||
[tValidation],
|
||||
);
|
||||
const [sentTo, setSentTo] = useState('');
|
||||
const [devCode, setDevCode] = useState('');
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
getValues,
|
||||
formState: { errors },
|
||||
setValue,
|
||||
} = useForm<ForgotPasswordForm>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { mobile: '', code: '' },
|
||||
defaultValues: { mobile: '', email: '', code: '' },
|
||||
});
|
||||
|
||||
const onSendCode = async () => {
|
||||
const mobile = getValues('mobile');
|
||||
const parsed = schema.safeParse({ mobile, code: '' });
|
||||
if (!parsed.success) {
|
||||
setError(parsed.error.issues[0]?.message ?? tValidation('mobileInvalid'));
|
||||
if (channel === 'sms') {
|
||||
const mobile = getValues('mobile');
|
||||
if (!/^9\d{9}$/.test(normalizeIranMobile(mobile))) {
|
||||
setError(mobile.trim() ? tValidation('mobileInvalid') : tValidation('mobileRequired'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setError(null);
|
||||
setIsSending(true);
|
||||
await authApi.sendForgotPasswordCode(mobile);
|
||||
setDevCode('');
|
||||
setSentTo(mobile.trim());
|
||||
setStep('code');
|
||||
} catch (err: unknown) {
|
||||
setError(getUserFacingError(err, tErrors, t('codeSendFailed')));
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const email = getValues('email').trim();
|
||||
if (!z.string().email().safeParse(email).success) {
|
||||
setError(tValidation('emailInvalid'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setError(null);
|
||||
setIsSending(true);
|
||||
await authApi.sendForgotPasswordCode(mobile);
|
||||
setSentMobile(mobile);
|
||||
const response = await authApi.sendForgotPasswordEmailCode(email, locale);
|
||||
const printedCode = response.data?.devCode ?? '';
|
||||
setDevCode(printedCode);
|
||||
if (printedCode) setValue('code', printedCode);
|
||||
setSentTo(email);
|
||||
setStep('code');
|
||||
} catch (err: unknown) {
|
||||
setError(getUserFacingError(err, tErrors, t('codeSendFailed')));
|
||||
@@ -84,8 +96,9 @@ export default function ForgotPasswordPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const onVerify = async (data: ForgotPasswordForm) => {
|
||||
if (!data.code.trim()) {
|
||||
const onVerify = async () => {
|
||||
const code = getValues('code').trim();
|
||||
if (!code) {
|
||||
setError(tValidation('codeRequired'));
|
||||
return;
|
||||
}
|
||||
@@ -93,10 +106,10 @@ export default function ForgotPasswordPage() {
|
||||
try {
|
||||
setError(null);
|
||||
setIsVerifying(true);
|
||||
const response = await authApi.verifyForgotPasswordCode(
|
||||
sentMobile || data.mobile,
|
||||
data.code.trim(),
|
||||
);
|
||||
const response =
|
||||
channel === 'sms'
|
||||
? await authApi.verifyForgotPasswordCode(sentTo, code)
|
||||
: await authApi.verifyForgotPasswordEmailCode(sentTo, code);
|
||||
|
||||
const orgs = response.data.organizations;
|
||||
if (orgs.length === 1) {
|
||||
@@ -123,6 +136,13 @@ export default function ForgotPasswordPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const subtitle =
|
||||
step === 'code'
|
||||
? t('codeSentTo', { destination: sentTo })
|
||||
: channel === 'sms'
|
||||
? t('forgotPasswordSubtitle')
|
||||
: t('forgotPasswordEmailSubtitle');
|
||||
|
||||
return (
|
||||
<AuthPageShell
|
||||
header={
|
||||
@@ -133,37 +153,76 @@ export default function ForgotPasswordPage() {
|
||||
<h2 className="mt-4 sm:mt-6 text-center text-2xl sm:text-3xl font-semibold text-text-primary">
|
||||
{t('forgotPasswordTitle')}
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-text-secondary">
|
||||
{step === 'mobile' ? t('forgotPasswordSubtitle') : t('codeSentHint')}
|
||||
</p>
|
||||
<p className="mt-2 text-center text-sm text-text-secondary">{subtitle}</p>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="surface-card py-6 sm:py-8 px-4 sm:px-10">
|
||||
<form
|
||||
className="space-y-5 sm:space-y-6"
|
||||
onSubmit={handleSubmit(step === 'code' ? onVerify : () => undefined)}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (step === 'code') void onVerify();
|
||||
}}
|
||||
>
|
||||
{step === 'mobile' ? (
|
||||
<Input
|
||||
label={t('mobile')}
|
||||
{...register('mobile')}
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="tel"
|
||||
placeholder={t('mobilePlaceholder')}
|
||||
error={errors.mobile?.message}
|
||||
icon={<Phone className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
{step === 'request' ? (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={channel === 'sms' ? 'primary' : 'outline'}
|
||||
onClick={() => {
|
||||
setChannel('sms');
|
||||
setError(null);
|
||||
}}
|
||||
>
|
||||
{t('resetBySms')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={channel === 'email' ? 'primary' : 'outline'}
|
||||
onClick={() => {
|
||||
setChannel('email');
|
||||
setError(null);
|
||||
}}
|
||||
>
|
||||
{t('resetByEmail')}
|
||||
</Button>
|
||||
</div>
|
||||
{channel === 'sms' ? (
|
||||
<Input
|
||||
label={t('mobile')}
|
||||
{...register('mobile')}
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="tel"
|
||||
placeholder={t('mobilePlaceholder')}
|
||||
icon={<Phone className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
label={t('email')}
|
||||
{...register('email')}
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder={t('emailPlaceholder')}
|
||||
icon={<Mail className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Input
|
||||
label={t('verificationCode')}
|
||||
{...register('code')}
|
||||
name="code"
|
||||
value={devCode}
|
||||
onChange={(event) => {
|
||||
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={<ShieldCheck className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
)}
|
||||
@@ -174,7 +233,7 @@ export default function ForgotPasswordPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'mobile' ? (
|
||||
{step === 'request' ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
@@ -185,9 +244,35 @@ export default function ForgotPasswordPage() {
|
||||
{t('sendCode')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="submit" variant="primary" isLoading={isVerifying} fullWidth>
|
||||
{t('verifyAndContinue')}
|
||||
</Button>
|
||||
<>
|
||||
<Button type="submit" variant="primary" isLoading={isVerifying} fullWidth>
|
||||
{t('verifyAndContinue')}
|
||||
</Button>
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="sm:shrink-0"
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
setValue('code', '');
|
||||
setDevCode('');
|
||||
setStep('request');
|
||||
}}
|
||||
>
|
||||
{tCommon('back')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
fullWidth
|
||||
isLoading={isSending}
|
||||
onClick={() => onSendCode()}
|
||||
>
|
||||
{t('resendCode')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="text-center text-sm text-text-secondary">
|
||||
|
||||
@@ -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<string | null>(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<RegisterForm>({
|
||||
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() {
|
||||
}
|
||||
>
|
||||
<div className="surface-card py-6 sm:py-8 px-4 sm:px-10">
|
||||
<RegistrationProgressSteps step={step} />
|
||||
<RegistrationProgressSteps step={step} thirdLabel={t('stepEmail')} />
|
||||
<div className="mb-5 sm:mb-6 p-3 sm:p-4 bg-primary-soft rounded-[var(--radius-md)] border border-primary/35">
|
||||
<h3 className="text-sm font-medium text-text-primary mb-2">{t('trialIncludes')}</h3>
|
||||
<ul className="text-sm text-text-secondary space-y-1">
|
||||
@@ -168,7 +193,10 @@ export default function RegisterPage() {
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-5 sm:space-y-6">
|
||||
<form
|
||||
onSubmit={step === 3 ? (event) => event.preventDefault() : handleSubmit(sendCode)}
|
||||
className="space-y-5 sm:space-y-6"
|
||||
>
|
||||
{step === 1 && (
|
||||
<>
|
||||
<Input
|
||||
@@ -242,10 +270,64 @@ export default function RegisterPage() {
|
||||
>
|
||||
{tCommon('back')}
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" isLoading={isLoading} fullWidth>
|
||||
<Button type="submit" variant="primary" isLoading={isSendingCode} fullWidth>
|
||||
{t('sendCode')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<>
|
||||
<p className="text-sm text-text-secondary">
|
||||
{t('emailCodeSent', { email: pendingEmail })}
|
||||
</p>
|
||||
<Input
|
||||
label={t('verificationCode')}
|
||||
value={verificationCode}
|
||||
onChange={(event) => setVerificationCode(event.target.value)}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder={t('verificationCodePlaceholder')}
|
||||
icon={<ShieldCheck className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
{error && (
|
||||
<div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
setStep(2);
|
||||
}}
|
||||
className="sm:shrink-0"
|
||||
>
|
||||
{tCommon('back')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
isLoading={isLoading}
|
||||
fullWidth
|
||||
onClick={() => onVerify()}
|
||||
>
|
||||
{t('startMyFreeTrial')}
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
fullWidth
|
||||
isLoading={isSendingCode}
|
||||
onClick={() => sendCode(getValues())}
|
||||
>
|
||||
{t('resendCode')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
|
||||
@@ -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 (
|
||||
<div className="mb-6 sm:mb-8 flex items-center gap-1.5 sm:gap-2">
|
||||
{labels.map((label, index) => (
|
||||
<div key={label} className="flex min-w-0 flex-1 items-center gap-1.5 sm:gap-2">
|
||||
{index > 0 && (
|
||||
<ChevronRight className="h-4 w-4 shrink-0 text-text-muted icon-flat" />
|
||||
)}
|
||||
<div
|
||||
className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-sm sm:h-8 sm:w-8 ${
|
||||
step >= index + 1
|
||||
? 'bg-primary text-primary-contrast'
|
||||
: 'border border-border bg-background-secondary text-text-secondary'
|
||||
}`}
|
||||
>
|
||||
{index + 1}
|
||||
</div>
|
||||
<div
|
||||
className={`truncate text-xs font-medium sm:text-sm ${
|
||||
step >= index + 1 ? 'text-primary' : 'text-text-muted'
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-6 sm:mb-8">
|
||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 sm:flex sm:justify-between">
|
||||
|
||||
@@ -5,8 +5,13 @@ import type { SubscriptionAlertData } from '@/types/subscription';
|
||||
|
||||
export const authApi = {
|
||||
// Register a new trial organization
|
||||
registerTrial: async (data: TrialRegistrationData): Promise<AuthResponse> => {
|
||||
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<AuthResponse> => {
|
||||
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<ForgotPasswordVerifyResponse> => {
|
||||
const response = await apiClient.post('/auth/forgot-password/verify-email', { email, code });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
changePassword: async (data: {
|
||||
currentPassword?: string;
|
||||
newPassword: string;
|
||||
|
||||
@@ -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')
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 = {},
|
||||
|
||||
@@ -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[] },
|
||||
|
||||
@@ -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<void>;
|
||||
registerTrial: (email: string, code: string) => Promise<void>;
|
||||
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);
|
||||
|
||||
@@ -46,7 +46,7 @@ Then `sudo systemctl restart docker` (containers restart).
|
||||
- `REGISTRY_PREFIX=wixur.ir:3000/<gitea-owner>` (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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user