Skip to content

Commit

Permalink
Added nodemailer package
Browse files Browse the repository at this point in the history
  • Loading branch information
antoineludeau committed Nov 12, 2024
1 parent 15afd01 commit 18a1344
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ REDIS_MAXMEMORY=5gb # Max memory
REDIS_MAXMEMORY_POLICY=allkeys-lru # Max memory policy
REDIS_MAPTILES_CACHE_DURATION=3600 # Duration in seconds for map tiles cache

# SMTP
SMTP_HOST=smtp.ethereal.email
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
MAIL_SENDER=[email protected]
# Pour les tests, créer un compte sur https://ethereal.email/create

# Token
TOKEN_EXPIRY_TIME=7200 # duration in seconds for token expiry

# APIs
# API BAN
BAN_API_URL=https://plateforme.adresse.data.gouv.fr/api
Expand Down
6 changes: 6 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ services:
- IS_GENERATE_BANID_ON_ASSEMBLY=${IS_GENERATE_BANID_ON_ASSEMBLY}
- CP_PATH=${CP_PATH}
- DATANOVA_PATH=${DATANOVA_PATH}
- SMTP_HOST=${SMTP_HOST}
- SMTP_PORT=${SMTP_PORT}
- SMTP_USER=${SMTP_USER}
- SMTP_PASSWORD=${SMTP_PASSWORD}
- TOKEN_EXPIRY_TIME=${TOKEN_EXPIRY_TIME}
- MAIL_SENDER=${MAIL_SENDER}
ports:
- "${PORT:-5000}:5000"
volumes:
Expand Down
138 changes: 138 additions & 0 deletions lib/api/token/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import 'dotenv/config.js' // eslint-disable-line import/no-unassigned-import
import express from 'express'
import {customAlphabet} from 'nanoid'
import auth from '../../middleware/auth.js'
import analyticsMiddleware from '../../middleware/analytics.js'
import {redis} from '../../util/redis.cjs'
import {transporter} from '../../util/smtp.js'
import {handleAPIResponse} from '../helper.js'

const app = new express.Router()

const nanoid = customAlphabet('123456789ABCDEFGHJKMNPQRSTVWXYZ', 6)

const TOKEN_EXPIRY_TIME = process.env.TOKEN_EXPIRY_TIME || 7200
const {MAIL_SENDER} = process.env

const generateMailContent = token => `
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Authentification - Base Adresse Nationale</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f6f6f6;
color: #333;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 20px auto;
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.header {
text-align: center;
padding-bottom: 20px;
}
.header img {
max-width: 100px;
}
.content {
font-size: 16px;
line-height: 1.6;
}
.token {
display: block;
text-align: center;
font-size: 24px;
font-weight: bold;
color: #004085;
background-color: #e9ecef;
padding: 10px;
border-radius: 4px;
margin: 20px 0;
}
.footer {
font-size: 12px;
color: #666;
text-align: center;
margin-top: 20px;
}
.footer a {
color: #004085;
text-decoration: none;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<img src="https://adresse.data.gouv.fr/images/logos/BAN.png" alt="Base Adresse Nationale">
</div>
<div class="content">
<p>Bonjour,</p>
<p>Vous avez demandé un accès sécurisé pour vous connecter à votre Espace "Commune" sur le site de la <strong>Base Adresse Nationale</strong> via <a href="https://adresse.data.gouv.fr">adresse.data.gouv.fr</a>.</p>
<p>Veuillez utiliser le code de vérification ci-dessous pour procéder à votre authentification :</p>
<div class="token">${token}</div>
<p>Ce code est valide pendant <strong>${TOKEN_EXPIRY_TIME / 3600} heures</strong>. Passé ce délai, vous devrez en générer un nouveau pour vous connecter.</p>
<p>Si vous n'avez pas fait cette demande, veuillez ignorer cet email. Votre adresse restera en sécurité.</p>
</div>
<div class="footer">
<p>Merci de faire confiance à la Base Adresse Nationale.<br>
<p>&copy; 2024 Base Adresse Nationale - Tous droits réservés.</p>
</div>
</div>
</body>
</html>
`

const defaultMailOptions = {
from: MAIL_SENDER,
subject: 'Base Adresse Nationale - Votre token de connexion',
}

app.post('/', auth, analyticsMiddleware, async (req, res) => {
try {
const {email} = req.body

if (!email) {
handleAPIResponse(res, 400, 'Email address is required.', {})
}

// Const existingToken = await redis.get(email)
// if (existingToken) {
// handleAPIResponse(res, 401, 'Token already sent. Please check your email.', {})
// }

// Generate a token and set expiry time
const token = nanoid()

// Store the token in Redis with expiry time
await redis.set(email, token, 'EX', TOKEN_EXPIRY_TIME)

// Send the token via email
const mailOptions = {
...defaultMailOptions,
to: email,
html: generateMailContent(token),
}

await transporter.sendMail(mailOptions)

handleAPIResponse(res, 200, 'Token generated and sent to email.', {})
} catch (error) {
console.error(error)
handleAPIResponse(res, 500, 'Internal server error', {})
}
})

export default app
13 changes: 13 additions & 0 deletions lib/util/smtp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import nodemailer from 'nodemailer'

const {SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD} = process.env

// Set up SMTP transporter
export const transporter = nodemailer.createTransport({
host: SMTP_HOST,
port: SMTP_PORT,
auth: {
user: SMTP_USER,
pass: SMTP_PASSWORD
}
})
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
"nanoid": "^4.0.2",
"ndjson": "^2.0.0",
"node-fetch": "^2.6.11",
"nodemailer": "^6.9.16",
"ora": "^5.4.1",
"papaparse": "^5.4.1",
"pg": "^8.11.0",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6697,6 +6697,11 @@ node-releases@^2.0.8:
resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.10.tgz#c311ebae3b6a148c89b1813fd7c4d3c024ef537f"
integrity sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w==

nodemailer@^6.9.16:
version "6.9.16"
resolved "https://registry.yarnpkg.com/nodemailer/-/nodemailer-6.9.16.tgz#3ebdf6c6f477c571c0facb0727b33892635e0b8b"
integrity sha512-psAuZdTIRN08HKVd/E8ObdV6NO7NTBY3KsC30F7M4H1OnmLCUNaS56FpYxyb26zWLSyYF9Ozch9KYHhHegsiOQ==

nopt@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/nopt/-/nopt-5.0.0.tgz#530942bb58a512fccafe53fe210f13a25355dc88"
Expand Down

0 comments on commit 18a1344

Please sign in to comment.