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:
parent
6a38c236b2
commit
317de48765
@ -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,
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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
|
||||
*
|
||||
|
||||
@ -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)',
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -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"`);
|
||||
}
|
||||
}
|
||||
@ -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
|
||||
<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>
|
||||
</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.
|
||||
{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>
|
||||
|
||||
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-800">{error}</div>
|
||||
<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-address" className="sr-only">
|
||||
Email address
|
||||
<label htmlFor="email" className="label">
|
||||
Adresse email
|
||||
</label>
|
||||
<input
|
||||
id="email-address"
|
||||
name="email"
|
||||
id="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"
|
||||
className="input w-full"
|
||||
placeholder="votre.email@entreprise.com"
|
||||
autoComplete="email"
|
||||
disabled={loading}
|
||||
/>
|
||||
</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"
|
||||
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>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="text-center text-sm">
|
||||
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
|
||||
Back to sign in
|
||||
<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>
|
||||
</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>
|
||||
);
|
||||
|
||||
@ -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>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -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
|
||||
<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>
|
||||
</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>
|
||||
{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 été 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>
|
||||
|
||||
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-800">{error}</div>
|
||||
<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>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Form */}
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
|
||||
New Password
|
||||
<label htmlFor="password" className="label">
|
||||
Nouveau mot de passe
|
||||
</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"
|
||||
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>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">
|
||||
Confirm New Password
|
||||
<label htmlFor="confirmPassword" className="label">
|
||||
Confirmer le mot de passe
|
||||
</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"
|
||||
className="input w-full"
|
||||
placeholder="••••••••••••"
|
||||
autoComplete="new-password"
|
||||
disabled={loading}
|
||||
/>
|
||||
</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"
|
||||
disabled={loading}
|
||||
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>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="text-center text-sm">
|
||||
<Link href="/login" className="font-medium text-blue-600 hover:text-blue-500">
|
||||
Back to sign in
|
||||
<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>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<ResetPasswordContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -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`;
|
||||
}
|
||||
|
||||
|
||||
@ -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';
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user