feat: fix auth flows — reset password, 2-step register, remember me, SIRET

- Backend: add forgot-password and reset-password endpoints with token-based
  flow (1h expiry, secure random token, email via existing EmailPort)
- Backend: add PasswordResetTokenOrmEntity + migration
- Backend: add siret field to RegisterOrganizationDto and pass it to org creation
- Backend: remove MinLength(12) from LoginDto.password (wrong for login use case)
- Backend: add rememberMe to LoginDto (optional, informational)
- Frontend: register page rewritten as 2-step flow (account info → org info)
  with SIRET field, Suspense wrapper, "Centre d'aide" link removed
- Frontend: forgot-password page rewritten in French, matching login style
- Frontend: reset-password page rewritten in French, matching login style, with Suspense
- Frontend: remember me now works — localStorage when checked, sessionStorage otherwise
- Frontend: login page removes "Centre d'aide" link, connects rememberMe to login
- Frontend: auth-context and api/auth updated to pass rememberMe through full chain

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
David 2026-04-02 13:10:08 +02:00
parent 6a38c236b2
commit 317de48765
15 changed files with 1001 additions and 594 deletions

View File

@ -17,6 +17,7 @@ import { TypeOrmInvitationTokenRepository } from '../../infrastructure/persisten
import { UserOrmEntity } from '../../infrastructure/persistence/typeorm/entities/user.orm-entity';
import { OrganizationOrmEntity } from '../../infrastructure/persistence/typeorm/entities/organization.orm-entity';
import { InvitationTokenOrmEntity } from '../../infrastructure/persistence/typeorm/entities/invitation-token.orm-entity';
import { PasswordResetTokenOrmEntity } from '../../infrastructure/persistence/typeorm/entities/password-reset-token.orm-entity';
import { InvitationService } from '../services/invitation.service';
import { InvitationsController } from '../controllers/invitations.controller';
import { EmailModule } from '../../infrastructure/email/email.module';
@ -40,7 +41,7 @@ import { SubscriptionsModule } from '../subscriptions/subscriptions.module';
}),
// 👇 Add this to register TypeORM repositories
TypeOrmModule.forFeature([UserOrmEntity, OrganizationOrmEntity, InvitationTokenOrmEntity]),
TypeOrmModule.forFeature([UserOrmEntity, OrganizationOrmEntity, InvitationTokenOrmEntity, PasswordResetTokenOrmEntity]),
// Email module for sending invitations
EmailModule,

View File

