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

View File

@ -5,10 +5,14 @@ import {
Logger, Logger,
Inject, Inject,
BadRequestException, BadRequestException,
NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import * as argon2 from 'argon2'; 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 { UserRepository, USER_REPOSITORY } from '@domain/ports/out/user.repository';
import { User, UserRole } from '@domain/entities/user.entity'; import { User, UserRole } from '@domain/entities/user.entity';
import { import {
@ -16,9 +20,11 @@ import {
ORGANIZATION_REPOSITORY, ORGANIZATION_REPOSITORY,
} from '@domain/ports/out/organization.repository'; } from '@domain/ports/out/organization.repository';
import { Organization } from '@domain/entities/organization.entity'; import { Organization } from '@domain/entities/organization.entity';
import { EmailPort, EMAIL_PORT } from '@domain/ports/out/email.port';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import { RegisterOrganizationDto } from '../dto/auth-login.dto'; import { RegisterOrganizationDto } from '../dto/auth-login.dto';
import { SubscriptionService } from '../services/subscription.service'; import { SubscriptionService } from '../services/subscription.service';
import { PasswordResetTokenOrmEntity } from '../../infrastructure/persistence/typeorm/entities/password-reset-token.orm-entity';
export interface JwtPayload { export interface JwtPayload {
sub: string; // user ID sub: string; // user ID
@ -39,6 +45,10 @@ export class AuthService {
private readonly userRepository: UserRepository, private readonly userRepository: UserRepository,
@Inject(ORGANIZATION_REPOSITORY) @Inject(ORGANIZATION_REPOSITORY)
private readonly organizationRepository: OrganizationRepository, private readonly organizationRepository: OrganizationRepository,
@Inject(EMAIL_PORT)
private readonly emailService: EmailPort,
@InjectRepository(PasswordResetTokenOrmEntity)
private readonly passwordResetTokenRepository: Repository<PasswordResetTokenOrmEntity>,
private readonly jwtService: JwtService, private readonly jwtService: JwtService,
private readonly configService: ConfigService, private readonly configService: ConfigService,
private readonly subscriptionService: SubscriptionService 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 * Validate user from JWT payload
*/ */
@ -336,6 +425,7 @@ export class AuthService {
type: organizationData.type, type: organizationData.type,
scac: organizationData.scac, scac: organizationData.scac,
siren: organizationData.siren, siren: organizationData.siren,
siret: organizationData.siret,
address: { address: {
street: organizationData.street, street: organizationData.street,
city: organizationData.city, city: organizationData.city,

View File

@ -11,7 +11,14 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'; import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { AuthService } from '../auth/auth.service'; 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 { Public } from '../decorators/public.decorator';
import { CurrentUser, UserPayload } from '../decorators/current-user.decorator'; import { CurrentUser, UserPayload } from '../decorators/current-user.decorator';
import { JwtAuthGuard } from '../guards/jwt-auth.guard'; import { JwtAuthGuard } from '../guards/jwt-auth.guard';
@ -209,6 +216,41 @@ export class AuthController {
return { message: 'Logout successful' }; 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 * Get current user profile
* *

View File

@ -7,6 +7,7 @@ import {
IsEnum, IsEnum,
MaxLength, MaxLength,
Matches, Matches,
IsBoolean,
} from 'class-validator'; } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
@ -22,12 +23,45 @@ export class LoginDto {
@ApiProperty({ @ApiProperty({
example: 'SecurePassword123!', 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, minLength: 12,
}) })
@IsString() @IsString()
@MinLength(12, { message: 'Password must be at least 12 characters' }) @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' }) @Matches(/^[0-9]{9}$/, { message: 'SIREN must be 9 digits' })
siren: string; 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({ @ApiPropertyOptional({
example: 'MAEU', example: 'MAEU',
description: 'Standard Carrier Alpha Code (4 uppercase letters, required for carriers only)', 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'; 'use client';
import { useState } from 'react'; import { useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import Image from 'next/image';
import { forgotPassword } from '@/lib/api/auth';
export default function ForgotPasswordPage() { export default function ForgotPasswordPage() {
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
@ -21,97 +17,173 @@ export default function ForgotPasswordPage() {
setLoading(true); setLoading(true);
try { try {
// TODO: Implement forgotPassword API endpoint await forgotPassword(email);
await new Promise(resolve => setTimeout(resolve, 1000));
setSuccess(true); setSuccess(true);
} catch (err: any) { } 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 { } finally {
setLoading(false); setLoading(false);
} }
}; };
if (success) {
return ( 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="min-h-screen flex">
<div className="max-w-md w-full space-y-8"> {/* Left Side - Form */}
<div> <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">
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1> <div className="max-w-md w-full mx-auto">
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> {/* Logo */}
Check your email <div className="mb-10">
</h2> <Link href="/">
</div> <Image
src="/assets/logos/logo-black.svg"
<div className="rounded-md bg-green-50 p-4"> alt="Xpeditis"
<div className="text-sm text-green-800"> width={50}
We've sent a password reset link to <strong>{email}</strong>. Please check your inbox height={60}
and follow the instructions. priority
</div> className="h-auto"
</div> />
<div className="text-center">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
Back to sign in
</Link> </Link>
</div> </div>
</div>
</div>
);
}
return ( {success ? (
<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 className="mb-8">
<div> <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-6">
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1> <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> <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" />
Reset your password </svg>
</h2> </div>
<p className="mt-2 text-center text-sm text-gray-600"> <h1 className="text-h1 text-brand-navy mb-2">Email envoyé</h1>
Enter your email address and we'll send you a link to reset your password. <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> </p>
</div> </div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}> {/* Error Message */}
{error && ( {error && (
<div className="rounded-md bg-red-50 p-4"> <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
<div className="text-sm text-red-800">{error}</div> <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> </div>
)} )}
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-6">
<div> <div>
<label htmlFor="email-address" className="sr-only"> <label htmlFor="email" className="label">
Email address Adresse email
</label> </label>
<input <input
id="email-address" id="email"
name="email"
type="email" type="email"
autoComplete="email"
required required
value={email} value={email}
onChange={e => setEmail(e.target.value)} 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" className="input w-full"
placeholder="Email address" placeholder="votre.email@entreprise.com"
autoComplete="email"
disabled={loading}
/> />
</div> </div>
<div>
<button <button
type="submit" type="submit"
disabled={loading} 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" className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed"
> >
{loading ? 'Sending...' : 'Send reset link'} {loading ? 'Envoi en cours...' : 'Envoyer le lien de réinitialisation'}
</button> </button>
</div> </form>
<div className="text-center text-sm"> <div className="mt-8 text-center">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500"> <Link href="/login" className="text-body-sm link flex items-center justify-center gap-2">
Back to sign in <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> </Link>
</div> </div>
</form> </>
)}
{/* 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>
{/* 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>
</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>
</div> </div>
); );

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,12 @@
/**
* Reset Password Page
*
* Reset password with token from email
*/
'use client'; 'use client';
import { useState, useEffect } from 'react'; import { useState, useEffect, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation'; import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link'; 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 searchParams = useSearchParams();
const router = useRouter(); const router = useRouter();
const [token, setToken] = useState(''); const [token, setToken] = useState('');
@ -19,13 +15,14 @@ export default function ResetPasswordPage() {
const [success, setSuccess] = useState(false); const [success, setSuccess] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [tokenError, setTokenError] = useState(false);
useEffect(() => { useEffect(() => {
const tokenFromUrl = searchParams.get('token'); const tokenFromUrl = searchParams.get('token');
if (tokenFromUrl) { if (tokenFromUrl) {
setToken(tokenFromUrl); setToken(tokenFromUrl);
} else { } else {
setError('Invalid reset link. Please request a new password reset.'); setTokenError(true);
} }
}, [searchParams]); }, [searchParams]);
@ -33,139 +30,218 @@ export default function ResetPasswordPage() {
e.preventDefault(); e.preventDefault();
setError(''); setError('');
// Validate passwords match
if (password !== confirmPassword) { if (password !== confirmPassword) {
setError('Passwords do not match'); setError('Les mots de passe ne correspondent pas');
return; return;
} }
// Validate password length
if (password.length < 12) { if (password.length < 12) {
setError('Password must be at least 12 characters long'); setError('Le mot de passe doit contenir au moins 12 caractères');
return;
}
if (!token) {
setError('Invalid reset token');
return; return;
} }
setLoading(true); setLoading(true);
try { try {
// TODO: Implement resetPassword API endpoint await resetPassword(token, password);
await new Promise(resolve => setTimeout(resolve, 1000));
setSuccess(true); setSuccess(true);
setTimeout(() => { setTimeout(() => router.push('/login'), 3000);
router.push('/login');
}, 3000);
} catch (err: any) { } catch (err: any) {
setError( setError(err.message || 'Le lien de réinitialisation est invalide ou expiré.');
err.response?.data?.message || 'Failed to reset password. The link may have expired.'
);
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
if (success) {
return ( 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="min-h-screen flex">
<div className="max-w-md w-full space-y-8"> {/* Left Side - Form */}
<div> <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">
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1> <div className="max-w-md w-full mx-auto">
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> {/* Logo */}
Password reset successful <div className="mb-10">
</h2> <Link href="/">
</div> <Image
src="/assets/logos/logo-black.svg"
<div className="rounded-md bg-green-50 p-4"> alt="Xpeditis"
<div className="text-sm text-green-800"> width={50}
Your password has been reset successfully. You will be redirected to the login page in height={60}
a few seconds... priority
</div> className="h-auto"
</div> />
<div className="text-center">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
Go to login now
</Link> </Link>
</div> </div>
</div>
</div>
);
}
return ( {tokenError ? (
<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 className="mb-8">
<div> <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mb-6">
<h1 className="text-center text-4xl font-bold text-blue-600">Xpeditis</h1> <svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
Set new password </svg>
</h2> </div>
<p className="mt-2 text-center text-sm text-gray-600">Please enter your new password.</p> <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> </div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}> {/* Error Message */}
{error && ( {error && (
<div className="rounded-md bg-red-50 p-4"> <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
<div className="text-sm text-red-800">{error}</div> <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> </div>
)} )}
<div className="space-y-4"> {/* Form */}
<form onSubmit={handleSubmit} className="space-y-6">
<div> <div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700"> <label htmlFor="password" className="label">
New Password Nouveau mot de passe
</label> </label>
<input <input
id="password" id="password"
name="password"
type="password" type="password"
autoComplete="new-password"
required required
value={password} value={password}
onChange={e => setPassword(e.target.value)} 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" className="input w-full"
placeholder="••••••••••••"
autoComplete="new-password"
disabled={loading}
/> />
<p className="mt-1 text-xs text-gray-500">Must be at least 12 characters long</p> <p className="mt-1.5 text-body-xs text-neutral-500">Au moins 12 caractères</p>
</div> </div>
<div> <div>
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700"> <label htmlFor="confirmPassword" className="label">
Confirm New Password Confirmer le mot de passe
</label> </label>
<input <input
id="confirmPassword" id="confirmPassword"
name="confirmPassword"
type="password" type="password"
autoComplete="new-password"
required required
value={confirmPassword} value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)} 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" className="input w-full"
placeholder="••••••••••••"
autoComplete="new-password"
disabled={loading}
/> />
</div> </div>
</div>
<div>
<button <button
type="submit" type="submit"
disabled={loading || !token} 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" className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed"
> >
{loading ? 'Resetting password...' : 'Reset password'} {loading ? 'Réinitialisation...' : 'Réinitialiser le mot de passe'}
</button> </button>
</div> </form>
<div className="text-center text-sm"> <div className="mt-8 text-center">
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500"> <Link href="/login" className="text-body-sm link flex items-center justify-center gap-2">
Back to sign in <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> </Link>
</div> </div>
</form> </>
)}
{/* 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>
{/* 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>
</div> </div>
</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 * User login
* POST /api/v1/auth/login * POST /api/v1/auth/login
*/ */
export async function login(data: LoginRequest): Promise<AuthResponse> { export async function login(data: LoginRequest & { rememberMe?: boolean }): Promise<AuthResponse> {
const response = await post<AuthResponse>('/api/v1/auth/login', data, false); const { rememberMe, ...loginData } = data;
const response = await post<AuthResponse>('/api/v1/auth/login', loginData, false);
// Store tokens // Store tokens — localStorage if rememberMe, sessionStorage otherwise
setAuthTokens(response.accessToken, response.refreshToken); setAuthTokens(response.accessToken, response.refreshToken, rememberMe ?? false);
return response; return response;
} }
@ -69,3 +70,19 @@ export async function logout(): Promise<SuccessResponse> {
export async function getCurrentUser(): Promise<UserPayload> { export async function getCurrentUser(): Promise<UserPayload> {
return get<UserPayload>('/api/v1/auth/me'); 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> = []; 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 { export function getAuthToken(): string | null {
if (typeof window === 'undefined') return 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 { export function getRefreshToken(): string | null {
if (typeof window === 'undefined') return 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; if (typeof window === 'undefined') return;
localStorage.setItem('access_token', accessToken); const storage = rememberMe ? localStorage : sessionStorage;
localStorage.setItem('refresh_token', refreshToken); storage.setItem('access_token', accessToken);
storage.setItem('refresh_token', refreshToken);
// Sync to cookie so Next.js middleware can read it for route protection // Sync to cookie so Next.js middleware can read it for route protection
document.cookie = `accessToken=${accessToken}; path=/; SameSite=Lax`; document.cookie = `accessToken=${accessToken}; path=/; SameSite=Lax`;
} }
/** /**
* Clear authentication tokens * Clear authentication tokens from both storages
*/ */
export function clearAuthTokens(): void { export function clearAuthTokens(): void {
if (typeof window === 'undefined') return; if (typeof window === 'undefined') return;
localStorage.removeItem('access_token'); localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token'); localStorage.removeItem('refresh_token');
localStorage.removeItem('user'); localStorage.removeItem('user');
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('refresh_token');
sessionStorage.removeItem('user');
// Expire the middleware cookie // Expire the middleware cookie
document.cookie = 'accessToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax'; 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 data = await response.json();
const newAccessToken = data.accessToken; 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') { 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`; document.cookie = `accessToken=${newAccessToken}; path=/; SameSite=Lax`;
} }

View File

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

View File

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

View File

@ -12,6 +12,7 @@ export interface RegisterOrganizationData {
name: string; name: string;
type: OrganizationType; type: OrganizationType;
siren: string; siren: string;
siret?: string;
street: string; street: string;
city: string; city: string;
state?: string; state?: string;
@ -25,7 +26,8 @@ export interface RegisterRequest {
password: string; password: string;
firstName: string; firstName: string;
lastName: 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 organization?: RegisterOrganizationData; // For new users
} }