Compare commits

6 Commits

14 changed files with 432 additions and 1 deletions

21
package-lock.json generated
View File

@@ -9,6 +9,7 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@fastify/cookie": "^11.0.2",
"@prisma/adapter-pg": "^7.6.0",
"@prisma/client": "^7.6.0",
"argon2": "^0.44.0",
@@ -548,6 +549,26 @@
"fast-uri": "^3.0.0"
}
},
"node_modules/@fastify/cookie": {
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/@fastify/cookie/-/cookie-11.0.2.tgz",
"integrity": "sha512-GWdwdGlgJxyvNv+QcKiGNevSspMQXncjMZ1J8IvuDQk0jvkzgWWZFNC2En3s+nHndZBGV8IbLwOI/sxCZw/mzA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "MIT",
"dependencies": {
"cookie": "^1.0.0",
"fastify-plugin": "^5.0.0"
}
},
"node_modules/@fastify/error": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.0.tgz",

View File

@@ -16,6 +16,7 @@
"author": "Raffi",
"license": "ISC",
"dependencies": {
"@fastify/cookie": "^11.0.2",
"@prisma/adapter-pg": "^7.6.0",
"@prisma/client": "^7.6.0",
"argon2": "^0.44.0",

View File

@@ -41,4 +41,13 @@ model User {
encryptedPrivateKey String?
ActionToken ActionToken[]
AuthToken AuthToken[]
UserPreference UserPreference?
}
model UserPreference {
id String @id
userId String @unique
language String @default("fr")
theme String @default("light")
User User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

View File

@@ -1,11 +1,20 @@
import Fastify from 'fastify'
import prismaPlugin from './plugins/prisma'
import cookie from '@fastify/cookie'
import prismaPlugin from './plugins/prisma.js'
import mailerPlugin from './plugins/mailer.js'
import authRoutes from './routes/auth.js'
import userRoutes from './routes/users.js'
import errorHandler from './plugins/errorHandler.js'
export default function buildApp() {
const app = Fastify({ logger: true })
app.register(errorHandler)
app.register(cookie)
app.register(prismaPlugin)
app.register(mailerPlugin)
app.register(authRoutes, { prefix: '/api' })
app.register(userRoutes, { prefix: '/api' })
app.get('/health', async () => ({ status: 'ok' }))

25
src/errors/AppError.ts Normal file
View File

@@ -0,0 +1,25 @@
export class AppError extends Error {
constructor(
public readonly code: string,
public readonly statusCode: number,
message: string
) {
super(message)
this.name = 'AppError'
}
}
// Erreurs prédéfinies
export const Errors = {
// registration errors
EMAIL_TAKEN: new AppError('EMAIL_TAKEN', 409, 'Cette adresse email est déjà utilisée.'),
PASSWORD_TOO_WEAK: new AppError('PASSWORD_TOO_WEAK', 400, 'Le mot de passe doit contenir au moins 8 caractères.'),
INVALID_CREDENTIALS: new AppError('INVALID_CREDENTIALS', 401, 'Email ou mot de passe incorrect.'),
VALIDATION_ERROR: (message: string) => new AppError('VALIDATION_ERROR', 400, message),
//Action token errors
INVALID_TOKEN: new AppError('INVALID_TOKEN', 400, 'Invalid or already used token'),
TOKEN_EXPIRED: new AppError('TOKEN_EXPIRED', 400, 'Token has expired'),
ALREADY_CONFIRMED: new AppError('ALREADY_CONFIRMED', 400, 'User is already confirmed'),
}

View File

@@ -0,0 +1,34 @@
import fp from 'fastify-plugin'
import { FastifyInstance } from 'fastify'
import { ZodError } from 'zod'
import { AppError } from '../errors/AppError.js'
export default fp(async (fastify: FastifyInstance) => {
fastify.setErrorHandler((error, request, reply) => {
// Erreur Zod
if (error instanceof ZodError) {
return reply.status(400).send({
error: 'VALIDATION_ERROR',
details: error.issues.map((e) => ({
field: e.path.join('.'),
message: e.message,
})),
})
}
// Erreur métier
if (error instanceof AppError) {
return reply.status(error.statusCode).send({
error: error.code,
message: error.message,
})
}
// Erreur inconnue
fastify.log.error(error)
return reply.status(500).send({
error: 'INTERNAL_ERROR',
message: 'Une erreur interne est survenue.',
})
})
})

22
src/plugins/mailer.ts Normal file
View File

@@ -0,0 +1,22 @@
import fp from 'fastify-plugin'
import { FastifyInstance } from 'fastify'
import nodemailer, { Transporter } from 'nodemailer'
declare module 'fastify' {
interface FastifyInstance {
mailer: Transporter
}
}
export default fp(async (fastify: FastifyInstance) => {
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
})
fastify.decorate('mailer', transporter)
})

47
src/routes/auth.ts Normal file
View File

@@ -0,0 +1,47 @@
import { FastifyInstance } from 'fastify'
import { RegisterSchema } from '../schemas/auth.schema.js'
import { registerUser } from '../services/auth.service.js'
import { LoginSchema } from '../schemas/auth.schema.js'
import { loginUser } from '../services/auth.service.js'
export default async function authRoutes(fastify: FastifyInstance) {
fastify.post('/auth/register', async (request, reply) => {
const body = RegisterSchema.parse(request.body) // Zod throw → handler global
const lang = request.headers['accept-language']
?.split(',')[0]
.split('-')[0] as 'fr' | 'en'
const validLang = ['fr', 'en'].includes(lang) ? lang : 'fr'
const { user, authToken } = await registerUser(
fastify.prisma,
fastify.mailer,
body,
validLang
)
reply.setCookie('authToken', authToken, {
httpOnly: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 7,
})
return reply.status(201).send({ user })
})
fastify.post('/auth/login', async (request, reply) => {
const body = LoginSchema.parse(request.body)
const { user, authToken } = await loginUser(fastify.prisma, body)
reply.setCookie('authToken', authToken, {
httpOnly: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 7,
})
return reply.status(200).send({ user })
})
}

View File

@@ -1,4 +1,6 @@
import { FastifyInstance } from 'fastify'
import { Errors } from '../errors/AppError'
import { confirmEmail } from '../services/user.service'
export default async function userRoutes(fastify: FastifyInstance) {
fastify.get('/users', async (request, reply) => {
@@ -16,4 +18,15 @@ export default async function userRoutes(fastify: FastifyInstance) {
return users
})
fastify.get('/user/confirm', async (request, reply) => {
const { token } = request.query as { token?: string }
if (!token) {
throw Errors.INVALID_TOKEN
}
const result = await confirmEmail(fastify.prisma, token)
return reply.status(200).send(result)
})
}

View File

@@ -0,0 +1,21 @@
import { z } from 'zod'
export const RegisterSchema = z.object({
email: z.email({ error: 'Adresse email invalide.' }),
password: z
.string()
.regex(/^.{8,22}$/, { error: 'Le mot de passe doit contenir entre 8 et 22 caractères.' })
.regex(/[^A-Za-z0-9]/, { error: 'Le mot de passe doit contenir au moins un caractère spécial.' })
.regex(/[A-Z]/, { error: 'Le mot de passe doit contenir au moins une majuscule.' })
.regex(/[a-z]/, { error: 'Le mot de passe doit contenir au moins une minuscule.' })
.regex(/\d/, { error: 'Le mot de passe doit contenir au moins un chiffre.' }),
})
export type RegisterInput = z.infer<typeof RegisterSchema>
export const LoginSchema = z.object({
email: z.email({ error: 'Adresse email invalide.' }),
password: z.string().min(1, { error: 'Le mot de passe est requis.' }),
})
export type LoginInput = z.infer<typeof LoginSchema>

View File

@@ -0,0 +1,124 @@
import argon2 from 'argon2'
import crypto from 'crypto'
import { PrismaClient } from '../generated/prisma/client.js'
import { Transporter } from 'nodemailer'
import { RegisterInput, LoginInput } from '../schemas/auth.schema.js'
import { generateToken, generateAuthTokenExpiry, generateActionTokenExpiry } from './token.service.js'
import { sendConfirmationMail } from './mail.service.js'
import { Errors } from '../errors/AppError.js'
export async function registerUser(
prisma: PrismaClient,
mailer: Transporter,
input: RegisterInput,
lang: 'fr' | 'en' = 'fr'
) {
// 1. Vérif email unique
const existing = await prisma.user.findUnique({
where: { email: input.email },
})
if (existing) {
throw Errors.EMAIL_TAKEN }
// 2. Hash du mot de passe
const passwordHash = await argon2.hash(input.password)
// 3. Création du user
const displayName = input.email.split('@')[0]
const user = await prisma.user.create({
data: {
id: crypto.randomUUID(),
email: input.email,
passwordHash,
displayName,
avatar: '',
},
select: {
id: true,
email: true,
displayName: true,
isConfirmed: true,
createdAt: true,
},
})
// 4. ActionToken pour confirmation mail
const confirmToken = generateToken()
await prisma.actionToken.create({
data: {
id: crypto.randomUUID(),
userId: user.id,
token: confirmToken,
type: 'email-confirm',
expiresAt: generateActionTokenExpiry(1440), // 24h
},
})
// 5. Envoi du mail avec la langue
await sendConfirmationMail(mailer, user.email, confirmToken, lang)
// 6. AuthToken pour la persistance
const authToken = generateToken()
await prisma.authToken.create({
data: {
id: crypto.randomUUID(),
userId: user.id,
token: authToken,
expiresAt: generateAuthTokenExpiry(),
},
})
// 7 Création des préférences avec la langue détectée
await prisma.userPreference.create({
data: {
id: crypto.randomUUID(),
userId: user.id,
language: lang,
theme: 'light',
},
})
return { user, authToken }
}
export async function loginUser(
prisma: PrismaClient,
input: LoginInput
) {
// 1. Vérif user existe
const user = await prisma.user.findUnique({
where: { email: input.email },
})
if (!user) {
throw Errors.INVALID_CREDENTIALS
}
// 2. Vérif password
const valid = await argon2.verify(user.passwordHash, input.password)
if (!valid) {
throw Errors.INVALID_CREDENTIALS
}
// 3. Création AuthToken
const authToken = generateToken()
await prisma.authToken.create({
data: {
id: crypto.randomUUID(),
userId: user.id,
token: authToken,
expiresAt: generateAuthTokenExpiry(),
},
})
return {
user: {
id: user.id,
email: user.email,
displayName: user.displayName,
isConfirmed: user.isConfirmed,
createdAt: user.createdAt,
},
authToken,
}
}

View File

@@ -0,0 +1,51 @@
import { Transporter } from 'nodemailer'
type Lang = 'fr' | 'en'
const templates = {
fr: (url: string) => ({
subject: 'Merci de confirmer votre e-mail',
html: `
<html><body>
<p>Bienvenue sur le gestionnaire de listes !</p>
<p>
Pour pouvoir utiliser le site, vous devez confirmer votre adresse mail sous 7 jours en cliquant sur
<a href="${url}" style="font-size:1.2em;color:blueviolet;">
ce lien
</a>.
</p>
</body></html>
`,
}),
en: (url: string) => ({
subject: 'Please confirm your email address',
html: `
<html><body>
<p>Welcome to the list manager!</p>
<p>
To start using the site, please confirm your email address within 7 days by clicking
<a href="${url}" style="font-size:1.2em;color:blueviolet;">
this link
</a>.
</p>
</body></html>
`,
}),
}
export async function sendConfirmationMail(
mailer: Transporter,
email: string,
token: string,
lang: Lang = 'fr'
): Promise<void> {
const url = `${process.env.FRONT_URL}/${lang}/confirm?token=${token}`
const { subject, html } = templates[lang](url)
await mailer.sendMail({
from: process.env.MAIL_FROM,
to: email,
subject,
html,
})
}

View File

@@ -0,0 +1,17 @@
import crypto from 'crypto'
export function generateToken(length = 32): string {
return crypto.randomBytes(length).toString('hex')
}
export function generateAuthTokenExpiry(): Date {
const date = new Date()
date.setDate(date.getDate() + 7)
return date
}
export function generateActionTokenExpiry(minutes = 1440): Date {
const date = new Date()
date.setMinutes(date.getMinutes() + minutes)
return date
}

View File

@@ -0,0 +1,37 @@
import { PrismaClient } from '../generated/prisma/client.js'
import { Errors } from '../errors/AppError.js'
export async function confirmEmail(prisma: PrismaClient, token: string) {
const actionToken = await prisma.actionToken.findUnique({
where: { token },
})
if (!actionToken || actionToken.type !== 'email-confirm' || actionToken.used) {
throw Errors.INVALID_TOKEN
}
if (actionToken.expiresAt < new Date()) {
throw Errors.TOKEN_EXPIRED
}
const user = await prisma.user.findUnique({
where: { id: actionToken.userId },
select: { isConfirmed: true },
})
if (user?.isConfirmed) {
throw Errors.ALREADY_CONFIRMED
}
await prisma.$transaction([
prisma.user.update({
where: { id: actionToken.userId },
data: { isConfirmed: true },
}),
prisma.actionToken.delete({
where: { id: actionToken.id },
}),
])
return { success: true }
}