@ -5,10 +5,14 @@ import {
Logger,
Inject,
BadRequestException,
NotFoundException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import * as argon2 from 'argon2';
import * as crypto from 'crypto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, IsNull } from 'typeorm';
import { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
import { User, UserRole } from '@domain/entities/user.entity';
import {
@ -16,9 +20,11 @@ import {
ORGANIZATION_REPOSITORY,
} from '@domain/ports/out/organization.repository';
import { Organization } from '@domain/entities/organization.entity';
import { EmailPort, EMAIL_PORT } from '@domain/ports/out/email.port';
import { v4 as uuidv4 } from 'uuid';
import { RegisterOrganizationDto } from '../dto/auth-login.dto';
import { SubscriptionService } from '../services/subscription.service';
import { PasswordResetTokenOrmEntity } from '../../infrastructure/persistence/typeorm/entities/password-reset-token.orm-entity';
export interface JwtPayload {
sub: string; // user ID
@ -39,6 +45,10 @@ export class AuthService {
private readonly userRepository: UserRepository,
@Inject(ORGANIZATION_REPOSITORY)
private readonly organizationRepository: OrganizationRepository,
@Inject(EMAIL_PORT)
private readonly emailService: EmailPort,
@InjectRepository(PasswordResetTokenOrmEntity)
private readonly passwordResetTokenRepository: Repository<PasswordResetTokenOrmEntity>,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
private readonly subscriptionService: SubscriptionService
@ -205,6 +215,85 @@ export class AuthService {
}
}
/**
* Initiate password reset generates token and sends email
*/
async forgotPassword(email: string): Promise<void> {
this.logger.log(`Password reset requested for: ${email}`);
const user = await this.userRepository.findByEmail(email);
// Silently succeed if user not found (security: don't reveal user existence)
if (!user || !user.isActive) {
return;
}
// Invalidate any existing unused tokens for this user
await this.passwordResetTokenRepository.update(
{ userId: user.id, usedAt: IsNull() },
{ usedAt: new Date() }
);
// Generate a secure random token
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
await this.passwordResetTokenRepository.save({
userId: user.id,
token,
expiresAt,
usedAt: null,
});
await this.emailService.sendPasswordResetEmail(email, token);
this.logger.log(`Password reset email sent to: ${email}`);
}
/**
* Reset password using token from email
*/
async resetPassword(token: string, newPassword: string): Promise<void> {
const resetToken = await this.passwordResetTokenRepository.findOne({ where: { token } });
if (!resetToken) {
throw new BadRequestException('Token de réinitialisation invalide ou expiré');
}
if (resetToken.usedAt) {
throw new BadRequestException('Ce lien de réinitialisation a déjà été utilisé');
}
if (resetToken.expiresAt < new Date()) {
throw new BadRequestException('Le lien de réinitialisation a expiré. Veuillez en demander un nouveau.');
}
const user = await this.userRepository.findById(resetToken.userId);
if (!user || !user.isActive) {
throw new NotFoundException('Utilisateur introuvable');
}
const passwordHash = await argon2.hash(newPassword, {
type: argon2.argon2id,
memoryCost: 65536,
timeCost: 3,
parallelism: 4,
});
// Update password (mutates in place)
user.updatePassword(passwordHash);
await this.userRepository.save(user);
// Mark token as used
await this.passwordResetTokenRepository.update(
{ id: resetToken.id },
{ usedAt: new Date() }
);
this.logger.log(`Password reset successfully for user: ${user.email}`);
}
/**
* Validate user from JWT payload
*/
@ -336,6 +425,7 @@ export class AuthService {
type: organizationData.type,
scac: organizationData.scac,
siren: organizationData.siren,
siret: organizationData.siret,
address: {
street: organizationData.street,
city: organizationData.city,

View File

@ -11,7 +11,14 @@ import {
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { AuthService } from '../auth/auth.service';
import { LoginDto, RegisterDto, AuthResponseDto, RefreshTokenDto } from '../dto/auth-login.dto';
import {
LoginDto,
RegisterDto,
AuthResponseDto,
RefreshTokenDto,
ForgotPasswordDto,
ResetPasswordDto,
} from '../dto/auth-login.dto';
import { Public } from '../decorators/public.decorator';
import { CurrentUser, UserPayload } from '../decorators/current-user.decorator';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
@ -209,6 +216,41 @@ export class AuthController {
return { message: 'Logout successful' };
}
/**
* Forgot password sends reset email
*/
@Public()
@Post('forgot-password')
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: 'Forgot password',
description: 'Send a password reset email. Always returns 200 to avoid user enumeration.',
})
@ApiResponse({ status: 200, description: 'Reset email sent (if account exists)' })
async forgotPassword(@Body() dto: ForgotPasswordDto): Promise<{ message: string }> {
await this.authService.forgotPassword(dto.email);
return {
message: 'Si un compte existe avec cet email, vous recevrez un lien de réinitialisation.',
};
}
/**
* Reset password using token from email
*/
@Public()
@Post('reset-password')
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: 'Reset password',
description: 'Reset user password using the token received by email.',
})
@ApiResponse({ status: 200, description: 'Password reset successfully' })
@ApiResponse({ status: 400, description: 'Invalid or expired token' })
async resetPassword(@Body() dto: ResetPasswordDto): Promise<{ message: string }> {
await this.authService.resetPassword(dto.token, dto.newPassword);
return { message: 'Mot de passe réinitialisé avec succès.' };
}
/**
* Get current user profile
*

View File

@ -7,6 +7,7 @@ import {
IsEnum,
MaxLength,
Matches,
IsBoolean,
} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
@ -22,12 +23,45 @@ export class LoginDto {
@ApiProperty({
example: 'SecurePassword123!',
description: 'Password (minimum 12 characters)',
description: 'Password',
})
@IsString()
password: string;
@ApiPropertyOptional({
example: true,
description: 'Remember me for extended session',
})
@IsBoolean()
@IsOptional()
rememberMe?: boolean;
}
export class ForgotPasswordDto {
@ApiProperty({
example: 'john.doe@acme.com',
description: 'Email address for password reset',
})
@IsEmail({}, { message: 'Invalid email format' })
email: string;
}
export class ResetPasswordDto {
@ApiProperty({
example: 'abc123token...',
description: 'Password reset token from email',
})
@IsString()
token: string;
@ApiProperty({
example: 'NewSecurePassword123!',
description: 'New password (minimum 12 characters)',
minLength: 12,
})
@IsString()
@MinLength(12, { message: 'Password must be at least 12 characters' })
password: string;
newPassword: string;
}
/**
@ -106,6 +140,19 @@ export class RegisterOrganizationDto {
@Matches(/^[0-9]{9}$/, { message: 'SIREN must be 9 digits' })
siren: string;
@ApiPropertyOptional({
example: '12345678901234',
description: 'French SIRET number (14 digits, optional)',
minLength: 14,
maxLength: 14,
})
@IsString()
@IsOptional()
@MinLength(14, { message: 'SIRET must be exactly 14 digits' })
@MaxLength(14, { message: 'SIRET must be exactly 14 digits' })
@Matches(/^[0-9]{14}$/, { message: 'SIRET must be 14 digits' })
siret?: string;
@ApiPropertyOptional({
example: 'MAEU',
description: 'Standard Carrier Alpha Code (4 uppercase letters, required for carriers only)',

View File

@ -0,0 +1,30 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
Index,
} from 'typeorm';
@Entity('password_reset_tokens')
export class PasswordResetTokenOrmEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ name: 'user_id' })
@Index('IDX_password_reset_tokens_user_id')
userId: string;
@Column({ unique: true, length: 255 })
@Index('IDX_password_reset_tokens_token')
token: string;
@Column({ name: 'expires_at', type: 'timestamp' })
expiresAt: Date;
@Column({ name: 'used_at', type: 'timestamp', nullable: true })
usedAt: Date | null;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
}

View File

@ -0,0 +1,31 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreatePasswordResetTokens1741500000001 implements MigrationInterface {
name = 'CreatePasswordResetTokens1741500000001';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE "password_reset_tokens" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"user_id" uuid NOT NULL,
"token" character varying(255) NOT NULL,
"expires_at" TIMESTAMP NOT NULL,
"used_at" TIMESTAMP,
"created_at" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "PK_password_reset_tokens" PRIMARY KEY ("id"),
CONSTRAINT "UQ_password_reset_tokens_token" UNIQUE ("token")
)
`);
await queryRunner.query(
`CREATE INDEX "IDX_password_reset_tokens_token" ON "password_reset_tokens" ("token")`
);
await queryRunner.query(
`CREATE INDEX "IDX_password_reset_tokens_user_id" ON "password_reset_tokens" ("user_id")`
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "password_reset_tokens"`);
}
}

View File

@ -1,13 +1,9 @@
/**
* Forgot Password Page
*
* Request password reset
*/
'use client';
import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { forgotPassword } from '@/lib/api/auth';
export default function ForgotPasswordPage() {
const [email, setEmail] = useState('');
@ -21,97 +17,173 @@ export default function ForgotPasswordPage() {
setLoading(true);
try {
// TODO: Implement forgotPassword API endpoint
await new Promise(resolve => setTimeout(resolve, 1000));
await forgotPassword(email);
setSuccess(true);
} catch (err: any) {
setError(err.response?.data?.message || 'Failed to send reset email. Please try again.');
setError(err.message || 'Une erreur est survenue. Veuillez réessayer.');
} finally {
setLoading(false);
}
};
if (success) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Check your email
</h2>
</div>
<div className="rounded-md bg-green-50 p-4">
<div className="text-sm text-green-800">
We've sent a password reset link to <strong>{email}</strong>. Please check your inbox
and follow the instructions.
</div>
</div>
<div className="text-center">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
Back to sign in
return (
<div className="min-h-screen flex">
{/* Left Side - Form */}
<div className="w-full lg:w-1/2 flex flex-col justify-center px-8 sm:px-12 lg:px-16 xl:px-24 bg-white">
<div className="max-w-md w-full mx-auto">
{/* Logo */}
<div className="mb-10">
<Link href="/">
<Image
src="/assets/logos/logo-black.svg"
alt="Xpeditis"
width={50}
height={60}
priority
className="h-auto"
/>
</Link>
</div>
{success ? (
<>
<div className="mb-8">
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-6">
<svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
</div>
<h1 className="text-h1 text-brand-navy mb-2">Email envoyé</h1>
<p className="text-body text-neutral-600">
Si un compte est associé à <strong>{email}</strong>, vous recevrez un email avec
les instructions pour réinitialiser votre mot de passe.
</p>
<p className="text-body-sm text-neutral-500 mt-3">
Pensez à vérifier vos spams si vous ne recevez rien d'ici quelques minutes.
</p>
</div>
<Link href="/login" className="btn-primary w-full text-center block text-lg">
Retour à la connexion
</Link>
</>
) : (
<>
{/* Header */}
<div className="mb-8">
<h1 className="text-h1 text-brand-navy mb-2">Mot de passe oublié ?</h1>
<p className="text-body text-neutral-600">
Entrez votre adresse email et nous vous enverrons un lien pour réinitialiser votre mot de passe.
</p>
</div>
{/* Error Message */}
{error && (
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
<svg className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p className="text-body-sm text-red-800">{error}</p>
</div>
)}
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="email" className="label">
Adresse email
</label>
<input
id="email"
type="email"
required
value={email}
onChange={e => setEmail(e.target.value)}
className="input w-full"
placeholder="votre.email@entreprise.com"
autoComplete="email"
disabled={loading}
/>
</div>
<button
type="submit"
disabled={loading}
className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? 'Envoi en cours...' : 'Envoyer le lien de réinitialisation'}
</button>
</form>
<div className="mt-8 text-center">
<Link href="/login" className="text-body-sm link flex items-center justify-center gap-2">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
Retour à la connexion
</Link>
</div>
</>
)}
{/* Footer Links */}
<div className="mt-8 pt-8 border-t border-neutral-200">
<div className="flex flex-wrap justify-center gap-6 text-body-sm text-neutral-500">
<Link href="/contact" className="hover:text-accent transition-colors">
Contactez-nous
</Link>
<Link href="/privacy" className="hover:text-accent transition-colors">
Confidentialité
</Link>
<Link href="/terms" className="hover:text-accent transition-colors">
Conditions
</Link>
</div>
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Reset your password
</h2>
<p className="mt-2 text-center text-sm text-gray-600">
Enter your email address and we'll send you a link to reset your password.
</p>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
{error && (
<div className="rounded-md bg-red-50 p-4">
<div className="text-sm text-red-800">{error}</div>
{/* Right Side - Brand */}
<div className="hidden lg:block lg:w-1/2 relative bg-brand-navy">
<div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-800 opacity-95"></div>
<div className="absolute inset-0 flex flex-col justify-center px-16 xl:px-24 text-white">
<div className="max-w-xl">
<h2 className="text-display-sm mb-6 text-white">Sécurité avant tout</h2>
<p className="text-body-lg text-neutral-200 mb-12">
La protection de votre compte est notre priorité. Réinitialisez votre mot de passe en toute sécurité.
</p>
<div className="space-y-6">
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Lien sécurisé</h3>
<p className="text-body-sm text-neutral-300">Le lien expire après 1 heure pour votre sécurité</p>
</div>
</div>
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Email de confirmation</h3>
<p className="text-body-sm text-neutral-300">Vérifiez votre boîte de réception et vos spams</p>
</div>
</div>
</div>
)}
<div>
<label htmlFor="email-address" className="sr-only">
Email address
</label>
<input
id="email-address"
name="email"
type="email"
autoComplete="email"
required
value={email}
onChange={e => setEmail(e.target.value)}
className="appearance-none rounded-md relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-blue-500 focus:border-blue-500 focus:z-10 sm:text-sm"
placeholder="Email address"
/>
</div>
<div>
<button
type="submit"
disabled={loading}
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed"
>
{loading ? 'Sending...' : 'Send reset link'}
</button>
</div>
<div className="text-center text-sm">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
Back to sign in
</Link>
</div>
</form>
</div>
<div className="absolute bottom-0 right-0 opacity-10">
<svg width="400" height="400" viewBox="0 0 400 400" fill="none">
<circle cx="200" cy="200" r="150" stroke="currentColor" strokeWidth="2" className="text-white" />
<circle cx="200" cy="200" r="100" stroke="currentColor" strokeWidth="2" className="text-white" />
<circle cx="200" cy="200" r="50" stroke="currentColor" strokeWidth="2" className="text-white" />
</svg>
</div>
</div>
</div>
);

View File

@ -129,7 +129,7 @@ function LoginPageContent() {
setIsLoading(true);
try {
await login(email, password, redirectTo);
await login(email, password, redirectTo, rememberMe);
// Navigation is handled by the login function in auth context
} catch (err: any) {
const { message, field } = getErrorMessage(err);
@ -308,9 +308,6 @@ function LoginPageContent() {
{/* Footer Links */}
<div className="mt-8 pt-8 border-t border-neutral-200">
<div className="flex flex-wrap justify-center gap-6 text-body-sm text-neutral-500">
<Link href="/help" className="hover:text-accent transition-colors">
Centre d'aide
</Link>
<Link href="/contact" className="hover:text-accent transition-colors">
Contactez-nous
</Link>

View File

@ -1,12 +1,6 @@
/**
* Register Page - Xpeditis
*
* Modern registration page with split-screen design
*/
'use client';
import { useState, useEffect } from 'react';
import { useState, useEffect, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
@ -14,20 +8,25 @@ import { register } from '@/lib/api';
import { verifyInvitation, type InvitationResponse } from '@/lib/api/invitations';
import type { OrganizationType } from '@/types/api';
export default function RegisterPage() {
function RegisterPageContent() {
const router = useRouter();
const searchParams = useSearchParams();
// Step management
const [step, setStep] = useState<1 | 2>(1);
// Step 1 — Personal info
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
// Organization fields
// Step 2 — Organization
const [organizationName, setOrganizationName] = useState('');
const [organizationType, setOrganizationType] = useState<OrganizationType>('FREIGHT_FORWARDER');
const [siren, setSiren] = useState('');
const [siret, setSiret] = useState('');
const [street, setStreet] = useState('');
const [city, setCity] = useState('');
const [state, setState] = useState('');
@ -37,12 +36,11 @@ export default function RegisterPage() {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
// Invitation-related state
// Invitation state
const [invitationToken, setInvitationToken] = useState<string | null>(null);
const [invitation, setInvitation] = useState<InvitationResponse | null>(null);
const [isVerifyingInvitation, setIsVerifyingInvitation] = useState(false);
// Verify invitation token on mount
useEffect(() => {
const token = searchParams.get('token');
if (token) {
@ -51,13 +49,12 @@ export default function RegisterPage() {
.then(invitationData => {
setInvitation(invitationData);
setInvitationToken(token);
// Pre-fill user information from invitation
setEmail(invitationData.email);
setFirstName(invitationData.firstName);
setLastName(invitationData.lastName);
})
.catch(err => {
setError('Le lien d\'invitation est invalide ou expiré.');
.catch(() => {
setError("Le lien d'invitation est invalide ou expiré.");
})
.finally(() => {
setIsVerifyingInvitation(false);
@ -65,41 +62,58 @@ export default function RegisterPage() {
}
}, [searchParams]);
const handleSubmit = async (e: React.FormEvent) => {
// ---- Step 1 validation ----
const validateStep1 = (): string | null => {
if (!firstName.trim() || firstName.trim().length < 2) return 'Le prénom doit contenir au moins 2 caractères';
if (!lastName.trim() || lastName.trim().length < 2) return 'Le nom doit contenir au moins 2 caractères';
if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return "L'adresse email n'est pas valide";
if (password.length < 12) return 'Le mot de passe doit contenir au moins 12 caractères';
if (password !== confirmPassword) return 'Les mots de passe ne correspondent pas';
return null;
};
const handleStep1 = (e: React.FormEvent) => {
e.preventDefault();
setError('');
// Validate passwords match
if (password !== confirmPassword) {
setError('Les mots de passe ne correspondent pas');
const err = validateStep1();
if (err) {
setError(err);
return;
}
// If invitation — submit directly (no org step)
if (invitationToken) {
handleFinalSubmit();
} else {
setStep(2);
}
};
// Validate password length
if (password.length < 12) {
setError('Le mot de passe doit contenir au moins 12 caractères');
// ---- Step 2 validation ----
const validateStep2 = (): string | null => {
if (!organizationName.trim()) return "Le nom de l'organisation est requis";
if (!/^[0-9]{9}$/.test(siren)) return 'Le numéro SIREN est requis (9 chiffres)';
if (siret && !/^[0-9]{14}$/.test(siret)) return 'Le numéro SIRET doit contenir 14 chiffres';
if (!street.trim() || !city.trim() || !postalCode.trim() || !country.trim()) {
return "Tous les champs d'adresse sont requis";
}
return null;
};
const handleStep2 = (e: React.FormEvent) => {
e.preventDefault();
setError('');
const err = validateStep2();
if (err) {
setError(err);
return;
}
handleFinalSubmit();
};
// Validate organization fields only if NOT using invitation
if (!invitationToken) {
if (!organizationName.trim()) {
setError('Le nom de l\'organisation est requis');
return;
}
if (!siren.trim() || !/^[0-9]{9}$/.test(siren)) {
setError('Le numero SIREN est requis (9 chiffres)');
return;
}
if (!street.trim() || !city.trim() || !postalCode.trim() || !country.trim()) {
setError('Tous les champs d\'adresse sont requis');
return;
}
}
// ---- Final submit ----
const handleFinalSubmit = async () => {
setIsLoading(true);
setError('');
try {
await register({
@ -107,7 +121,6 @@ export default function RegisterPage() {
password,
firstName,
lastName,
// If invitation token exists, use it; otherwise provide organization data
...(invitationToken
? { invitationToken }
: {
@ -115,6 +128,7 @@ export default function RegisterPage() {
name: organizationName,
type: organizationType,
siren,
siret: siret || undefined,
street,
city,
state: state || undefined,
@ -126,18 +140,92 @@ export default function RegisterPage() {
router.push('/dashboard');
} catch (err: any) {
setError(err.message || 'Erreur lors de la création du compte');
// On error at step 2, stay on step 2; at invitation (step 1), stay on step 1
} finally {
setIsLoading(false);
}
};
// ---- Right panel content ----
const rightPanel = (
<div className="hidden lg:block lg:w-1/2 relative bg-brand-navy">
<div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-800 opacity-95"></div>
<div className="absolute inset-0 flex flex-col justify-center px-16 xl:px-24 text-white">
<div className="max-w-xl">
<h2 className="text-display-sm mb-6 text-white">
{invitation ? 'Rejoignez votre équipe' : 'Rejoignez des milliers d\'entreprises'}
</h2>
<p className="text-body-lg text-neutral-200 mb-12">
Simplifiez votre logistique maritime et gagnez du temps sur chaque expédition.
</p>
<div className="space-y-6">
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Essai gratuit de 30 jours</h3>
<p className="text-body-sm text-neutral-300">Testez toutes les fonctionnalités sans engagement</p>
</div>
</div>
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Sécurité maximale</h3>
<p className="text-body-sm text-neutral-300">Vos données sont protégées et chiffrées</p>
</div>
</div>
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Support 24/7</h3>
<p className="text-body-sm text-neutral-300">Notre équipe est pour vous accompagner</p>
</div>
</div>
</div>
<div className="grid grid-cols-3 gap-8 mt-12 pt-12 border-t border-neutral-700">
<div>
<div className="text-display-sm text-brand-turquoise">2k+</div>
<div className="text-body-sm text-neutral-300 mt-1">Entreprises</div>
</div>
<div>
<div className="text-display-sm text-brand-turquoise">150+</div>
<div className="text-body-sm text-neutral-300 mt-1">Pays couverts</div>
</div>
<div>
<div className="text-display-sm text-brand-turquoise">24/7</div>
<div className="text-body-sm text-neutral-300 mt-1">Support</div>
</div>
</div>
</div>
</div>
<div className="absolute bottom-0 right-0 opacity-10">
<svg width="400" height="400" viewBox="0 0 400 400" fill="none">
<circle cx="200" cy="200" r="150" stroke="currentColor" strokeWidth="2" className="text-white" />
<circle cx="200" cy="200" r="100" stroke="currentColor" strokeWidth="2" className="text-white" />
<circle cx="200" cy="200" r="50" stroke="currentColor" strokeWidth="2" className="text-white" />
</svg>
</div>
</div>
);
return (
<div className="min-h-screen flex">
{/* Left Side - Form */}
<div className="w-full lg:w-1/2 flex flex-col justify-center px-8 sm:px-12 lg:px-16 xl:px-24 bg-white">
<div className="max-w-md w-full mx-auto">
{/* Logo */}
<div className="mb-10">
<div className="mb-8">
<Link href="/">
<Image
src="/assets/logos/logo-black.svg"
@ -150,142 +238,179 @@ export default function RegisterPage() {
</Link>
</div>
{/* Progress indicator (only for self-registration, 2 steps) */}
{!invitation && (
<div className="mb-8">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-colors ${
step >= 1 ? 'bg-brand-navy text-white' : 'bg-neutral-100 text-neutral-400'
}`}>
{step > 1 ? (
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
</svg>
) : '1'}
</div>
<span className={`text-body-sm font-medium ${step >= 1 ? 'text-brand-navy' : 'text-neutral-400'}`}>
Votre compte
</span>
</div>
<div className={`flex-1 h-0.5 transition-colors ${step >= 2 ? 'bg-brand-navy' : 'bg-neutral-200'}`} />
<div className="flex items-center gap-2">
<div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-colors ${
step >= 2 ? 'bg-brand-navy text-white' : 'bg-neutral-100 text-neutral-400'
}`}>
2
</div>
<span className={`text-body-sm font-medium ${step >= 2 ? 'text-brand-navy' : 'text-neutral-400'}`}>
Votre organisation
</span>
</div>
</div>
</div>
)}
{/* Header */}
<div className="mb-8">
<h1 className="text-h1 text-brand-navy mb-2">
{invitation ? 'Accepter l\'invitation' : 'Créer un compte'}
</h1>
<p className="text-body text-neutral-600">
{invitation
? `Vous avez été invité à rejoindre une organisation`
: 'Commencez votre essai gratuit dès aujourd\'hui'}
</p>
<div className="mb-6">
{isVerifyingInvitation ? (
<p className="text-body text-neutral-600">Vérification de l'invitation...</p>
) : invitation ? (
<>
<h1 className="text-h1 text-brand-navy mb-2">Accepter l'invitation</h1>
<div className="p-3 bg-green-50 border border-green-200 rounded-lg">
<p className="text-body-sm text-green-800">
Invitation valide créez votre mot de passe pour rejoindre l'organisation.
</p>
</div>
</>
) : step === 1 ? (
<>
<h1 className="text-h1 text-brand-navy mb-2">Créer un compte</h1>
<p className="text-body text-neutral-600">Commencez votre essai gratuit dès aujourd'hui</p>
</>
) : (
<>
<h1 className="text-h1 text-brand-navy mb-2">Votre organisation</h1>
<p className="text-body text-neutral-600">Renseignez les informations de votre entreprise</p>
</>
)}
</div>
{/* Verifying Invitation Loading */}
{isVerifyingInvitation && (
<div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
<p className="text-body-sm text-blue-800">Vérification de l'invitation...</p>
</div>
)}
{/* Success Message for Invitation */}
{invitation && !error && (
<div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg">
<p className="text-body-sm text-green-800">
Invitation valide ! Créez votre mot de passe pour rejoindre l'organisation.
</p>
</div>
)}
{/* Error Message */}
{error && (
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
<svg className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p className="text-body-sm text-red-800">{error}</p>
</div>
)}
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-5">
{/* First Name & Last Name */}
<div className="grid grid-cols-2 gap-4">
{/* ---- STEP 1: Personal info ---- */}
{(step === 1 || invitation) && !isVerifyingInvitation && (
<form onSubmit={handleStep1} className="space-y-5">
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="firstName" className="label">Prénom</label>
<input
id="firstName"
type="text"
required
value={firstName}
onChange={e => setFirstName(e.target.value)}
className="input w-full"
placeholder="Jean"
disabled={isLoading || !!invitation}
/>
</div>
<div>
<label htmlFor="lastName" className="label">Nom</label>
<input
id="lastName"
type="text"
required
value={lastName}
onChange={e => setLastName(e.target.value)}
className="input w-full"
placeholder="Dupont"
disabled={isLoading || !!invitation}
/>
</div>
</div>
<div>
<label htmlFor="firstName" className="label">
Prénom
</label>
<label htmlFor="email" className="label">Adresse email</label>
<input
id="firstName"
type="text"
id="email"
type="email"
required
value={firstName}
onChange={e => setFirstName(e.target.value)}
value={email}
onChange={e => setEmail(e.target.value)}
className="input w-full"
placeholder="Jean"
placeholder="jean.dupont@entreprise.com"
autoComplete="email"
disabled={isLoading || !!invitation}
/>
</div>
<div>
<label htmlFor="lastName" className="label">
Nom
</label>
<label htmlFor="password" className="label">Mot de passe</label>
<input
id="lastName"
type="text"
id="password"
type="password"
required
value={lastName}
onChange={e => setLastName(e.target.value)}
value={password}
onChange={e => setPassword(e.target.value)}
className="input w-full"
placeholder="Dupont"
disabled={isLoading || !!invitation}
placeholder="••••••••••••"
autoComplete="new-password"
disabled={isLoading}
/>
<p className="mt-1.5 text-body-xs text-neutral-500">Au moins 12 caractères</p>
</div>
<div>
<label htmlFor="confirmPassword" className="label">Confirmer le mot de passe</label>
<input
id="confirmPassword"
type="password"
required
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
className="input w-full"
placeholder="••••••••••••"
autoComplete="new-password"
disabled={isLoading}
/>
</div>
</div>
{/* Email */}
<div>
<label htmlFor="email" className="label">
Adresse email
</label>
<input
id="email"
type="email"
required
value={email}
onChange={e => setEmail(e.target.value)}
className="input w-full"
placeholder="jean.dupont@entreprise.com"
autoComplete="email"
disabled={isLoading || !!invitation}
/>
</div>
{/* Password */}
<div>
<label htmlFor="password" className="label">
Mot de passe
</label>
<input
id="password"
type="password"
required
value={password}
onChange={e => setPassword(e.target.value)}
className="input w-full"
placeholder="••••••••••••"
autoComplete="new-password"
<button
type="submit"
disabled={isLoading}
/>
<p className="mt-1.5 text-body-xs text-neutral-500">Au moins 12 caractères</p>
</div>
className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed mt-2"
>
{isLoading
? 'Création du compte...'
: invitation
? 'Créer mon compte'
: 'Continuer'}
</button>
{/* Confirm Password */}
<div>
<label htmlFor="confirmPassword" className="label">
Confirmer le mot de passe
</label>
<input
id="confirmPassword"
type="password"
required
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
className="input w-full"
placeholder="••••••••••••"
autoComplete="new-password"
disabled={isLoading}
/>
</div>
<p className="text-body-xs text-center text-neutral-500">
En créant un compte, vous acceptez nos{' '}
<Link href="/terms" className="link">Conditions d'utilisation</Link>{' '}
et notre{' '}
<Link href="/privacy" className="link">Politique de confidentialité</Link>
</p>
</form>
)}
{/* Organization Section - Only show if NOT using invitation */}
{!invitation && (
<div className="pt-4 border-t border-neutral-200">
<h3 className="text-h5 text-brand-navy mb-4">Informations de votre organisation</h3>
{/* Organization Name */}
<div className="mb-4">
<label htmlFor="organizationName" className="label">
Nom de l'organisation
</label>
{/* ---- STEP 2: Organization info ---- */}
{step === 2 && !invitation && (
<form onSubmit={handleStep2} className="space-y-5">
<div>
<label htmlFor="organizationName" className="label">Nom de l'organisation *</label>
<input
id="organizationName"
type="text"
@ -298,11 +423,8 @@ export default function RegisterPage() {
/>
</div>
{/* Organization Type */}
<div className="mb-4">
<label htmlFor="organizationType" className="label">
Type d'organisation
</label>
<div>
<label htmlFor="organizationType" className="label">Type d'organisation *</label>
<select
id="organizationType"
value={organizationType}
@ -316,30 +438,40 @@ export default function RegisterPage() {
</select>
</div>
{/* SIREN */}
<div className="mb-4">
<label htmlFor="siren" className="label">
Numero SIREN *
</label>
<input
id="siren"
type="text"
required
value={siren}
onChange={e => setSiren(e.target.value.replace(/\D/g, ''))}
className="input w-full"
placeholder="123456789"
maxLength={9}
disabled={isLoading}
/>
<p className="mt-1.5 text-body-xs text-neutral-500">9 chiffres, obligatoire pour toute organisation</p>
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="siren" className="label">SIREN *</label>
<input
id="siren"
type="text"
required
value={siren}
onChange={e => setSiren(e.target.value.replace(/\D/g, '').slice(0, 9))}
className="input w-full"
placeholder="123456789"
maxLength={9}
disabled={isLoading}
/>
<p className="mt-1 text-body-xs text-neutral-500">9 chiffres</p>
</div>
<div>
<label htmlFor="siret" className="label">SIRET <span className="text-neutral-400 font-normal">(optionnel)</span></label>
<input
id="siret"
type="text"
value={siret}
onChange={e => setSiret(e.target.value.replace(/\D/g, '').slice(0, 14))}
className="input w-full"
placeholder="12345678900014"
maxLength={14}
disabled={isLoading}
/>
<p className="mt-1 text-body-xs text-neutral-500">14 chiffres</p>
</div>
</div>
{/* Street Address */}
<div className="mb-4">
<label htmlFor="street" className="label">
Adresse
</label>
<div>
<label htmlFor="street" className="label">Adresse *</label>
<input
id="street"
type="text"
@ -352,12 +484,9 @@ export default function RegisterPage() {
/>
</div>
{/* City & Postal Code */}
<div className="grid grid-cols-2 gap-4 mb-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="city" className="label">
Ville
</label>
<label htmlFor="city" className="label">Ville *</label>
<input
id="city"
type="text"
@ -370,9 +499,7 @@ export default function RegisterPage() {
/>
</div>
<div>
<label htmlFor="postalCode" className="label">
Code postal
</label>
<label htmlFor="postalCode" className="label">Code postal *</label>
<input
id="postalCode"
type="text"
@ -386,11 +513,10 @@ export default function RegisterPage() {
</div>
</div>
{/* State & Country */}
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="state" className="label">
Région (optionnel)
Région <span className="text-neutral-400 font-normal">(optionnel)</span>
</label>
<input
id="state"
@ -403,209 +529,77 @@ export default function RegisterPage() {
/>
</div>
<div>
<label htmlFor="country" className="label">
Pays (code ISO)
</label>
<label htmlFor="country" className="label">Pays *</label>
<input
id="country"
type="text"
required
value={country}
onChange={e => setCountry(e.target.value)}
onChange={e => setCountry(e.target.value.toUpperCase().slice(0, 2))}
className="input w-full"
placeholder="FR"
maxLength={2}
disabled={isLoading}
/>
<p className="mt-1 text-body-xs text-neutral-500">Code ISO 2 lettres</p>
</div>
</div>
<div className="flex gap-3 pt-2">
<button
type="button"
onClick={() => { setStep(1); setError(''); }}
disabled={isLoading}
className="btn-secondary flex-1 text-lg disabled:opacity-50"
>
Retour
</button>
<button
type="submit"
disabled={isLoading}
className="btn-primary flex-2 flex-1 text-lg disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Création...' : 'Créer mon compte'}
</button>
</div>
)}
{/* Submit Button */}
<button
type="submit"
disabled={isLoading}
className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed mt-6"
>
{isLoading ? 'Création du compte...' : 'Créer mon compte'}
</button>
{/* Terms */}
<p className="text-body-xs text-center text-neutral-500 mt-4">
En créant un compte, vous acceptez nos{' '}
<Link href="/terms" className="link">
Conditions d'utilisation
</Link>{' '}
et notre{' '}
<Link href="/privacy" className="link">
Politique de confidentialité
</Link>
</p>
</form>
<p className="text-body-xs text-center text-neutral-500">
En créant un compte, vous acceptez nos{' '}
<Link href="/terms" className="link">Conditions d'utilisation</Link>{' '}
et notre{' '}
<Link href="/privacy" className="link">Politique de confidentialité</Link>
</p>
</form>
)}
{/* Sign In Link */}
<div className="mt-8 text-center">
<p className="text-body text-neutral-600">
Vous avez déjà un compte ?{' '}
<Link href="/login" className="link font-semibold">
Se connecter
</Link>
<Link href="/login" className="link font-semibold">Se connecter</Link>
</p>
</div>
{/* Footer Links */}
<div className="mt-8 pt-8 border-t border-neutral-200">
<div className="mt-6 pt-6 border-t border-neutral-200">
<div className="flex flex-wrap justify-center gap-6 text-body-sm text-neutral-500">
<Link href="/help" className="hover:text-accent transition-colors">
Centre d'aide
</Link>
<Link href="/contact" className="hover:text-accent transition-colors">
Contactez-nous
</Link>
<Link href="/privacy" className="hover:text-accent transition-colors">
Confidentialité
</Link>
<Link href="/terms" className="hover:text-accent transition-colors">
Conditions
</Link>
<Link href="/contact" className="hover:text-accent transition-colors">Contactez-nous</Link>
<Link href="/privacy" className="hover:text-accent transition-colors">Confidentialité</Link>
<Link href="/terms" className="hover:text-accent transition-colors">Conditions</Link>
</div>
</div>
</div>
</div>
{/* Right Side - Brand Features (same as login) */}
<div className="hidden lg:block lg:w-1/2 relative bg-brand-navy">
<div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-800 opacity-95"></div>
<div className="absolute inset-0 flex flex-col justify-center px-16 xl:px-24 text-white">
<div className="max-w-xl">
<h2 className="text-display-sm mb-6 text-white">
Rejoignez des milliers d'entreprises
</h2>
<p className="text-body-lg text-neutral-200 mb-12">
Simplifiez votre logistique maritime et gagnez du temps sur chaque expédition.
</p>
<div className="space-y-6">
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg
className="w-6 h-6 text-white"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M5 13l4 4L19 7"
/>
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Essai gratuit de 30 jours</h3>
<p className="text-body-sm text-neutral-300">
Testez toutes les fonctionnalités sans engagement
</p>
</div>
</div>
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg
className="w-6 h-6 text-white"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
/>
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Sécurité maximale</h3>
<p className="text-body-sm text-neutral-300">
Vos données sont protégées et chiffrées
</p>
</div>
</div>
<div className="flex items-start">
<div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
<svg
className="w-6 h-6 text-white"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z"
/>
</svg>
</div>
<div className="ml-4">
<h3 className="text-h5 mb-1 text-white">Support 24/7</h3>
<p className="text-body-sm text-neutral-300">
Notre équipe est pour vous accompagner
</p>
</div>
</div>
</div>
<div className="grid grid-cols-3 gap-8 mt-12 pt-12 border-t border-neutral-700">
<div>
<div className="text-display-sm text-brand-turquoise">2k+</div>
<div className="text-body-sm text-neutral-300 mt-1">Entreprises</div>
</div>
<div>
<div className="text-display-sm text-brand-turquoise">150+</div>
<div className="text-body-sm text-neutral-300 mt-1">Pays couverts</div>
</div>
<div>
<div className="text-display-sm text-brand-turquoise">24/7</div>
<div className="text-body-sm text-neutral-300 mt-1">Support</div>
</div>
</div>
</div>
</div>
<div className="absolute bottom-0 right-0 opacity-10">
<svg width="400" height="400" viewBox="0 0 400 400" fill="none">
<circle
cx="200"
cy="200"
r="150"
stroke="currentColor"
strokeWidth="2"
className="text-white"
/>
<circle
cx="200"
cy="200"
r="100"
stroke="currentColor"
strokeWidth="2"
className="text-white"
/>
<circle
cx="200"
cy="200"
r="50"
stroke="currentColor"
strokeWidth="2"
className="text-white"
/>
</svg>
</div>
</div>
{rightPanel}
</div>
);
}
export default function RegisterPage() {
return (
<Suspense>
<RegisterPageContent />
</Suspense>
);
}

View File

@ -1,16 +1,12 @@
/**
* Reset Password Page
*
* Reset password with token from email
*/
'use client';
import { useState, useEffect } from 'react';
import { useState, useEffect, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { resetPassword } from '@/lib/api/auth';
export default function ResetPasswordPage() {
function ResetPasswordContent() {
const searchParams = useSearchParams();
const router = useRouter();
const [token, setToken] = useState('');
@ -19,13 +15,14 @@ export default function ResetPasswordPage() {
const [success, setSuccess] = useState(false);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [tokenError, setTokenError] = useState(false);
useEffect(() => {
const tokenFromUrl = searchParams.get('token');
if (tokenFromUrl) {
setToken(tokenFromUrl);
} else {
setError('Invalid reset link. Please request a new password reset.');
setTokenError(true);
}
}, [searchParams]);
@ -33,139 +30,218 @@ export default function ResetPasswordPage() {
e.preventDefault();
setError('');
// Validate passwords match
if (password !== confirmPassword) {
setError('Passwords do not match');
setError('Les mots de passe ne correspondent pas');
return;
}
// Validate password length
if (password.length < 12) {
setError('Password must be at least 12 characters long');
return;
}
if (!token) {
setError('Invalid reset token');
setError('Le mot de passe doit contenir au moins 12 caractères');
return;
}
setLoading(true);
try {
// TODO: Implement resetPassword API endpoint
await new Promise(resolve => setTimeout(resolve, 1000));
await resetPassword(token, password);
setSuccess(true);
setTimeout(() => {
router.push('/login');
}, 3000);
setTimeout(() => router.push('/login'), 3000);
} catch (err: any) {
setError(
err.response?.data?.message || 'Failed to reset password. The link may have expired.'
);
setError(err.message || 'Le lien de réinitialisation est invalide ou expiré.');
} finally {
setLoading(false);
}
};
if (success) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Password reset successful
</h2>
</div>
<div className="rounded-md bg-green-50 p-4">
<div className="text-sm text-green-800">
Your password has been reset successfully. You will be redirected to the login page in
a few seconds...
</div>
</div>
<div className="text-center">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
Go to login now
return (
<div className="min-h-screen flex">
{/* Left Side - Form */}
<div className="w-full lg:w-1/2 flex flex-col justify-center px-8 sm:px-12 lg:px-16 xl:px-24 bg-white">
<div className="max-w-md w-full mx-auto">
{/* Logo */}
<div className="mb-10">
<Link href="/">
<Image
src="/assets/logos/logo-black.svg"
alt="Xpeditis"
width={50}
height={60}
priority
className="h-auto"
/>
</Link>
</div>
{tokenError ? (
<>
<div className="mb-8">
<div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-6">
<svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<h1 className="text-h1 text-brand-navy mb-2">Lien invalide</h1>
<p className="text-body text-neutral-600">
Ce lien de réinitialisation est invalide. Veuillez faire une nouvelle demande.
</p>
</div>
<Link href="/forgot-password" className="btn-primary w-full text-center block text-lg">
Demander un nouveau lien
</Link>
</>
) : success ? (
<>
<div className="mb-8">
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-6">
<svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
<h1 className="text-h1 text-brand-navy mb-2">Mot de passe réinitialisé !</h1>
<p className="text-body text-neutral-600">
Votre mot de passe a é modifié avec succès. Vous allez être redirigé vers la page de connexion...
</p>
</div>
<Link href="/login" className="btn-primary w-full text-center block text-lg">
Se connecter maintenant
</Link>
</>
) : (
<>
{/* Header */}
<div className="mb-8">
<h1 className="text-h1 text-brand-navy mb-2">Nouveau mot de passe</h1>
<p className="text-body text-neutral-600">
Choisissez un nouveau mot de passe sécurisé pour votre compte.
</p>
</div>
{/* Error Message */}
{error && (
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
<svg className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p className="text-body-sm text-red-800">{error}</p>
</div>
)}
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="password" className="label">
Nouveau mot de passe
</label>
<input
id="password"
type="password"
required
value={password}
onChange={e => setPassword(e.target.value)}
className="input w-full"
placeholder="••••••••••••"
autoComplete="new-password"
disabled={loading}
/>
<p className="mt-1.5 text-body-xs text-neutral-500">Au moins 12 caractères</p>
</div>
<div>
<label htmlFor="confirmPassword" className="label">
Confirmer le mot de passe
</label>
<input
id="confirmPassword"
type="password"
required
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
className="input w-full"
placeholder="••••••••••••"
autoComplete="new-password"
disabled={loading}
/>
</div>
<button
type="submit"
disabled={loading}
className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? 'Réinitialisation...' : 'Réinitialiser le mot de passe'}
</button>
</form>
<div className="mt-8 text-center">
<Link href="/login" className="text-body-sm link flex items-center justify-center gap-2">
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
Retour à la connexion
</Link>
</div>
</>
)}
{/* Footer Links */}
<div className="mt-8 pt-8 border-t border-neutral-200">
<div className="flex flex-wrap justify-center gap-6 text-body-sm text-neutral-500">
<Link href="/contact" className="hover:text-accent transition-colors">
Contactez-nous
</Link>
<Link href="/privacy" className="hover:text-accent transition-colors">
Confidentialité
</Link>
<Link href="/terms" className="hover:text-accent transition-colors">
Conditions
</Link>
</div>
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Set new password
</h2>
<p className="mt-2 text-center text-sm text-gray-600">Please enter your new password.</p>
{/* Right Side - Brand */}
<div className="hidden lg:block lg:w-1/2 relative bg-brand-navy">
<div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-800 opacity-95"></div>
<div className="absolute inset-0 flex flex-col justify-center px-16 xl:px-24 text-white">
<div className="max-w-xl">
<h2 className="text-display-sm mb-6 text-white">Votre sécurité, notre priorité</h2>
<p className="text-body-lg text-neutral-200 mb-12">
Choisissez un mot de passe fort pour protéger votre compte et vos données.
</p>
<div className="space-y-4">
{[
'Au moins 12 caractères',
'Mélangez lettres, chiffres et symboles',
'Évitez les mots du dictionnaire',
'N\'utilisez pas le même mot de passe ailleurs',
].map((tip) => (
<div key={tip} className="flex items-center gap-3">
<svg className="w-5 h-5 text-brand-turquoise flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
<p className="text-body-sm text-neutral-300">{tip}</p>
</div>
))}
</div>
</div>
</div>
<div className="absolute bottom-0 right-0 opacity-10">
<svg width="400" height="400" viewBox="0 0 400 400" fill="none">
<circle cx="200" cy="200" r="150" stroke="currentColor" strokeWidth="2" className="text-white" />
<circle cx="200" cy="200" r="100" stroke="currentColor" strokeWidth="2" className="text-white" />
<circle cx="200" cy="200" r="50" stroke="currentColor" strokeWidth="2" className="text-white" />
</svg>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
{error && (
<div className="rounded-md bg-red-50 p-4">
<div className="text-sm text-red-800">{error}</div>
</div>
)}
<div className="space-y-4">
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
New Password
</label>
<input
id="password"
name="password"
type="password"
autoComplete="new-password"
required
value={password}
onChange={e => setPassword(e.target.value)}
className="mt-1 appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
/>
<p className="mt-1 text-xs text-gray-500">Must be at least 12 characters long</p>
</div>
<div>
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">
Confirm New Password
</label>
<input
id="confirmPassword"
name="confirmPassword"
type="password"
autoComplete="new-password"
required
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
className="mt-1 appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
/>
</div>
</div>
<div>
<button
type="submit"
disabled={loading || !token}
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed"
>
{loading ? 'Resetting password...' : 'Reset password'}
</button>
</div>
<div className="text-center text-sm">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
Back to sign in
</Link>
</div>
</form>
</div>
</div>
);
}
export default function ResetPasswordPage() {
return (
<Suspense>
<ResetPasswordContent />
</Suspense>
);
}

View File

@ -31,11 +31,12 @@ export async function register(data: RegisterRequest): Promise<AuthResponse> {
* User login
* POST /api/v1/auth/login
*/
export async function login(data: LoginRequest): Promise<AuthResponse> {
const response = await post<AuthResponse>('/api/v1/auth/login', data, false);
export async function login(data: LoginRequest & { rememberMe?: boolean }): Promise<AuthResponse> {
const { rememberMe, ...loginData } = data;
const response = await post<AuthResponse>('/api/v1/auth/login', loginData, false);
// Store tokens
setAuthTokens(response.accessToken, response.refreshToken);
// Store tokens — localStorage if rememberMe, sessionStorage otherwise
setAuthTokens(response.accessToken, response.refreshToken, rememberMe ?? false);
return response;
}
@ -69,3 +70,19 @@ export async function logout(): Promise<SuccessResponse> {
export async function getCurrentUser(): Promise<UserPayload> {
return get<UserPayload>('/api/v1/auth/me');
}
/**
* Forgot password request reset email
* POST /api/v1/auth/forgot-password
*/
export async function forgotPassword(email: string): Promise<{ message: string }> {
return post<{ message: string }>('/api/v1/auth/forgot-password', { email }, false);
}
/**
* Reset password with token from email
* POST /api/v1/auth/reset-password
*/
export async function resetPassword(token: string, newPassword: string): Promise<{ message: string }> {
return post<{ message: string }>('/api/v1/auth/reset-password', { token, newPassword }, false);
}

View File

@ -11,40 +11,46 @@ let isRefreshing = false;
let refreshSubscribers: Array<(token: string) => void> = [];
/**
* Get authentication token from localStorage
* Get authentication token checks localStorage first (remember me), then sessionStorage
*/
export function getAuthToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('access_token');
return localStorage.getItem('access_token') || sessionStorage.getItem('access_token');
}
/**
* Get refresh token from localStorage
* Get refresh token checks localStorage first (remember me), then sessionStorage
*/
export function getRefreshToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('refresh_token');
return localStorage.getItem('refresh_token') || sessionStorage.getItem('refresh_token');
}
/**
* Set authentication tokens
* Set authentication tokens.
* rememberMe=true localStorage (persists across browser sessions)
* rememberMe=false sessionStorage (cleared when browser closes)
*/
export function setAuthTokens(accessToken: string, refreshToken: string): void {
export function setAuthTokens(accessToken: string, refreshToken: string, rememberMe = false): void {
if (typeof window === 'undefined') return;
localStorage.setItem('access_token', accessToken);
localStorage.setItem('refresh_token', refreshToken);
const storage = rememberMe ? localStorage : sessionStorage;
storage.setItem('access_token', accessToken);
storage.setItem('refresh_token', refreshToken);
// Sync to cookie so Next.js middleware can read it for route protection
document.cookie = `accessToken=${accessToken}; path=/; SameSite=Lax`;
}
/**
* Clear authentication tokens
* Clear authentication tokens from both storages
*/
export function clearAuthTokens(): void {
if (typeof window === 'undefined') return;
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
localStorage.removeItem('user');
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('refresh_token');
sessionStorage.removeItem('user');
// Expire the middleware cookie
document.cookie = 'accessToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax';
}
@ -95,9 +101,10 @@ async function refreshAccessToken(): Promise<string> {
const data = await response.json();
const newAccessToken = data.accessToken;
// Update access token in localStorage and cookie (keep same refresh token)
// Update access token in the same storage that holds the refresh token
if (typeof window !== 'undefined') {
localStorage.setItem('access_token', newAccessToken);
const storage = localStorage.getItem('refresh_token') ? localStorage : sessionStorage;
storage.setItem('access_token', newAccessToken);
document.cookie = `accessToken=${newAccessToken}; path=/; SameSite=Lax`;
}

View File

@ -24,8 +24,8 @@ export {
ApiError,
} from './client';
// Authentication (5 endpoints)
export { register, login, refreshToken, logout, getCurrentUser } from './auth';
// Authentication (7 endpoints)
export { register, login, refreshToken, logout, getCurrentUser, forgotPassword, resetPassword } from './auth';
// Rates (4 endpoints)
export { searchRates, searchCsvRates, getAvailableCompanies, getFilterOptions } from './rates';

View File

@ -20,7 +20,7 @@ import type { UserPayload } from '@/types/api';
interface AuthContextType {
user: UserPayload | null;
loading: boolean;
login: (email: string, password: string, redirectTo?: string) => Promise<void>;
login: (email: string, password: string, redirectTo?: string, rememberMe?: boolean) => Promise<void>;
register: (data: {
email: string;
password: string;
@ -106,15 +106,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
return () => clearInterval(tokenCheckInterval);
}, []);
const login = async (email: string, password: string, redirectTo = '/dashboard') => {
const login = async (email: string, password: string, redirectTo = '/dashboard', rememberMe = false) => {
try {
await apiLogin({ email, password });
await apiLogin({ email, password, rememberMe });
// Fetch complete user profile after login
const currentUser = await getCurrentUser();
setUser(currentUser);
// Store user in localStorage
// Store user in the same storage as the tokens
if (typeof window !== 'undefined') {
localStorage.setItem('user', JSON.stringify(currentUser));
const storage = rememberMe ? localStorage : sessionStorage;
storage.setItem('user', JSON.stringify(currentUser));
}
router.push(redirectTo);
} catch (error) {

View File

@ -12,6 +12,7 @@ export interface RegisterOrganizationData {
name: string;
type: OrganizationType;
siren: string;
siret?: string;
street: string;
city: string;
state?: string;
@ -25,7 +26,8 @@ export interface RegisterRequest {
password: string;
firstName: string;
lastName: string;
organizationId?: string; // For invited users
invitationToken?: string; // For invited users (token-based)
organizationId?: string; // For invited users (ID-based)
organization?: RegisterOrganizationData; // For new users
}