878 lines
95 KiB
Python
878 lines
95 KiB
Python
#!/usr/bin/env python3
|
||
import base64, hashlib, hmac, json, os, secrets, sqlite3
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
from http.cookies import SimpleCookie
|
||
from urllib.parse import parse_qs, urlparse
|
||
|
||
VERSION = "1.0.0"
|
||
DB = "candipilot.db"
|
||
SESSIONS = {}
|
||
|
||
def db():
|
||
con = sqlite3.connect(DB)
|
||
con.row_factory = sqlite3.Row
|
||
return con
|
||
|
||
def init_db():
|
||
with db() as con:
|
||
con.executescript("""
|
||
CREATE TABLE IF NOT EXISTS users (
|
||
id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL,
|
||
password_hash TEXT NOT NULL, salt TEXT NOT NULL
|
||
);
|
||
CREATE TABLE IF NOT EXISTS applications (
|
||
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL,
|
||
company TEXT NOT NULL DEFAULT '', role TEXT NOT NULL DEFAULT '',
|
||
location TEXT NOT NULL DEFAULT '', contact TEXT NOT NULL DEFAULT '',
|
||
method TEXT NOT NULL DEFAULT 'Mail', sent_date TEXT DEFAULT '',
|
||
followup_date TEXT DEFAULT '', status TEXT NOT NULL DEFAULT 'Envoyée',
|
||
notes TEXT NOT NULL DEFAULT '', FOREIGN KEY(user_id) REFERENCES users(id)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS shares (
|
||
token TEXT PRIMARY KEY, user_id INTEGER UNIQUE NOT NULL
|
||
);
|
||
""")
|
||
|
||
def init_settings():
|
||
with db() as con:
|
||
con.execute("CREATE TABLE IF NOT EXISTS share_links(token TEXT PRIMARY KEY,user_id INTEGER NOT NULL,label TEXT NOT NULL DEFAULT '',permission TEXT NOT NULL CHECK(permission IN ('read','edit')))")
|
||
con.execute("INSERT OR IGNORE INTO share_links(token,user_id,label,permission) SELECT token,user_id,'Ancien lien','edit' FROM shares")
|
||
con.execute('DELETE FROM shares')
|
||
con.executescript("""
|
||
CREATE TABLE IF NOT EXISTS settings(user_id INTEGER PRIMARY KEY, methods TEXT NOT NULL, notify_email TEXT DEFAULT '', enabled INTEGER DEFAULT 0);
|
||
CREATE TABLE IF NOT EXISTS mail_log(application_id INTEGER, followup_date TEXT, PRIMARY KEY(application_id,followup_date));
|
||
CREATE TABLE IF NOT EXISTS sessions(token TEXT PRIMARY KEY,user_id INTEGER NOT NULL,expires REAL NOT NULL);
|
||
""")
|
||
|
||
columns={r['name'] for r in con.execute('PRAGMA table_info(applications)')}
|
||
if 'interview_at' not in columns:con.execute("ALTER TABLE applications ADD COLUMN interview_at TEXT DEFAULT ''")
|
||
if 'interview_type' not in columns:con.execute("ALTER TABLE applications ADD COLUMN interview_type TEXT NOT NULL DEFAULT 'Présentiel'")
|
||
if 'interview_address' not in columns:con.execute("ALTER TABLE applications ADD COLUMN interview_address TEXT DEFAULT ''")
|
||
con.execute('CREATE TABLE IF NOT EXISTS interview_mail_log(application_id INTEGER, reminder_days INTEGER, interview_at TEXT, PRIMARY KEY(application_id,reminder_days,interview_at))')
|
||
con.execute("CREATE TABLE IF NOT EXISTS mail_settings(user_id INTEGER PRIMARY KEY, config TEXT NOT NULL)")
|
||
|
||
MAIL_DEFAULTS={'smtp_host':'','smtp_port':587,'smtp_security':'starttls','smtp_from':'','smtp_user':'','smtp_password':'','mail_subject':'Relance à faire : {entreprise}','mail_body':'Bonjour,\nVotre candidature chez {entreprise} pour le poste {poste} est à relancer.\nDate de relance : {date_relance}\nMoyen : {moyen}\nContact : {contact}'}
|
||
MAIL_DEFAULTS.update({'interview_mail_subject':'Rappel : entretien dans {jours_restants} jour(s) — {entreprise}','interview_mail_body':'Votre entretien avec {entreprise} pour le poste {poste} est prévu le {date_entretien} à {heure_entretien}.\nType de rendez-vous : {type_entretien}\nAdresse : {adresse_entretien}\n\nIl reste {jours_restants} jour(s).\nContact : {contact}\nNotes : {notes}'})
|
||
def mail_settings(uid):
|
||
uid=admin_id() or uid
|
||
values=dict(MAIL_DEFAULTS)
|
||
for key,env in [('smtp_host','SMTP_HOST'),('smtp_from','SMTP_FROM'),('smtp_user','SMTP_USER'),('smtp_password','SMTP_PASSWORD')]:values[key]=os.environ.get(env,'')
|
||
values['smtp_port']=int(os.environ.get('SMTP_PORT','587'));values['smtp_security']='ssl' if values['smtp_port']==465 else 'starttls'
|
||
with db() as con:r=con.execute('SELECT config FROM mail_settings WHERE user_id=?',(uid,)).fetchone()
|
||
if r:values.update(json.loads(r['config']))
|
||
return values
|
||
|
||
def render_mail(template,r):
|
||
mapping={'entreprise':r['company'],'poste':r['role'],'date_relance':r['followup_date'],'date_envoi':r['sent_date'],'moyen':r['method'],'contact':r['contact'],'notes':r['notes']}
|
||
import re
|
||
return re.sub(r'\{(entreprise|poste|date_relance|date_envoi|moyen|contact|notes)\}',lambda m:mapping[m.group(1)] or '',template)
|
||
|
||
def render_interview_mail(template,r,when,remaining):
|
||
mapping={'entreprise':r['company'],'poste':r['role'],'date_entretien':when.strftime('%d/%m/%Y'),'heure_entretien':when.strftime('%H:%M'),'type_entretien':r['interview_type'] or 'Présentiel','adresse_entretien':('Sans objet (visio)' if r['interview_type']=='Visio' else r['interview_address'] or 'non renseignée'),'jours_restants':str(remaining),'contact':r['contact'],'notes':r['notes'],'date_relance':r['followup_date'],'date_envoi':r['sent_date'],'moyen':r['method']}
|
||
import re
|
||
return re.sub(r'\{('+'|'.join(mapping)+r')\}',lambda m:str(mapping[m.group(1)] or ''),template)
|
||
|
||
def admin_id():
|
||
with db() as con:r=con.execute('SELECT MIN(id) AS id FROM users').fetchone()
|
||
return r['id']
|
||
|
||
def registration_enabled():
|
||
with db() as con:
|
||
con.execute('CREATE TABLE IF NOT EXISTS app_config(key TEXT PRIMARY KEY,value TEXT NOT NULL)')
|
||
r=con.execute("SELECT value FROM app_config WHERE key='registration'").fetchone()
|
||
return not r or r['value']=='1'
|
||
|
||
def get_settings(uid):
|
||
with db() as con:
|
||
columns={r['name'] for r in con.execute('PRAGMA table_info(settings)')}
|
||
if 'followup_days' not in columns:con.execute("ALTER TABLE settings ADD COLUMN followup_days INTEGER NOT NULL DEFAULT 7")
|
||
if 'notify_time' not in columns:con.execute("ALTER TABLE settings ADD COLUMN notify_time TEXT NOT NULL DEFAULT '09:00'")
|
||
if 'interview_reminders' not in columns:con.execute("ALTER TABLE settings ADD COLUMN interview_reminders TEXT NOT NULL DEFAULT '7,1'")
|
||
r=con.execute('SELECT * FROM settings WHERE user_id=?',(uid,)).fetchone()
|
||
return dict(r) if r else {'methods':json.dumps(['Mail','Formulaire','LinkedIn','Site carrière','Autre']), 'notify_email':'', 'enabled':0}
|
||
|
||
def notification_loop():
|
||
import time, smtplib
|
||
from datetime import date
|
||
from email.message import EmailMessage
|
||
while True:
|
||
try:
|
||
if True:
|
||
with db() as con:
|
||
due=con.execute("SELECT a.*,s.notify_email FROM applications a JOIN settings s ON s.user_id=a.user_id WHERE s.enabled=1 AND s.notify_email<>'' AND a.status IN ('Envoyée','À relancer') AND a.followup_date<>'' AND a.followup_date<=? AND NOT EXISTS(SELECT 1 FROM mail_log m WHERE m.application_id=a.id AND m.followup_date=a.followup_date)",(date.today().isoformat(),)).fetchall()
|
||
for r in due:
|
||
from datetime import datetime
|
||
settings=get_settings(r['user_id'])
|
||
if datetime.now().strftime('%H:%M') < settings.get('notify_time','09:00'):continue
|
||
cfg=mail_settings(r['user_id'])
|
||
if not cfg['smtp_host'] or not cfg['smtp_from']:continue
|
||
msg=EmailMessage();msg['From']=cfg['smtp_from'];msg['To']=r['notify_email'];msg['Subject']=render_mail(cfg['mail_subject'],r).replace('\r',' ').replace('\n',' ')
|
||
msg.set_content(render_mail(cfg['mail_body'],r))
|
||
cls=smtplib.SMTP_SSL if cfg['smtp_security']=='ssl' else smtplib.SMTP
|
||
import ssl
|
||
with cls(cfg['smtp_host'],cfg['smtp_port'],timeout=30) as smtp:
|
||
if cfg['smtp_security']=='starttls':smtp.starttls(context=ssl.create_default_context())
|
||
if cfg['smtp_user']:smtp.login(cfg['smtp_user'],cfg['smtp_password'])
|
||
smtp.send_message(msg)
|
||
with db() as con:
|
||
con.execute('INSERT OR IGNORE INTO mail_log VALUES(?,?)',(r['id'],r['followup_date']))
|
||
con.execute("UPDATE applications SET status='À relancer' WHERE id=? AND status='Envoyée'",(r['id'],))
|
||
with db() as con:
|
||
interviews=con.execute("SELECT a.*,s.notify_email FROM applications a JOIN settings s ON s.user_id=a.user_id WHERE s.enabled=1 AND s.notify_email<>'' AND a.status='Entretien' AND a.interview_at<>''").fetchall()
|
||
from datetime import datetime,timedelta
|
||
for r in interviews:
|
||
settings=get_settings(r['user_id'])
|
||
if datetime.now().strftime('%H:%M') < settings.get('notify_time','09:00'):continue
|
||
try:when=datetime.fromisoformat(r['interview_at'])
|
||
except ValueError:continue
|
||
remaining=(when.date()-date.today()).days
|
||
try:reminders={int(v.strip()) for v in settings.get('interview_reminders','7,1').split(',') if v.strip()}
|
||
except ValueError:continue
|
||
if remaining not in reminders or when<=datetime.now():continue
|
||
with db() as con:already=con.execute('SELECT 1 FROM interview_mail_log WHERE application_id=? AND reminder_days=? AND interview_at=?',(r['id'],remaining,r['interview_at'])).fetchone()
|
||
if already:continue
|
||
cfg=mail_settings(r['user_id'])
|
||
if not cfg['smtp_host'] or not cfg['smtp_from']:continue
|
||
msg=EmailMessage();msg['From']=cfg['smtp_from'];msg['To']=r['notify_email'];msg['Subject']=render_interview_mail(cfg['interview_mail_subject'],r,when,remaining).replace('\r',' ').replace('\n',' ')
|
||
msg.set_content(render_interview_mail(cfg['interview_mail_body'],r,when,remaining))
|
||
cls=smtplib.SMTP_SSL if cfg['smtp_security']=='ssl' else smtplib.SMTP
|
||
import ssl
|
||
with cls(cfg['smtp_host'],cfg['smtp_port'],timeout=30) as smtp:
|
||
if cfg['smtp_security']=='starttls':smtp.starttls(context=ssl.create_default_context())
|
||
if cfg['smtp_user']:smtp.login(cfg['smtp_user'],cfg['smtp_password'])
|
||
smtp.send_message(msg)
|
||
with db() as con:con.execute('INSERT OR IGNORE INTO interview_mail_log VALUES(?,?,?)',(r['id'],remaining,r['interview_at']))
|
||
except Exception as e:
|
||
print('Notification non envoyée :',type(e).__name__,flush=True)
|
||
time.sleep(60)
|
||
|
||
RESET_LIMIT={}
|
||
def recovery_tables(con):
|
||
con.execute('CREATE TABLE IF NOT EXISTS password_resets(token_hash TEXT PRIMARY KEY,user_id INTEGER NOT NULL,expires REAL NOT NULL)')
|
||
def invalidate_sessions(uid):
|
||
for token,owner in list(SESSIONS.items()):
|
||
if owner==uid:SESSIONS.pop(token,None)
|
||
with db() as con:con.execute('DELETE FROM sessions WHERE user_id=?',(uid,))
|
||
def send_recovery(recipient,token):
|
||
import smtplib,ssl
|
||
from email.message import EmailMessage
|
||
cfg=mail_settings(admin_id());msg=EmailMessage();msg['From']=cfg['smtp_from'];msg['To']=recipient;msg['Subject']='Réinitialisation de votre mot de passe'
|
||
msg.set_content('Votre code de récupération (valable 30 minutes, utilisable une seule fois) :\n\n'+token+'\n\nOuvrez votre application, choisissez Mot de passe oublié, puis saisissez ce code et votre nouveau mot de passe. Si vous n’avez rien demandé, ignorez ce mail.')
|
||
cls=smtplib.SMTP_SSL if cfg['smtp_security']=='ssl' else smtplib.SMTP
|
||
with cls(cfg['smtp_host'],cfg['smtp_port'],timeout=30) as smtp:
|
||
if cfg['smtp_security']=='starttls':smtp.starttls(context=ssl.create_default_context())
|
||
if cfg['smtp_user']:smtp.login(cfg['smtp_user'],cfg['smtp_password'])
|
||
smtp.send_message(msg)
|
||
|
||
def hash_password(password, salt=None):
|
||
salt = salt or secrets.token_bytes(16)
|
||
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 310000)
|
||
return base64.b64encode(digest).decode(), base64.b64encode(salt).decode()
|
||
|
||
def page():
|
||
return '''<!doctype html><html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>CandiPilot</title><link rel="icon" type="image/png" href="/favicon.png">
|
||
<style>
|
||
:root{color-scheme:light dark;--bg:#f5f7fb;--card:#fff;--ink:#172333;--muted:#647487;--line:#dbe3ef;--accent:#2967d8;--danger:#c94242}@media(prefers-color-scheme:dark){:root{--bg:#101722;--card:#192231;--ink:#edf3fa;--muted:#aebdce;--line:#314154;--accent:#78a8ff;--danger:#ff8585}}
|
||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:14px system-ui,-apple-system,Segoe UI,sans-serif}.wrap{max-width:1400px;margin:auto;padding:28px 18px}.auth{max-width:420px;margin:11vh auto;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px;box-shadow:0 12px 30px #0001}h1{font-size:28px;margin:0 0 4px}h2{margin:0 0 18px}.muted{color:var(--muted);margin:0 0 22px}label{display:block;font-weight:650;margin:13px 0 5px}input,select,textarea{width:100%;border:1px solid var(--line);background:transparent;color:var(--ink);border-radius:8px;padding:9px;font:inherit}select{color-scheme:light;background-color:#ffffff!important;color:#172333!important}select option,optgroup{background-color:#ffffff!important;color:#172333!important}@media(prefers-color-scheme:dark){select{color-scheme:dark;background-color:#192231!important;color:#edf3fa!important}select option,optgroup{background-color:#192231!important;color:#edf3fa!important}}button{background:var(--accent);color:white;border:0;border-radius:8px;padding:10px 14px;font:inherit;font-weight:700;cursor:pointer}.ghost{background:transparent;border:1px solid var(--line);color:var(--ink)}.error{color:var(--danger);min-height:20px;margin-top:10px}.bar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:20px}.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:18px}.stat{background:var(--card);border:1px solid var(--line);padding:14px;border-radius:11px}.stat b{font-size:23px;display:block}table{border-collapse:collapse;width:100%;min-width:1120px;background:var(--card)}.box{overflow:auto;border:1px solid var(--line);border-radius:12px}th,td{padding:10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}th{font-size:11px;color:var(--muted);text-transform:uppercase;white-space:nowrap}td input,td select{min-width:100px;padding:7px}.delete{color:var(--danger);background:none;padding:7px}.new{margin-bottom:12px}@media(max-width:650px){.grid{grid-template-columns:repeat(2,1fr)}h1{font-size:23px}}
|
||
[hidden]{display:none!important}.stat.alert{border-color:var(--danger);background:color-mix(in srgb,var(--danger) 10%,var(--card))}.stat.alert b{color:var(--danger)}.stat.success{border-color:#20945a;background:color-mix(in srgb,#20945a 10%,var(--card))}.stat.success b{color:#16824b}.action-buttons{display:flex;align-items:center;justify-content:flex-end;gap:8px;min-width:max-content}.action-buttons .delete{flex:0 0 auto}.action-buttons .ghost{flex:0 0 auto;white-space:nowrap}.toolbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:0 0 12px}.toolbar input{flex:1 1 260px}.pagination{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-top:14px}.pagination .pages{display:flex;gap:6px;flex-wrap:wrap}.pagination button[aria-current="page"]{background:var(--accent);color:white;border-color:var(--accent)}
|
||
.wrap{width:100%;min-width:0}.auth{width:calc(100% - 32px)}.stat{min-width:0;overflow-wrap:anywhere}input,select,textarea{max-width:100%;min-width:0}textarea{resize:vertical}button{max-width:100%;white-space:normal}.bar{flex-wrap:wrap}.bar>div{min-width:0}nav[role=tablist]{align-items:stretch}input:disabled,select:disabled{opacity:1;color:var(--ink);-webkit-text-fill-color:var(--ink)}
|
||
@media(max-width:900px){.wrap{padding:20px 14px}.bar{align-items:flex-start}.bar .muted{margin-bottom:8px}.auth{margin:6vh auto;padding:22px}.stat{padding:14px}nav[role=tablist] button{flex:1 1 120px}input,select,textarea{font-size:16px;min-height:44px}button{min-height:44px}.stat p button{margin:4px 4px 4px 0}}
|
||
@media(max-width:700px){.grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.bar h1{font-size:24px}.box{border:0;background:transparent;overflow:visible}.box table{min-width:0;background:transparent;display:block}.box thead{display:none}.box tbody{display:grid;gap:14px}.box tr{display:grid;grid-template-columns:minmax(0,1fr);padding:14px;background:var(--card);border:1px solid var(--line);border-radius:12px}.box td{display:block;border:0;padding:6px 0;min-width:0}.box td::before{content:attr(data-label);display:block;margin-bottom:5px;font-size:12px;font-weight:700;color:var(--muted)}.box td:last-child::before{display:none}.box td input,.box td select{min-width:0;width:100%}.box .delete{border:1px solid var(--line);margin-top:0;width:auto}.action-buttons{justify-content:flex-start;flex-wrap:wrap}.action-buttons .ghost{max-width:100%;white-space:normal}.new{width:100%}.auth{margin:24px auto}.auth>button{margin:4px 4px 4px 0}#sharePanel,#settingsPanel,#usersPanel{width:100%}}
|
||
@media(max-width:380px){.wrap{padding:16px 10px}.grid{gap:8px}.stat{padding:12px}.stat b{font-size:21px}nav[role=tablist] button{flex-basis:100px}.auth{padding:18px}}
|
||
.settings-category{margin:18px 0;padding:18px;border:1px solid var(--line);border-radius:12px}.settings-category h3{margin:0 0 14px;font-size:18px}.settings-category p{color:var(--muted);line-height:1.5}.settings-category>label:first-of-type{margin-top:0}@media(max-width:650px){.settings-category{padding:14px}}
|
||
</style></head><body><main id="app"></main><script>
|
||
const app=document.querySelector('#app'); let rows=[];let preferences={methods:['Mail','Formulaire','LinkedIn','Site carrière','Autre']};
|
||
async function openSettings(){try{preferences=await api('/api/settings');document.querySelector('#settingsPanel')?.remove();const panel=document.createElement('section');panel.id='settingsPanel';panel.className='stat';panel.style.marginBottom='16px';panel.innerHTML=`<h2>Paramètres</h2><section class="settings-category"><h3>Candidatures</h3><label>Moyens de candidature — un par ligne</label><textarea id="methodList" rows="6"></textarea><label>Nombre de jours avant la relance</label><input id="followupDays" type="number" min="0" max="365" step="1" value="7"><p>Délai utilisé par défaut pour les nouvelles candidatures.</p></section><section class="settings-category"><h3>Notifications</h3><label>Adresse de réception des rappels</label><input id="notifyEmail" type="email"><label><input id="notifyEnabled" type="checkbox" style="width:auto"> Activer les rappels automatiques</label><label>Heure d’envoi des rappels</label><input id="notifyTime" type="time" value="09:00"><p>Heure locale de l’ordinateur serveur. Vérification chaque minute ; si le serveur était arrêté, les rappels en attente seront envoyés après sa reprise, une fois cette heure atteinte.</p><label>Rappels d’entretien (jours avant)</label><input id="interviewReminders" placeholder="7, 1"><p>Indiquez les nombres de jours séparés par des virgules : par exemple « 7, 1 » pour une semaine et un jour avant.</p><p>Un rappel par candidature et par date de relance, y compris les relances déjà dépassées. Le serveur doit rester allumé.</p></section><div id="adminSettings"><section class="settings-category"><h3>Administration</h3><label><input id="registration_enabled" type="checkbox" style="width:auto"> Autoriser les nouvelles inscriptions</label></section><section class="settings-category"><h3>Configuration SMTP</h3><p>Configuration actuelle récupérée du serveur. Le mot de passe enregistré n’est jamais affiché.</p><label>Serveur SMTP</label><input id="smtp_host"><label>Port</label><input id="smtp_port" type="number" min="1" max="65535"><label>Sécurité</label><select id="smtp_security"><option value="starttls">STARTTLS (généralement 587)</option><option value="ssl">SSL/TLS (généralement 465)</option></select><label>Adresse expéditeur</label><input id="smtp_from" type="email"><label>Identifiant SMTP</label><input id="smtp_user" autocomplete="off"><label>Mot de passe SMTP / mot de passe d’application</label><input id="smtp_password" type="password" autocomplete="new-password" placeholder="Laisser vide pour conserver le mot de passe"><label><input id="clear_smtp_password" type="checkbox" style="width:auto"> Effacer le mot de passe enregistré</label><p id="smtpSecretState"></p><button id="testMailButton" type="button" onclick="sendTestMail()">Envoyer un mail de test</button><p id="testMailResult" role="status" aria-live="polite"></p><small>Le test utilise les paramètres déjà enregistrés. Enregistrez vos modifications avant de tester.</small><p>Attention : la base SQLite contient le secret SMTP non chiffré. Protégez le fichier et utilisez HTTPS avant de saisir des identifiants depuis un autre appareil.</p></section><section class="settings-category"><h3>Modèle de rappel</h3><label>Objet du mail</label><input id="mail_subject"><label>Contenu du mail (texte brut)</label><textarea id="mail_body" rows="7"></textarea><p>Variables : {entreprise}, {poste}, {date_relance}, {date_envoi}, {moyen}, {contact}, {notes}.</p></section><section class="settings-category"><h3>Modèle du mail de rappel d’entretien</h3><label for="interview_mail_subject">Objet du mail</label><input id="interview_mail_subject"><label for="interview_mail_body">Contenu du mail (texte brut)</label><textarea id="interview_mail_body" rows="8"></textarea><p>Variables : {entreprise}, {poste}, {date_entretien}, {heure_entretien}, {type_entretien}, {adresse_entretien}, {jours_restants}, {contact}, {notes}, {date_envoi}, {date_relance}, {moyen}.</p><p>Ce modèle est utilisé pour tous les rappels d’entretien et tous les comptes.</p></section></div><button onclick="storeSettings()">Enregistrer</button> <button class="ghost" onclick="selectTab("home")">Annuler</button><p id="settingsError" class="error"></p>`;document.querySelector('.grid').before(panel);document.querySelector('#methodList').value=preferences.methods.join(String.fromCharCode(10));document.querySelector('#followupDays').value=preferences.followup_days??7;document.querySelector('#notifyEmail').value=preferences.notify_email;document.querySelector('#notifyEnabled').checked=!!preferences.enabled;document.querySelector('#notifyTime').value=preferences.notify_time||'09:00';document.querySelector('#interviewReminders').value=preferences.interview_reminders||'7,1';document.querySelector('#adminSettings').hidden=!preferences.is_admin;document.querySelector('#registration_enabled').checked=!!preferences.registration_enabled;for(const key of ['smtp_host','smtp_port','smtp_security','smtp_from','smtp_user','mail_subject','mail_body','interview_mail_subject','interview_mail_body'])document.getElementById(key).value=preferences[key]??'';document.querySelector('#smtpSecretState').textContent=preferences.smtp_password_saved?'Un mot de passe est déjà enregistré.':'Aucun mot de passe enregistré.'}catch(e){alert(e.message)}}
|
||
async function sendTestMail(){const button=document.querySelector('#testMailButton');const result=document.querySelector('#testMailResult');button.disabled=true;result.textContent='Envoi en cours…';try{const data=await api('/api/mail/test','POST',{});result.textContent=data.message;result.className=''}catch(e){result.textContent=e.message;result.className='error'}finally{button.disabled=false}}
|
||
async function storeSettings(){try{await api('/api/settings','POST',{methods:document.querySelector('#methodList').value.split(String.fromCharCode(10)).map(x=>x.trim()).filter(Boolean),followup_days:Number(document.querySelector('#followupDays').value),notify_email:document.querySelector('#notifyEmail').value,enabled:document.querySelector('#notifyEnabled').checked,notify_time:document.querySelector('#notifyTime').value,interview_reminders:document.querySelector('#interviewReminders').value,...(preferences.is_admin?{...Object.fromEntries(['smtp_host','smtp_port','smtp_security','smtp_from','smtp_user','smtp_password','mail_subject','mail_body','interview_mail_subject','interview_mail_body'].map(k=>[k,document.getElementById(k).value])),clear_smtp_password:document.querySelector('#clear_smtp_password').checked,registration_enabled:document.querySelector('#registration_enabled').checked}:{})});await load()}catch(e){document.querySelector('#settingsError').textContent=e.message}}
|
||
const shareToken=new URLSearchParams(location.hash.slice(1)).get('partage')||'';
|
||
async function api(path, method='GET', body){const r=await fetch(path,{method,headers:{'Content-Type':'application/json',...(shareToken?{'X-Share-Token':shareToken}:{})},body:body?JSON.stringify(body):undefined});const data=await r.json();if(!r.ok)throw Error(data.error||'Erreur');return data}
|
||
let sharedLinks=[];
|
||
async function showShare(){try{sharedLinks=await api('/api/shares');document.querySelector('#sharePanel')?.remove();const panel=document.createElement('section');panel.id='sharePanel';panel.className='stat';panel.innerHTML=`<h2>Liens de partage</h2><p>Chaque lien donne accès au même tableau. Toute personne possédant le lien bénéficie de ses droits.</p><label>Nom du nouveau lien</label><input id="newShareLabel" maxlength="100" placeholder="Ex. Conseiller emploi"><label>Autorisation</label><select id="newSharePermission"><option value="read">Consultation uniquement</option><option value="edit">Modification autorisée</option></select><p><button onclick="createShare()">Créer un lien</button></p><div>${sharedLinks.map((s,i)=>`<section class="stat" style="margin-bottom:12px"><label>Nom</label><input id="shareName${i}" value="${esc(s.label)}" maxlength="100"><label>Droits</label><select id="sharePermission${i}"><option value="read" ${s.permission==='read'?'selected':''}>Consultation uniquement</option><option value="edit" ${s.permission==='edit'?'selected':''}>Modification autorisée</option></select><label>Lien</label><input id="shareUrl${i}" readonly value="${esc(location.origin+'/#partage='+encodeURIComponent(s.token))}"><p><button onclick="copyShare(${i})">Copier</button> <button class="ghost" onclick="updateShare(${i})">Enregistrer les droits</button> <button class="ghost" onclick="revokeShare(${i})">Révoquer</button></p></section>`).join('')||'<p>Aucun lien actif.</p>'}</div><small>Ouvrez cette page avec l’adresse réseau du serveur, pas localhost. Accès limité au réseau local.</small>`;document.querySelector('.grid').before(panel)}catch(e){alert(e.message)}}
|
||
async function createShare(){try{await api('/api/share','POST',{label:document.querySelector('#newShareLabel').value,permission:document.querySelector('#newSharePermission').value});await showShare()}catch(e){alert(e.message)}}
|
||
async function updateShare(i){try{await api('/api/share/update','POST',{token:sharedLinks[i].token,label:document.querySelector('#shareName'+i).value,permission:document.querySelector('#sharePermission'+i).value});await showShare()}catch(e){alert(e.message)}}
|
||
async function copyShare(i){const input=document.querySelector('#shareUrl'+i);input.select();try{await navigator.clipboard.writeText(input.value)}catch(e){document.execCommand('copy')}}
|
||
async function revokeShare(i){if(!confirm('Révoquer uniquement ce lien ?'))return;try{await api('/api/share/revoke','POST',{token:sharedLinks[i].token});await showShare()}catch(e){alert(e.message)}}
|
||
function esc(s){return String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
||
function login(){app.innerHTML=`<section class="auth"><img src="/favicon.png" alt="Logo CandiPilot" width="80" height="80" style="display:block;object-fit:contain;margin:0 auto 16px"><h2>CandiPilot</h2><p id="loginSubtitle" class="muted">Connectez-vous.</p><label>Adresse e-mail</label><input id="email" type="email" autocomplete="email"><label>Mot de passe</label><input id="password" type="password" autocomplete="current-password" onkeydown="if(event.key==="Enter"){event.preventDefault();if(!event.repeat)auth("login")}"><p id="err" class="error"></p><button onclick="auth('login')">Se connecter</button> <button id="registerButton" hidden class="ghost" onclick="registerPage()">Créer un compte</button><p><button id="forgotButton" hidden class="ghost" onclick="recoveryForm()">Mot de passe oublié</button></p></section>`;api('/api/auth/options').then(o=>{const r=document.querySelector('#registerButton'),f=document.querySelector('#forgotButton');if(r)r.hidden=!o.registration;const subtitle=document.querySelector('#loginSubtitle');if(subtitle)subtitle.textContent=o.registration?'Connectez-vous ou créez un compte.':'Connectez-vous.';if(f)f.hidden=!o.recovery}).catch(()=>{})}
|
||
async function auth(action){try{await api('/api/'+action,'POST',{email:email.value,password:password.value});load()}catch(e){err.textContent=e.message}}
|
||
async function registerPage(){try{const options=await api('/api/auth/options');if(!options.registration){login();return}app.innerHTML=`<section class="auth"><img src="/favicon.png" alt="Logo CandiPilot" width="80" height="80" style="display:block;object-fit:contain;margin:0 auto 16px"><h2>Créer un compte</h2><p class="muted">Votre compte CandiPilot</p><form id="registrationForm"><label for="registrationEmail">Adresse e-mail</label><input id="registrationEmail" type="email" required maxlength="254" autocomplete="email"><label for="registrationPassword">Mot de passe</label><input id="registrationPassword" type="password" required minlength="8" autocomplete="new-password"><label for="registrationConfirm">Confirmer le mot de passe</label><input id="registrationConfirm" type="password" required minlength="8" autocomplete="new-password"><p><small>Le mot de passe doit contenir au moins 8 caractères.</small></p><p id="registrationError" class="error" role="alert"></p><button type="submit">Créer mon compte</button> <button type="button" class="ghost" onclick="login()">Retour à la connexion</button></form></section>`;document.querySelector('#registrationForm').addEventListener('submit',async event=>{event.preventDefault();const button=event.target.querySelector('[type=submit]');const error=document.querySelector('#registrationError');error.textContent='';const password=document.querySelector('#registrationPassword').value;if(password!==document.querySelector('#registrationConfirm').value){error.textContent='Les mots de passe ne correspondent pas';return}button.disabled=true;try{await api('/api/register','POST',{email:document.querySelector('#registrationEmail').value.trim(),password});await load()}catch(e){error.textContent=e.message}finally{button.disabled=false}});document.querySelector('#registrationEmail').focus()}catch(e){const error=document.querySelector('#err');if(error)error.textContent=e.message}}
|
||
async function openUsers(){if(!preferences.is_admin)return;try{const users=await api('/api/users');const panel=document.createElement('section');panel.id='usersPanel';panel.className='stat';panel.innerHTML=`<h2>Utilisateurs</h2><label>E-mail du nouveau compte</label><input id="newUserEmail" type="email"><label>Mot de passe initial</label><input id="newUserPassword" type="password" autocomplete="new-password"><p><button onclick="createUser()">Ajouter un utilisateur</button></p><p>La suppression efface aussi les candidatures et les liens du compte. Le compte administrateur est protégé.</p>${users.map(u=>`<section class="stat" style="margin-bottom:12px"><b>${u.admin?'Administrateur':'Utilisateur'}</b><label>E-mail</label><input id="userEmail${u.id}" value="${esc(u.email)}"><label>Nouveau mot de passe (vide : conserver)</label><input id="userPassword${u.id}" type="password" autocomplete="new-password"><p><button onclick="updateUser(${u.id})">Enregistrer</button> ${u.admin?'':'<button class="ghost" onclick="deleteUser('+u.id+')">Supprimer</button>'}</p></section>`).join('')}`;document.querySelector('#usersPanel')?.remove();document.querySelector('.grid').before(panel)}catch(e){alert(e.message)}}
|
||
async function createUser(){try{await api('/api/users/create','POST',{email:document.querySelector('#newUserEmail').value,password:document.querySelector('#newUserPassword').value});await openUsers()}catch(e){alert(e.message)}}
|
||
async function updateUser(id){try{await api('/api/users/update','POST',{id,email:document.querySelector('#userEmail'+id).value,password:document.querySelector('#userPassword'+id).value});alert('Utilisateur modifié. Ses sessions ont été fermées.');try{await openUsers()}catch(e){login()}}catch(e){alert(e.message)}}
|
||
async function deleteUser(id){if(!confirm('Supprimer définitivement ce compte, ses candidatures et ses liens ?'))return;try{await api('/api/users/delete','POST',{id});await openUsers()}catch(e){alert(e.message)}}
|
||
let recoveryState={email:'',token:''};
|
||
function recoveryForm(){recoveryState={email:document.querySelector('#email')?.value.trim()||'',token:''};recoveryStep(1)}
|
||
function recoveryStep(step,message=''){app.innerHTML=`<section class="auth"><img src="/favicon.png" alt="Logo CandiPilot" width="80" height="80" style="display:block;object-fit:contain;margin:0 auto 16px"><h2>Mot de passe oublié</h2><p class="muted">Étape ${step} sur 3 — ${['Adresse mail','Vérification du code','Nouveau mot de passe'][step-1]}</p><form id="recoveryForm">${step===1?`<label for="recoveryEmail">Adresse e-mail du compte</label><input id="recoveryEmail" type="email" required autocomplete="email" value="${esc(recoveryState.email)}"><p><button id="requestCode" type="submit">Recevoir un code par mail</button></p>`:step===2?`<p>Consultez votre boîte mail et les indésirables. Le code est valable 30 minutes.</p><label for="recoveryCode">Code reçu par mail</label><input id="recoveryCode" required autocomplete="one-time-code" value="${esc(recoveryState.token)}"><p><button type="submit">Vérifier le code</button> <button type="button" class="ghost" onclick="recoveryStep(1)">Modifier l’adresse / renvoyer</button></p>`:`<label for="recoveryPassword">Nouveau mot de passe</label><input id="recoveryPassword" type="password" required minlength="8" autocomplete="new-password"><label for="recoveryConfirm">Confirmer le mot de passe</label><input id="recoveryConfirm" type="password" required minlength="8" autocomplete="new-password"><p><small>Au moins 8 caractères.</small></p><p><button type="submit">Enregistrer le nouveau mot de passe</button> <button type="button" class="ghost" onclick="recoveryStep(2)">Retour au code</button></p>`}<button type="button" class="ghost" onclick="recoveryState={email:'',token:''};login()">Retour à la connexion</button><p id="recoveryMessage" role="status" aria-live="polite">${esc(message)}</p></form></section>`;document.querySelector('#recoveryForm').addEventListener('submit',async event=>{event.preventDefault();const button=event.target.querySelector('[type=submit]');button.disabled=true;try{if(step===1)await requestRecovery();else if(step===2){recoveryState.token=document.querySelector('#recoveryCode').value.trim();await api('/api/reset/verify','POST',{token:recoveryState.token});recoveryStep(3)}else await resetPassword()}catch(e){const output=document.querySelector('#recoveryMessage');if(output){output.className='error';output.textContent=e.message}}finally{button.disabled=false}});document.querySelector(step===1?'#recoveryEmail':step===2?'#recoveryCode':'#recoveryPassword').focus()}
|
||
async function requestRecovery(){recoveryState.email=document.querySelector('#recoveryEmail').value.trim();const r=await api('/api/forgot','POST',{email:recoveryState.email});recoveryState.token='';recoveryStep(2,r.message)}
|
||
async function resetPassword(){const password=document.querySelector('#recoveryPassword').value;if(password!==document.querySelector('#recoveryConfirm').value)throw Error('Les mots de passe ne correspondent pas');const r=await api('/api/reset','POST',{token:recoveryState.token,password});recoveryState={email:'',token:''};login();const message=document.querySelector('#err');message.className='muted';message.textContent=r.message}
|
||
let currentPage=1;const pageSize=10;let searchTerm='';let statusFilter='';
|
||
function matchingRows(){const q=searchTerm.trim().toLocaleLowerCase('fr');return rows.filter(r=>(!q||[r.company,r.role,r.location,r.contact,r.method,r.status,r.notes,r.sent_date,r.followup_date].join(' ').toLocaleLowerCase('fr').includes(q))&&(!statusFilter||r.status===statusFilter))}
|
||
function exportTable(){const data=matchingRows();if(!data.length){alert('Aucune candidature à exporter.');return}const columns=[['Entreprise','company'],['Poste','role'],['Ville / télétravail','location'],['Contact / annonce','contact'],['Moyen','method'],['Date d’envoi','sent_date'],['Date de relance','followup_date'],['Statut','status'],['Notes','notes'],['Date et heure de l’entretien','interview_at'],['Type de rendez-vous','interview_type'],['Adresse de l’entretien','interview_address']];const cell=value=>{let text=String(value??'');if(/^[=+@-]/.test(text.trimStart()))text="'"+text;return '"'+text.replaceAll('"','""')+'"'};const lines=[columns.map(c=>cell(c[0])).join(';'),...data.map(r=>columns.map(c=>cell(r[c[1]])).join(';'))];const csv=String.fromCharCode(65279)+lines.join(String.fromCharCode(13,10));const url=URL.createObjectURL(new Blob([csv],{type:'text/csv;charset=utf-8;'}));const link=document.createElement('a');const now=new Date();const stamp=[now.getFullYear(),String(now.getMonth()+1).padStart(2,'0'),String(now.getDate()).padStart(2,'0')].join('-');link.href=url;link.download='CandiPilot-candidatures-'+stamp+'.csv';document.body.appendChild(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000)}
|
||
function setSearch(value){const field=document.activeElement;const start=field?.selectionStart??value.length;const end=field?.selectionEnd??value.length;searchTerm=value;currentPage=1;dashboard();requestAnimationFrame(()=>{const search=document.querySelector('.toolbar input[type="search"]');if(search){search.focus();search.setSelectionRange(start,end)}})}
|
||
function setStatusFilter(value){statusFilter=value;currentPage=1;dashboard()}
|
||
function goPage(page){currentPage=page;dashboard();document.querySelector('.toolbar input')?.focus()}
|
||
function pagination(filtered){const pages=Math.max(1,Math.ceil(filtered.length/pageSize));currentPage=Math.min(currentPage,pages);if(pages===1)return '';const buttons=Array.from({length:pages},(_,i)=>`<button class="ghost" aria-current="${currentPage===i+1?'page':'false'}" onclick="goPage(${i+1})">${i+1}</button>`).join('');return `<nav class="pagination" aria-label="Pages des candidatures"><span>${filtered.length} résultat${filtered.length>1?'s':''} · page ${currentPage} sur ${pages}</span><div class="pages"><button class="ghost" ${currentPage===1?'disabled':''} onclick="goPage(${currentPage-1})">Précédent</button>${buttons}<button class="ghost" ${currentPage===pages?'disabled':''} onclick="goPage(${currentPage+1})">Suivant</button></div></nav>`}
|
||
function sentCounts(){const today=new Date();today.setHours(0,0,0,0);const dateOf=r=>r.sent_date?new Date(r.sent_date+'T00:00:00'):null;const same=d=>d&&d.getTime()===today.getTime();const weekStart=new Date(today);weekStart.setDate(today.getDate()-(today.getDay()+6)%7);const month=today.getMonth(),year=today.getFullYear();return {day:rows.filter(r=>same(dateOf(r))).length,week:rows.filter(r=>{const d=dateOf(r);return d&&d>=weekStart&&d<=today}).length,month:rows.filter(r=>{const d=dateOf(r);return d&&d.getMonth()===month&&d.getFullYear()===year}).length,year:rows.filter(r=>{const d=dateOf(r);return d&&d.getFullYear()===year}).length}}
|
||
function stats(){const count=s=>rows.filter(x=>x.status===s).length;const sent=sentCounts(),follow=count('À relancer'),interviews=count('Entretien');const now=new Date(),next=rows.filter(r=>r.status==='Entretien'&&r.interview_at&&new Date(r.interview_at)>=now).sort((a,b)=>new Date(a.interview_at)-new Date(b.interview_at))[0];const days=next?Math.ceil((new Date(next.interview_at)-now)/86400000):null;const when=next?new Intl.DateTimeFormat('fr-FR',{dateStyle:'medium',timeStyle:'short'}).format(new Date(next.interview_at)):'';const place=next?(next.interview_type==='Visio'?'Visio':next.interview_address||'Présentiel'):'';return `<section class="grid"><div class="stat"><b>${rows.length}</b>Candidatures</div><div class="stat ${sent.day>0?'success':''}"><b>+${sent.day}</b>Envoyée${sent.day>1?'s':''} aujourd’hui</div><div class="stat ${follow?'alert':''}"><b>${follow}</b>À relancer</div><div class="stat ${interviews?'success':''}"><b>${interviews}</b>Entretiens</div><div class="stat"><b>${count('Refusée')}</b>Refusées</div>${next?`<div class="stat ${days>0?'success':''}"><b>${new Date(next.interview_at).toDateString()===now.toDateString()?Math.floor(Math.max(0,new Date(next.interview_at)-now)/3600000)+' h '+String(Math.floor(Math.max(0,new Date(next.interview_at)-now)/60000)%60).padStart(2,'0')+' min':days+' jour'+(days>1?'s':'')}</b>Prochain entretien<br><small>${esc(next.company)} · ${when}<br>${esc(place)}</small></div>`:''}</section>`}
|
||
function chart(title,items){const max=Math.max(1,...items.map(x=>x.value));return `<section class="stat" style="margin-top:16px"><h3 style="margin-top:0">${title}</h3><div style="display:flex;align-items:end;gap:7px;height:190px;border-bottom:1px solid var(--line);padding:8px 4px 0">${items.map(x=>`<div style="flex:1;min-width:0;height:100%;display:flex;flex-direction:column;justify-content:end;align-items:center;gap:5px"><b style="font-size:13px">${x.value}</b><div title="${esc(x.label)} : ${x.value}" style="width:100%;max-width:44px;height:${Math.max(x.value?8:2,Math.round(x.value/max*135))}px;background:var(--accent);border-radius:6px 6px 0 0"></div><small style="font-size:11px;white-space:nowrap">${esc(x.short)}</small></div>`).join('')}</div></section>`}
|
||
function openStatistics(){const sent=sentCounts(),today=new Date();today.setHours(0,0,0,0);const dateOf=r=>r.sent_date?new Date(r.sent_date+'T00:00:00'):null;const count=(start,end)=>rows.filter(r=>{const d=dateOf(r);return d&&d>=start&&d<=end}).length;const dayNames=['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];const monday=new Date(today);monday.setDate(today.getDate()-(today.getDay()+6)%7);const daily=Array.from({length:7},(_,i)=>{const d=new Date(monday);d.setDate(monday.getDate()+i);return {label:new Intl.DateTimeFormat('fr-FR',{weekday:'long',day:'numeric'}).format(d),short:`${dayNames[i]} ${String(d.getDate()).padStart(2,'0')}`,value:count(d,d)}});const weeks=Array.from({length:5},(_,i)=>{const end=new Date(today);end.setDate(today.getDate()-(4-i)*7);const start=new Date(end);start.setDate(end.getDate()-6);return {label:`Semaine du ${new Intl.DateTimeFormat('fr-FR',{day:'2-digit',month:'short'}).format(start)}`,short:new Intl.DateTimeFormat('fr-FR',{day:'2-digit',month:'2-digit'}).format(start),value:count(start,end)}});const monthNames=['Jan','Fév','Mar','Avr','Mai','Juin','Juil','Août','Sep','Oct','Nov','Déc'];const monthly=Array.from({length:12},(_,i)=>{const start=new Date(today.getFullYear(),i,1),end=new Date(today.getFullYear(),i+1,0);return {label:monthNames[i]+' '+today.getFullYear(),short:monthNames[i],value:count(start,end)}});document.querySelector('#statisticsPanel')?.remove();const panel=document.createElement('section');panel.id='statisticsPanel';panel.className='stat';panel.innerHTML=`<h2>Statistiques des candidatures envoyées</h2><p class="muted">Calculées à partir de la date d’envoi de chaque candidature.</p><section class="grid"><div class="stat ${sent.day>0?'success':''}"><b>${sent.day}</b>AUJOURD’HUI</div><div class="stat ${sent.week>0?'success':''}"><b>${sent.week}</b>CETTE SEMAINE</div><div class="stat ${sent.month>0?'success':''}"><b>${sent.month}</b>CE MOIS-CI</div><div class="stat ${sent.year>0?'success':''}"><b>${sent.year}</b>CETTE ANNÉE</div></section>${chart('Candidatures par jour — semaine en cours',daily)}${chart('Candidatures par semaine — cinq dernières semaines',weeks)}${chart('Candidatures par mois — année en cours',monthly)}`;document.querySelector('.grid').before(panel)}
|
||
function selectTab(tab){if(shareToken&&tab!=='home'&&tab!=='statistics')return;if(tab==='users'&&!preferences.is_admin)return;document.querySelector('#usersPanel')?.remove();document.querySelector('#settingsPanel')?.remove();document.querySelector('#sharePanel')?.remove();document.querySelector('#statisticsPanel')?.remove();const home=tab==='home';document.querySelectorAll('.grid,.toolbar,.new,.box,.pagination').forEach(el=>el.hidden=!home);document.querySelectorAll('[data-tab]').forEach(el=>{const active=el.dataset.tab===tab;el.classList.toggle('ghost',!active);el.setAttribute('aria-selected',String(active))});if(tab==='statistics')openStatistics();if(tab==='settings')openSettings();if(tab==='share')showShare();if(tab==='users')openUsers()}
|
||
function interviewDialog(id,previousDate='',previousStatus='Envoyée'){if(!preferences.can_edit)return;const current=rows.find(r=>r.id===id)||{};const previousType=current.interview_type||'Présentiel';const dialog=document.createElement('dialog');dialog.id='interviewDialog';dialog.style.cssText='width:min(460px,calc(100% - 24px));border:1px solid var(--line);border-radius:14px;background:var(--card);color:var(--ink);padding:22px';dialog.innerHTML=`<form method="dialog"><h2>Planifier l’entretien</h2><p>Indiquez la date et l’heure du rendez-vous pour recevoir les rappels configurés.</p><label for="interviewType">Type de rendez-vous *</label><select id="interviewType" required>${['Présentiel','Visio'].map(t=>`<option value="${t}" ${previousType===t?'selected':''}>${t}</option>`).join('')}</select><div id="interviewAddressWrap"><label for="interviewAddress">Adresse *</label><input id="interviewAddress" maxlength="300" value="${esc(current.interview_address||'')}" placeholder="Adresse du rendez-vous"></div><label>Date et heure *</label><input id="interviewAt" type="datetime-local" required value="${esc(previousDate)}"><p id="interviewError" class="error"></p><div style="display:flex;gap:10px;flex-wrap:wrap"><button value="save">Enregistrer</button><button class="ghost" value="cancel" formnovalidate>Annuler</button></div></form>`;app.appendChild(dialog);const typeInput=dialog.querySelector('#interviewType'),addressWrap=dialog.querySelector('#interviewAddressWrap'),addressInput=dialog.querySelector('#interviewAddress');const toggleAddress=()=>{const physical=typeInput.value==='Présentiel';addressWrap.hidden=!physical;addressInput.required=physical};typeInput.addEventListener('change',toggleAddress);toggleAddress();dialog.addEventListener('close',async()=>{const value=dialog.returnValue==='save'?dialog.querySelector('#interviewAt').value:'';const interviewType=typeInput.value;const interviewAddress=addressInput.value.trim();dialog.remove();if(!value){dashboard();return}if(interviewType==='Présentiel'&&!interviewAddress){alert('Indiquez l’adresse du rendez-vous');dashboard();return}try{await api('/api/applications/'+id,'PUT',{status:'Entretien',interview_at:value,interview_type:interviewType,interview_address:interviewType==='Visio'?'':interviewAddress});await load()}catch(e){alert(e.message)}});dialog.showModal()}
|
||
function changeStatus(id,value,previous){if(value==='Entretien'&&previous!=='Entretien'){interviewDialog(id,'',previous);return}save(id,'status',value)}
|
||
function field(r,k,type='text'){return `<input type="${type}" value="${esc(r[k])}" onchange="save(${r.id},'${k}',this.value)">`}
|
||
function dashboard(){const filtered=matchingRows();const totalPages=Math.max(1,Math.ceil(filtered.length/pageSize));currentPage=Math.min(currentPage,totalPages);const visibleRows=filtered.slice((currentPage-1)*pageSize,currentPage*pageSize);app.innerHTML=`<div class="wrap"><header class="bar"><div><h1>CandiPilot</h1><p class="muted" style="font-size:16px;margin-bottom:2px">Mes candidatures</p><small class="muted" style="margin:0">Version __VERSION__</small></div>${shareToken?`<span class="muted">Partagé par ${esc(preferences.share_owner||'un utilisateur')} · ${preferences.can_edit?'modification autorisée':'consultation uniquement'}</span>`:`<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;min-width:0"><span class="muted" style="overflow-wrap:anywhere;margin:0;align-self:center;line-height:1.4">${esc(preferences.account_name||'')}</span><button class="ghost" onclick="api("/api/logout","POST").then(login)">Déconnexion</button></div>`}</header><nav role="tablist" aria-label="Navigation" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:20px"><button role="tab" data-tab="home" aria-selected="true" onclick="selectTab("home")">Accueil</button><button role="tab" data-tab="statistics" aria-selected="false" class="ghost" onclick="selectTab("statistics")">Statistiques</button>${shareToken?'':'<button role="tab" data-tab="settings" aria-selected="false" class="ghost" onclick="selectTab("settings")">Paramètres</button><button role="tab" data-tab="share" aria-selected="false" class="ghost" onclick="selectTab("share")">Partage</button>'}${preferences.is_admin?'<button role="tab" data-tab="users" aria-selected="false" class="ghost" onclick="selectTab("users")">Utilisateurs</button>':''}</nav>${stats()}<div class="toolbar" style="align-items:center"><input type="search" value="${esc(searchTerm)}" oninput="setSearch(this.value)" placeholder="Rechercher une entreprise, un poste, un statut…" aria-label="Rechercher une candidature"><select onchange="setStatusFilter(this.value)" aria-label="Filtrer par statut"><option value="">Tous les statuts</option>${['Envoyée','À relancer','Entretien','Refusée','Acceptée'].map(s=>`<option value="${s}" ${statusFilter===s?'selected':''}>${s}</option>`).join('')}</select><button class="new" style="margin:0;min-height:44px;align-self:center" onclick="createRow()">+ Ajouter une candidature</button><button class="ghost" style="margin:0;min-height:44px;align-self:center" onclick="exportTable()" title="Exporter toutes les lignes correspondant à la recherche et au filtre">Exporter en CSV</button></div><div class="box"><table><thead><tr><th>Entreprise</th><th>Poste</th><th>Ville / télétravail</th><th>Contact / annonce</th><th>Moyen</th><th>Envoi</th><th>Relance</th><th>Statut</th><th>Notes</th><th></th></tr></thead><tbody>${visibleRows.length?visibleRows.map(r=>`<tr><td>${field(r,'company')}</td><td>${field(r,'role')}</td><td>${field(r,'location')}</td><td>${field(r,'contact')}</td><td><select onchange="save(${r.id},'method',this.value)">${[...new Set([...preferences.methods,r.method])].map(x=>`<option value="${esc(x)}" ${r.method===x?'selected':''}>${esc(x)}</option>`).join('')}</select></td><td>${field(r,'sent_date','date')}</td><td>${field(r,'followup_date','date')}</td><td><select onchange="changeStatus(${r.id},this.value,'${esc(r.status)}')">${['Envoyée','À relancer','Entretien','Refusée','Acceptée'].map(x=>`<option ${r.status===x?'selected':''}>${x}</option>`).join('')}</select></td><td>${field(r,'notes')}</td><td><div class="action-buttons">${preferences.can_edit&&r.status==='Entretien'?`<button class="ghost" onclick="interviewDialog(${r.id},'${esc(r.interview_at||'')}','Entretien')">Modifier le rendez-vous</button>`:''}<button class="delete" onclick="removeRow(${r.id})">Supprimer</button></div></td></tr>`).join(''):`<tr><td colspan="10" style="text-align:center;color:var(--muted);padding:24px">Aucune candidature ne correspond à la recherche.</td></tr>`}</tbody></table></div>${pagination(filtered)}</div>`;if(shareToken){document.querySelector('.bar span').textContent=`Partagé par ${preferences.share_owner||'un utilisateur'} · ${preferences.can_edit?'modification autorisée':'consultation uniquement'}`}if(!preferences.can_edit){document.querySelectorAll('.box input,.box select').forEach(el=>el.disabled=true);document.querySelectorAll('.new,.box .delete').forEach(el=>el.style.display='none')}}
|
||
async function load(){preferences=await api('/api/settings');rows=await api('/api/applications');dashboard()}function createRow(){if(!preferences.can_edit)return;document.querySelector('#applicationDialog')?.remove();const dialog=document.createElement('dialog');dialog.id='applicationDialog';dialog.style.cssText='width: min(600px, calc(100% - 24px));max-height:90vh;overflow:auto;border:1px solid var(--line);border-radius:14px;background:var(--card);color:var(--ink);padding:22px';const today=new Date();const later=new Date(today);later.setDate(later.getDate()+Number(preferences.followup_days??7));const localDate=d=>[d.getFullYear(),String(d.getMonth()+1).padStart(2,'0'),String(d.getDate()).padStart(2,'0')].join('-');dialog.innerHTML=`<form id="applicationForm"><h2>Nouvelle candidature</h2><label>Entreprise *</label><input name="company" required maxlength="200"><label>Poste recherché</label><input name="role"><label>Ville / télétravail</label><input name="location"><label>Contact / lien de l’annonce</label><input name="contact"><label>Moyen de candidature</label><select name="method">${preferences.methods.map(m=>`<option value="${esc(m)}">${esc(m)}</option>`).join('')}</select><label>Date d’envoi</label><input name="sent_date" type="date" value="${localDate(today)}"><label>Date de relance</label><input name="followup_date" type="date" value="${localDate(later)}"><label>Statut</label><select name="status">${['Envoyée','À relancer','Entretien','Refusée','Acceptée'].map(s=>`<option>${s}</option>`).join('')}</select><label>Notes</label><textarea name="notes" rows="3"></textarea><p id="applicationError" class="error" role="alert"></p><div style="display:flex;gap:10px;flex-wrap:wrap"><button type="submit">Ajouter la candidature</button><button type="button" class="ghost" onclick="document.getElementById("applicationDialog").close()">Annuler</button></div></form>`;app.appendChild(dialog);dialog.addEventListener('close',()=>dialog.remove());dialog.querySelector('form').addEventListener('submit',async event=>{event.preventDefault();const form=event.target;const button=form.querySelector('[type=submit]');button.disabled=true;try{const data=Object.fromEntries(new FormData(form));data.company=data.company.trim();if(!data.company)throw Error('Indiquez le nom de l’entreprise');await api('/api/applications','POST',data);dialog.close();await load()}catch(e){const error=document.querySelector('#applicationError');if(error)error.textContent=e.message}finally{button.disabled=false}});dialog.showModal()}async function save(id,key,value){try{await api('/api/applications/'+id,'PUT',{[key]:value});rows.find(x=>x.id===id)[key]=value;const summary=document.querySelector('.grid');if(summary)summary.outerHTML=stats()}catch(e){alert('Enregistrement impossible : '+e.message)}}async function removeRow(id){await api('/api/applications/'+id,'DELETE');load()}load().catch(()=>{if(shareToken){app.innerHTML='<section class="auth"><h2>Lien indisponible</h2><p>Ce lien de partage est invalide ou a été révoqué.</p></section>'}else login()}); setInterval(async()=>{if(!document.querySelector('.box')||document.querySelector('.box').hidden||document.querySelector('#applicationDialog')||document.querySelector('#settingsPanel')||document.activeElement.matches('input,select,textarea'))return;try{const freshPreferences=await api('/api/settings');const latest=await api('/api/applications');const changed=JSON.stringify(freshPreferences)!==JSON.stringify(preferences)||JSON.stringify(latest)!==JSON.stringify(rows);preferences=freshPreferences;if(changed){rows=latest;dashboard()}}catch(e){if(shareToken){app.innerHTML='<section class="auth"><h2>Accès retiré</h2><p>Le lien de partage n’est plus disponible.</p></section>'}else console.error(e.message)}},10000);
|
||
function addPasswordEyes(){const headers=[...app.querySelectorAll('.box th')].map(el=>el.textContent);app.querySelectorAll('.box tbody tr').forEach(tr=>[...tr.cells].forEach((cell,i)=>{const label=headers[i]||'';if(cell.getAttribute('data-label')!==label)cell.setAttribute('data-label',label)}));app.querySelectorAll('input[type="password"]').forEach(input=>{if(input.dataset.eyeReady)return;input.dataset.eyeReady='true';const wrap=document.createElement('div');wrap.style.cssText='position:relative;display:flex;align-items:center';input.parentNode.insertBefore(wrap,input);wrap.appendChild(input);input.style.paddingRight='48px';const button=document.createElement('button');button.type='button';button.className='ghost';button.style.cssText='position:absolute;right:4px;top:50%;transform:translateY(-50%);padding:6px;border:0;background:transparent;color:var(--ink);display:flex;align-items:center;justify-content:center';const draw=()=>{const visible=input.type==='text';button.setAttribute('aria-label',visible?'Masquer le mot de passe':'Afficher le mot de passe');button.title=visible?'Masquer le mot de passe':'Afficher le mot de passe';button.setAttribute('aria-pressed',String(visible));button.innerHTML='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/>'+(visible?'<path d="M3 3l18 18"/>':'')+'</svg>'};button.addEventListener('click',()=>{input.type=input.type==='password'?'text':'password';draw();input.focus()});draw();wrap.appendChild(button)})}
|
||
new MutationObserver(addPasswordEyes).observe(app,{childList:true,subtree:true});addPasswordEyes();
|
||
</script></body></html>'''.replace('__VERSION__', VERSION)
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
def log_message(self, *args): pass
|
||
def json(self, data, status=200, cookie=None):
|
||
raw=json.dumps(data).encode(); self.send_response(status); self.send_header('Content-Type','application/json'); self.send_header('Content-Length',str(len(raw)))
|
||
if cookie: self.send_header('Set-Cookie',cookie)
|
||
self.end_headers(); self.wfile.write(raw)
|
||
def owner(self):
|
||
import time
|
||
c=SimpleCookie(self.headers.get('Cookie')); token=c.get('session')
|
||
if not token:return None
|
||
with db() as con:
|
||
row=con.execute('SELECT user_id,expires FROM sessions WHERE token=?',(token.value,)).fetchone()
|
||
if not row or row['expires']<=time.time():
|
||
con.execute('DELETE FROM sessions WHERE token=?',(token.value,));return None
|
||
con.execute('UPDATE sessions SET expires=? WHERE token=?',(time.time()+2592000,token.value))
|
||
return row['user_id']
|
||
def shared(self):
|
||
token=self.headers.get('X-Share-Token','')
|
||
if not token:return None
|
||
with db() as con:return con.execute('SELECT * FROM share_links WHERE token=?',(token,)).fetchone()
|
||
def user(self):
|
||
if self.headers.get('X-Share-Token'):
|
||
shared=self.shared()
|
||
return shared['user_id'] if shared else None
|
||
return self.owner()
|
||
def can_edit(self):
|
||
if self.headers.get('X-Share-Token'):
|
||
shared=self.shared()
|
||
return bool(shared and shared['permission']=='edit')
|
||
return bool(self.owner())
|
||
def body(self):
|
||
n=int(self.headers.get('Content-Length',0)); return json.loads(self.rfile.read(n) or b'{}')
|
||
def do_GET(self):
|
||
if urlparse(self.path).path in ('/favicon.png','/favicon.ico'):
|
||
favicon_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'favicon.png')
|
||
try:
|
||
with open(favicon_path,'rb') as favicon:raw=favicon.read()
|
||
except FileNotFoundError:
|
||
self.send_error(404,'Placez favicon.png dans le dossier du script');return
|
||
except OSError:
|
||
self.send_error(500,'Lecture de la favicon impossible');return
|
||
self.send_response(200)
|
||
self.send_header('Content-Type','image/png')
|
||
self.send_header('Content-Length',str(len(raw)))
|
||
self.send_header('Cache-Control','no-cache')
|
||
self.send_header('X-Content-Type-Options','nosniff')
|
||
self.end_headers();self.wfile.write(raw);return
|
||
if urlparse(self.path).path=='/':
|
||
raw=page().encode(); self.send_response(200);self.send_header('Content-Type','text/html; charset=utf-8');self.end_headers();self.wfile.write(raw);return
|
||
if self.path=='/api/auth/options':
|
||
cfg=mail_settings(admin_id());return self.json({'recovery':bool(cfg['smtp_host'] and cfg['smtp_from']),'registration':registration_enabled()})
|
||
if self.path=='/api/users':
|
||
uid=self.owner()
|
||
if not uid or uid!=admin_id() or self.headers.get('X-Share-Token'):return self.json({'error':'Action réservée à l’administrateur'},403)
|
||
with db() as con:users=[{'id':r['id'],'email':r['email'],'admin':r['id']==uid} for r in con.execute('SELECT id,email FROM users ORDER BY id')]
|
||
return self.json(users)
|
||
if self.path=='/api/shares':
|
||
uid=self.owner()
|
||
if not uid or self.headers.get('X-Share-Token'):return self.json({'error':'Action réservée au propriétaire'},403)
|
||
with db() as con: links=[dict(r) for r in con.execute('SELECT token,label,permission FROM share_links WHERE user_id=? ORDER BY rowid DESC',(uid,))]
|
||
return self.json(links)
|
||
if self.path=='/api/settings':
|
||
uid=self.user()
|
||
if not uid:return self.json({'error':'Non connecté'},401)
|
||
s=get_settings(uid); s['methods']=json.loads(s['methods'])
|
||
s['can_edit']=self.can_edit()
|
||
cfg=mail_settings(uid)
|
||
s['smtp_ready']=bool(cfg['smtp_host'] and cfg['smtp_from'])
|
||
s['is_admin']=uid==admin_id() and not bool(self.headers.get('X-Share-Token'))
|
||
s['registration_enabled']=registration_enabled() if s['is_admin'] else None
|
||
if not self.headers.get('X-Share-Token'):
|
||
with db() as con:account=con.execute('SELECT email FROM users WHERE id=?',(uid,)).fetchone()
|
||
s['account_name']=account['email'] if account else ''
|
||
if s['is_admin']:
|
||
s.update({k:v for k,v in cfg.items() if k!='smtp_password'})
|
||
s['smtp_password_saved']=bool(cfg['smtp_password'])
|
||
if self.headers.get('X-Share-Token'):
|
||
with db() as con:owner=con.execute('SELECT email FROM users WHERE id=?',(uid,)).fetchone()
|
||
s['share_owner']=owner['email'] if owner else ''
|
||
s['notify_email']=''; s['enabled']=0
|
||
return self.json(s)
|
||
if self.path=='/api/applications':
|
||
uid=self.user()
|
||
if not uid:return self.json({'error':'Non connecté'},401)
|
||
from datetime import date
|
||
with db() as con:
|
||
con.execute("UPDATE applications SET status='À relancer' WHERE user_id=? AND status='Envoyée' AND followup_date<>'' AND followup_date<=?", (uid, date.today().isoformat()))
|
||
data=[dict(x) for x in con.execute('SELECT * FROM applications WHERE user_id=? ORDER BY id DESC',(uid,))]
|
||
return self.json(data)
|
||
self.json({'error':'Introuvable'},404)
|
||
def do_POST(self):
|
||
path=urlparse(self.path).path
|
||
if path=='/api/forgot':
|
||
import time,threading
|
||
cfg=mail_settings(admin_id())
|
||
if not cfg['smtp_host'] or not cfg['smtp_from']:return self.json({'error':'Récupération indisponible : serveur mail non configuré'},400)
|
||
x=self.body();email=str(x.get('email','')).strip().lower();now=time.time();key=self.client_address[0]
|
||
if now-RESET_LIMIT.get(key,0)<60:return self.json({'error':'Attendez une minute avant une nouvelle demande'},429)
|
||
RESET_LIMIT[key]=now
|
||
with db() as con:
|
||
recovery_tables(con);u=con.execute('SELECT id FROM users WHERE email=?',(email,)).fetchone()
|
||
if not u:return self.json({'error':'Adresse mail inconnue'},400)
|
||
if u:
|
||
token=secrets.token_urlsafe(32);con.execute('DELETE FROM password_resets WHERE user_id=? OR expires<?',(u['id'],now));con.execute('INSERT INTO password_resets VALUES(?,?,?)',(hashlib.sha256(token.encode()).hexdigest(),u['id'],now+1800))
|
||
if u:
|
||
def deliver():
|
||
try:send_recovery(email,token)
|
||
except Exception:print('Échec SMTP du mail de récupération',flush=True)
|
||
threading.Thread(target=deliver,daemon=True).start()
|
||
return self.json({'message':'Si cette adresse correspond à un compte, un code de récupération sera envoyé. Vérifiez aussi les indésirables.'})
|
||
if path=='/api/reset/verify':
|
||
import time
|
||
x=self.body();token=x.get('token','')
|
||
if not isinstance(token,str) or not token.strip():return self.json({'error':'Saisissez le code reçu par mail'},400)
|
||
with db() as con:
|
||
recovery_tables(con)
|
||
r=con.execute('SELECT 1 FROM password_resets WHERE token_hash=? AND expires>?',(hashlib.sha256(token.strip().encode()).hexdigest(),time.time())).fetchone()
|
||
if not r:return self.json({'error':'Code invalide, expiré ou déjà utilisé'},400)
|
||
return self.json({'ok':True})
|
||
if path=='/api/reset':
|
||
import time
|
||
x=self.body();password=x.get('password','');token=x.get('token','')
|
||
if not isinstance(password,str) or len(password)<8 or not isinstance(token,str):return self.json({'error':'Mot de passe : 8 caractères minimum'},400)
|
||
with db() as con:
|
||
con.execute('BEGIN IMMEDIATE');recovery_tables(con)
|
||
r=con.execute('SELECT * FROM password_resets WHERE token_hash=? AND expires>?',(hashlib.sha256(token.encode()).hexdigest(),time.time())).fetchone()
|
||
if not r:return self.json({'error':'Code invalide, expiré ou déjà utilisé'},400)
|
||
digest,salt=hash_password(password);con.execute('UPDATE users SET password_hash=?,salt=? WHERE id=?',(digest,salt,r['user_id']));con.execute('DELETE FROM password_resets WHERE user_id=?',(r['user_id'],))
|
||
invalidate_sessions(r['user_id']);return self.json({'message':'Mot de passe modifié. Vous pouvez vous connecter.'})
|
||
if path in ['/api/users/create','/api/users/update','/api/users/delete']:
|
||
uid=self.owner()
|
||
if not uid or uid!=admin_id() or self.headers.get('X-Share-Token'):return self.json({'error':'Action réservée à l’administrateur'},403)
|
||
x=self.body()
|
||
try:target=int(x.get('id',0))
|
||
except (ValueError,TypeError):return self.json({'error':'Utilisateur invalide'},400)
|
||
if path.endswith('/delete'):
|
||
if target==admin_id():return self.json({'error':'Le compte administrateur ne peut pas être supprimé'},400)
|
||
with db() as con:
|
||
recovery_tables(con)
|
||
con.execute('DELETE FROM mail_log WHERE application_id IN (SELECT id FROM applications WHERE user_id=?)',(target,))
|
||
for table in ['applications','share_links','shares','settings','mail_settings','password_resets']:con.execute(f'DELETE FROM {table} WHERE user_id=?',(target,))
|
||
con.execute('DELETE FROM users WHERE id=?',(target,))
|
||
invalidate_sessions(target);return self.json({'ok':True})
|
||
email=str(x.get('email','')).strip().lower();password=x.get('password','')
|
||
if '@' not in email or '\r' in email or '\n' in email or not isinstance(password,str) or (password and len(password)<8) or (path.endswith('/create') and not password):return self.json({'error':'E-mail valide et mot de passe de 8 caractères minimum requis'},400)
|
||
try:
|
||
with db() as con:
|
||
recovery_tables(con)
|
||
if path.endswith('/create'):
|
||
digest,salt=hash_password(password);con.execute('INSERT INTO users(email,password_hash,salt) VALUES(?,?,?)',(email,digest,salt))
|
||
else:
|
||
cur=con.execute('UPDATE users SET email=? WHERE id=?',(email,target))
|
||
if not cur.rowcount:return self.json({'error':'Utilisateur introuvable'},404)
|
||
con.execute('DELETE FROM password_resets WHERE user_id=?',(target,))
|
||
if password:
|
||
digest,salt=hash_password(password);con.execute('UPDATE users SET password_hash=?,salt=? WHERE id=?',(digest,salt,target))
|
||
except sqlite3.IntegrityError:return self.json({'error':'Cette adresse est déjà utilisée'},409)
|
||
if path.endswith('/update'):invalidate_sessions(target)
|
||
return self.json({'ok':True})
|
||
if path=='/api/mail/test':
|
||
uid=self.owner()
|
||
if not uid or self.headers.get('X-Share-Token'):return self.json({'error':'Action réservée au propriétaire'},403)
|
||
if uid!=admin_id():return self.json({'error':'Action réservée à l’administrateur'},403)
|
||
cfg=mail_settings(uid);recipient=get_settings(uid)['notify_email']
|
||
if not recipient or not cfg['smtp_host'] or not cfg['smtp_from']:return self.json({'error':'Enregistrez d’abord le serveur SMTP, l’expéditeur et l’adresse de réception dans les paramètres'},400)
|
||
try:
|
||
import smtplib, ssl
|
||
from email.message import EmailMessage
|
||
from datetime import date
|
||
sample={'company':'Entreprise de test','role':'Poste de test','followup_date':date.today().isoformat(),'sent_date':date.today().isoformat(),'method':'Mail','contact':'Contact de test','notes':'Ceci est un test, aucune candidature n’est modifiée.'}
|
||
msg=EmailMessage();msg['From']=cfg['smtp_from'];msg['To']=recipient
|
||
msg['Subject']='[TEST] '+render_mail(cfg['mail_subject'],sample).replace('\r',' ').replace('\n',' ')
|
||
msg.set_content(render_mail(cfg['mail_body'],sample))
|
||
cls=smtplib.SMTP_SSL if cfg['smtp_security']=='ssl' else smtplib.SMTP
|
||
with cls(cfg['smtp_host'],cfg['smtp_port'],timeout=30) as smtp:
|
||
if cfg['smtp_security']=='starttls':smtp.starttls(context=ssl.create_default_context())
|
||
if cfg['smtp_user']:smtp.login(cfg['smtp_user'],cfg['smtp_password'])
|
||
smtp.send_message(msg)
|
||
return self.json({'message':'Mail de test accepté par le serveur SMTP. Vérifiez votre boîte de réception et les courriers indésirables.'})
|
||
except smtplib.SMTPAuthenticationError:return self.json({'error':'Authentification SMTP refusée : vérifiez l’identifiant et le mot de passe d’application'},400)
|
||
except Exception:return self.json({'error':'Envoi impossible : vérifiez le serveur, le port, la sécurité SMTP et la connexion réseau'},400)
|
||
if path=='/api/settings':
|
||
uid=self.owner()
|
||
if not uid or self.headers.get('X-Share-Token'):return self.json({'error':'Action réservée au propriétaire'},403)
|
||
x=self.body(); methods=x.get('methods'); email=x.get('notify_email','').strip(); enabled=bool(x.get('enabled'))
|
||
if not isinstance(methods,list) or not 1<=len(methods)<=50 or any(not isinstance(m,str) or not m.strip() or len(m)>80 for m in methods):
|
||
return self.json({'error':'Indiquez de 1 à 50 moyens, chacun de 80 caractères maximum'},400)
|
||
if email and ('@' not in email or '\r' in email or '\n' in email):return self.json({'error':'Adresse e-mail invalide'},400)
|
||
if enabled and not email:return self.json({'error':'Adresse e-mail requise pour les notifications'},400)
|
||
current=get_settings(uid)
|
||
notify_time=x.get('notify_time',current.get('notify_time','09:00'))
|
||
import re
|
||
if not isinstance(notify_time,str) or not re.fullmatch(r'(?:[01][0-9]|2[0-3]):[0-5][0-9]',notify_time):return self.json({'error':'Heure invalide : utilisez HH:MM'},400)
|
||
reminder_text=x.get('interview_reminders',current.get('interview_reminders','7,1'))
|
||
try:
|
||
reminder_days=sorted({int(v.strip()) for v in reminder_text.split(',') if v.strip()},reverse=True)
|
||
if not reminder_days or any(v<0 or v>365 for v in reminder_days):raise ValueError
|
||
except (ValueError,AttributeError):return self.json({'error':'Rappels d’entretien invalides : utilisez des jours de 0 à 365 séparés par des virgules'},400)
|
||
reminder_text=','.join(map(str,reminder_days))
|
||
is_admin=uid==admin_id()
|
||
if not is_admin and any(k in x for k in ['smtp_host','smtp_port','smtp_from','smtp_user','smtp_security','smtp_password','clear_smtp_password','mail_subject','mail_body','interview_mail_subject','interview_mail_body','registration_enabled']):return self.json({'error':'Configuration mail et inscriptions réservées à l’administrateur'},403)
|
||
cfg=mail_settings(uid)
|
||
for key in ['smtp_host','smtp_from','smtp_user','smtp_security','mail_subject','mail_body','interview_mail_subject','interview_mail_body']:
|
||
if key in x:
|
||
if not isinstance(x[key],str) or len(x[key])>10000:return self.json({'error':'Configuration mail invalide'},400)
|
||
cfg[key]=x[key]
|
||
try:cfg['smtp_port']=int(x.get('smtp_port',cfg['smtp_port']))
|
||
except (ValueError,TypeError):return self.json({'error':'Port SMTP invalide'},400)
|
||
if not 1<=cfg['smtp_port']<=65535 or cfg['smtp_security'] not in ['ssl','starttls']:return self.json({'error':'Port ou sécurité SMTP invalide'},400)
|
||
if any('\r' in cfg[k] or '\n' in cfg[k] for k in ['smtp_host','smtp_from','smtp_user','mail_subject','interview_mail_subject']):return self.json({'error':'Les champs SMTP et l’objet doivent tenir sur une ligne'},400)
|
||
if x.get('smtp_password'):
|
||
if not isinstance(x['smtp_password'],str):return self.json({'error':'Mot de passe invalide'},400)
|
||
cfg['smtp_password']=x['smtp_password']
|
||
if x.get('clear_smtp_password'):cfg['smtp_password']=''
|
||
if enabled and (not cfg['smtp_host'] or '@' not in cfg['smtp_from']):return self.json({'error':'Serveur SMTP et adresse expéditeur requis'},400)
|
||
methods=list(dict.fromkeys(m.strip() for m in methods))
|
||
with db() as con:
|
||
if is_admin:
|
||
con.execute('INSERT INTO mail_settings VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET config=excluded.config',(uid,json.dumps(cfg)))
|
||
if 'registration_enabled' in x:
|
||
con.execute('CREATE TABLE IF NOT EXISTS app_config(key TEXT PRIMARY KEY,value TEXT NOT NULL)')
|
||
con.execute("INSERT INTO app_config VALUES('registration',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",('1' if x['registration_enabled'] else '0',))
|
||
con.execute('INSERT INTO settings(user_id,methods,notify_email,enabled) VALUES(?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET methods=excluded.methods,notify_email=excluded.notify_email,enabled=excluded.enabled',(uid,json.dumps(methods),email,int(enabled)))
|
||
con.execute('UPDATE settings SET notify_time=?,interview_reminders=? WHERE user_id=?',(notify_time,reminder_text,uid))
|
||
return self.json({'ok':True})
|
||
if path in ['/api/share','/api/share/update','/api/share/revoke']:
|
||
uid=self.owner()
|
||
if not uid or self.headers.get('X-Share-Token'):return self.json({'error':'Action réservée au propriétaire'},403)
|
||
x=self.body(); token=x.get('token','')
|
||
permission=x.get('permission','read');label=x.get('label','')
|
||
if permission not in ['read','edit'] or not isinstance(label,str) or len(label)>100:return self.json({'error':'Paramètres invalides'},400)
|
||
with db() as con:
|
||
if path.endswith('/revoke'):
|
||
cur=con.execute('DELETE FROM share_links WHERE token=? AND user_id=?',(token,uid))
|
||
elif path.endswith('/update'):
|
||
cur=con.execute('UPDATE share_links SET label=?,permission=? WHERE token=? AND user_id=?',(label.strip(),permission,token,uid))
|
||
else:
|
||
token=secrets.token_urlsafe(32)
|
||
con.execute('INSERT INTO share_links VALUES(?,?,?,?)',(token,uid,label.strip(),permission))
|
||
return self.json({'token':token})
|
||
if not cur.rowcount:return self.json({'error':'Lien introuvable'},404)
|
||
return self.json({'ok':True})
|
||
if path in ['/api/register','/api/login']:
|
||
x=self.body(); email=x.get('email',''); password=x.get('password','')
|
||
import re
|
||
if not isinstance(email,str):return self.json({'error':'Adresse mail invalide'},400)
|
||
email=email.strip().lower()
|
||
if len(email)>254 or not re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+',email):return self.json({'error':'Adresse mail invalide'},400)
|
||
if not isinstance(password,str):return self.json({'error':'Mot de passe incorrect'},400)
|
||
if path.endswith('register') and len(password)<8:return self.json({'error':'Le mot de passe doit contenir au moins 8 caractères'},400)
|
||
with db() as con:
|
||
if path.endswith('register'):
|
||
con.execute('BEGIN IMMEDIATE')
|
||
con.execute('CREATE TABLE IF NOT EXISTS app_config(key TEXT PRIMARY KEY,value TEXT NOT NULL)')
|
||
gate=con.execute("SELECT value FROM app_config WHERE key='registration'").fetchone()
|
||
if gate and gate['value']=='0':return self.json({'error':'Les inscriptions sont désactivées'},403)
|
||
digest,salt=hash_password(password)
|
||
try: cur=con.execute('INSERT INTO users(email,password_hash,salt) VALUES(?,?,?)',(email,digest,salt)); uid=cur.lastrowid
|
||
except sqlite3.IntegrityError:return self.json({'error':'Cette adresse e-mail existe déjà'},409)
|
||
else:
|
||
u=con.execute('SELECT * FROM users WHERE email=?',(email,)).fetchone()
|
||
if not u:return self.json({'error':'Adresse mail inconnue'},401)
|
||
digest,_=hash_password(password,base64.b64decode(u['salt']))
|
||
if not hmac.compare_digest(digest,u['password_hash']):return self.json({'error':'Mot de passe incorrect'},401)
|
||
uid=u['id']
|
||
import time
|
||
token=secrets.token_urlsafe(32); SESSIONS[token]=uid
|
||
with db() as con:
|
||
con.execute('DELETE FROM sessions WHERE user_id=? OR expires<=?',(uid,time.time()))
|
||
con.execute('INSERT INTO sessions(token,user_id,expires) VALUES(?,?,?)',(token,uid,time.time()+2592000))
|
||
return self.json({'ok':True},cookie=f'session={token}; Max-Age=2592000; HttpOnly; SameSite=Lax; Path=/')
|
||
if path=='/api/logout':
|
||
c=SimpleCookie(self.headers.get('Cookie')); token=c.get('session');
|
||
if token:
|
||
SESSIONS.pop(token.value,None)
|
||
with db() as con:con.execute('DELETE FROM sessions WHERE token=?',(token.value,))
|
||
return self.json({'ok':True},cookie='session=; Max-Age=0; Path=/')
|
||
if path=='/api/applications':
|
||
uid=self.user()
|
||
if not uid:return self.json({'error':'Non connecté'},401)
|
||
if not self.can_edit():return self.json({'error':'Lien en lecture seule'},403)
|
||
from datetime import date, timedelta
|
||
today = date.today()
|
||
followup = today + timedelta(days=10)
|
||
x=self.body()
|
||
if not isinstance(x,dict):return self.json({'error':'Données invalides'},400)
|
||
keys=['company','role','location','contact','method','sent_date','followup_date','status','notes']
|
||
defaults={'method':'Mail','sent_date':today.isoformat(),'followup_date':followup.isoformat(),'status':'Envoyée'}
|
||
values={k:x.get(k,defaults.get(k,'')) for k in keys}
|
||
if any(not isinstance(v,str) or len(v)>10000 for v in values.values()):return self.json({'error':'Champs invalides ou trop longs'},400)
|
||
values['company']=values['company'].strip()
|
||
if not values['company']:return self.json({'error':'Le nom de l’entreprise est obligatoire'},400)
|
||
if values['status'] not in ['Envoyée','À relancer','Entretien','Refusée','Acceptée']:return self.json({'error':'Statut invalide'},400)
|
||
try:
|
||
for k in ['sent_date','followup_date']:
|
||
if values[k]:values[k]=date.fromisoformat(values[k]).isoformat()
|
||
except ValueError:return self.json({'error':'Date invalide'},400)
|
||
with db() as con:
|
||
con.execute('INSERT INTO applications(user_id,company,role,location,contact,method,sent_date,followup_date,status,notes) VALUES(?,?,?,?,?,?,?,?,?,?)', [uid]+[values[k] for k in keys])
|
||
return self.json({'ok':True})
|
||
self.json({'error':'Introuvable'},404)
|
||
def do_PUT(self):
|
||
uid=self.user(); path=urlparse(self.path).path
|
||
if not uid:return self.json({'error':'Non connecté'},401)
|
||
if not self.can_edit():return self.json({'error':'Lien en lecture seule'},403)
|
||
try: ident=int(path.rsplit('/',1)[1])
|
||
except:return self.json({'error':'Adresse invalide'},400)
|
||
x=self.body(); allowed={'company','role','location','contact','method','sent_date','followup_date','status','notes','interview_at','interview_type','interview_address'}
|
||
changes={k:v for k,v in x.items() if k in allowed and isinstance(v,str)}
|
||
interview_fields={'status','interview_at','interview_type','interview_address'}
|
||
if not changes or (len(changes)>2 and not set(changes).issubset(interview_fields)) or ('interview_at' in changes and changes.get('status')!='Entretien'):return self.json({'error':'Modification invalide'},400)
|
||
if 'interview_type' in changes and changes['interview_type'] not in ('Présentiel','Visio'):return self.json({'error':'Type de rendez-vous invalide'},400)
|
||
if changes.get('interview_type')=='Présentiel' and not changes.get('interview_address','').strip():return self.json({'error':'Indiquez l’adresse du rendez-vous'},400)
|
||
if changes.get('status')=='Entretien' and 'interview_at' not in changes:
|
||
with db() as con:r=con.execute('SELECT interview_at FROM applications WHERE id=? AND user_id=?',(ident,uid)).fetchone()
|
||
if not r or not r['interview_at']:return self.json({'error':'Indiquez la date et l’heure de l’entretien'},400)
|
||
if 'interview_at' in changes:
|
||
from datetime import datetime
|
||
try:changes['interview_at']=datetime.fromisoformat(changes['interview_at']).strftime('%Y-%m-%dT%H:%M')
|
||
except ValueError:return self.json({'error':'Date et heure d’entretien invalides'},400)
|
||
with db() as con:
|
||
for k,v in changes.items():con.execute(f'UPDATE applications SET {k}=? WHERE id=? AND user_id=?',(v,ident,uid))
|
||
self.json({'ok':True})
|
||
def do_DELETE(self):
|
||
uid=self.user()
|
||
if not uid:return self.json({'error':'Non connecté'},401)
|
||
if not self.can_edit():return self.json({'error':'Lien en lecture seule'},403)
|
||
try: ident=int(urlparse(self.path).path.rsplit('/',1)[1])
|
||
except:return self.json({'error':'Adresse invalide'},400)
|
||
with db() as con: con.execute('DELETE FROM applications WHERE id=? AND user_id=?',(ident,uid))
|
||
self.json({'ok':True})
|
||
# --- Renforcement de sécurité CandiPilot ---
|
||
import re
|
||
import time
|
||
import threading
|
||
from collections import deque
|
||
from datetime import date, datetime, timedelta
|
||
from http.cookies import CookieError
|
||
|
||
class RequestRejected(Exception):
|
||
def __init__(self, message, status=400):
|
||
self.message = message
|
||
self.status = status
|
||
|
||
MAX_REQUEST_BYTES = 128 * 1024
|
||
SECURITY_LOCK = threading.Lock()
|
||
SECURITY_ATTEMPTS = {}
|
||
APPLICATION_COLUMNS = frozenset({
|
||
'company', 'role', 'location', 'contact', 'method',
|
||
'sent_date', 'followup_date', 'status', 'notes',
|
||
'interview_at', 'interview_type', 'interview_address'
|
||
})
|
||
APPLICATION_STATUSES = {
|
||
'Envoyée', 'À relancer', 'Entretien', 'Refusée', 'Acceptée'
|
||
}
|
||
|
||
def valid_address(value):
|
||
return (
|
||
isinstance(value, str)
|
||
and len(value) <= 254
|
||
and re.fullmatch(
|
||
r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+"
|
||
r"@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"
|
||
r"(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+",
|
||
value
|
||
) is not None
|
||
)
|
||
|
||
def secure_body(self):
|
||
if hasattr(self, '_security_body'):
|
||
return self._security_body
|
||
lengths = self.headers.get_all('Content-Length', [])
|
||
if self.headers.get('Transfer-Encoding'):
|
||
raise RequestRejected('Encodage de requête non accepté')
|
||
if len(lengths) != 1 or not re.fullmatch(r'[0-9]+', lengths[0]):
|
||
raise RequestRejected('Taille de requête invalide', 411)
|
||
size = int(lengths[0])
|
||
if size > MAX_REQUEST_BYTES:
|
||
raise RequestRejected('Requête trop volumineuse', 413)
|
||
content_type = self.headers.get('Content-Type', '').split(';')[0].strip()
|
||
if content_type.lower() != 'application/json':
|
||
raise RequestRejected('Format JSON requis', 415)
|
||
raw = self.rfile.read(size)
|
||
if len(raw) != size:
|
||
raise RequestRejected('Requête incomplète')
|
||
try:
|
||
data = json.loads(raw.decode('utf-8') or '{}')
|
||
except (ValueError, UnicodeError, RecursionError):
|
||
raise RequestRejected('JSON invalide')
|
||
if not isinstance(data, dict):
|
||
raise RequestRejected('Un objet JSON est requis')
|
||
self._security_body = data
|
||
return data
|
||
|
||
def check_rate(self, path):
|
||
quotas = {
|
||
'/api/login': 20,
|
||
'/api/register': 5,
|
||
'/api/forgot': 5,
|
||
'/api/reset': 20,
|
||
'/api/reset/verify': 20,
|
||
'/api/mail/test': 5,
|
||
}
|
||
if path not in quotas:
|
||
return
|
||
now = time.monotonic()
|
||
key = (self.client_address[0], path)
|
||
with SECURITY_LOCK:
|
||
for old_key in list(SECURITY_ATTEMPTS):
|
||
queue = SECURITY_ATTEMPTS[old_key]
|
||
while queue and queue[0] <= now - 300:
|
||
queue.popleft()
|
||
if not queue:
|
||
del SECURITY_ATTEMPTS[old_key]
|
||
if key not in SECURITY_ATTEMPTS and len(SECURITY_ATTEMPTS) >= 4096:
|
||
raise RequestRejected('Trop de demandes, réessayez plus tard', 429)
|
||
queue = SECURITY_ATTEMPTS.setdefault(key, deque())
|
||
if len(queue) >= quotas[path]:
|
||
raise RequestRejected('Trop de tentatives : attendez cinq minutes', 429)
|
||
queue.append(now)
|
||
|
||
def validate_payload(path, data):
|
||
for key in ('email', 'notify_email', 'smtp_from'):
|
||
if key in data:
|
||
value = data[key]
|
||
if not isinstance(value, str):
|
||
raise RequestRejected('Adresse mail invalide')
|
||
value = value.strip()
|
||
if (key == 'email' or value) and not valid_address(value):
|
||
raise RequestRejected('Adresse mail invalide')
|
||
data[key] = value
|
||
for key in ('password', 'smtp_password'):
|
||
if key in data:
|
||
value = data[key]
|
||
if not isinstance(value, str) or len(value) > 1024:
|
||
raise RequestRejected('Mot de passe invalide ou trop long')
|
||
for key in ('token', 'label', 'interview_reminders', 'notify_time'):
|
||
if key in data and not isinstance(data[key], str):
|
||
raise RequestRejected('Champ invalide : ' + key)
|
||
if 'token' in data:
|
||
if len(data['token']) > 256:
|
||
raise RequestRejected('Code ou lien invalide')
|
||
data['token'] = data['token'].strip()
|
||
for key in ('smtp_host', 'smtp_user', 'mail_subject',
|
||
'interview_mail_subject'):
|
||
if key in data:
|
||
value = data[key]
|
||
if (not isinstance(value, str) or len(value) > 1000
|
||
or any(ord(c) < 32 or ord(c) == 127 for c in value)):
|
||
raise RequestRejected('Champ SMTP ou objet invalide')
|
||
for key in ('enabled', 'registration_enabled', 'clear_smtp_password'):
|
||
if key in data and not isinstance(data[key], bool):
|
||
raise RequestRejected('Valeur booléenne requise : ' + key)
|
||
if 'followup_days' in data:
|
||
value = data['followup_days']
|
||
if type(value) is not int or not 0 <= value <= 365:
|
||
raise RequestRejected('Délai de relance : de 0 à 365 jours')
|
||
|
||
def validate_application(values):
|
||
for key in APPLICATION_COLUMNS:
|
||
value = values.get(key, '')
|
||
limit = 10000 if key == 'notes' else 1000
|
||
if not isinstance(value, str) or len(value) > limit or '\x00' in value:
|
||
raise RequestRejected('Champ invalide ou trop long : ' + key)
|
||
values['company'] = values['company'].strip()
|
||
if not values['company']:
|
||
raise RequestRejected('Le nom de l’entreprise est obligatoire')
|
||
if values['status'] not in APPLICATION_STATUSES:
|
||
raise RequestRejected('Statut invalide')
|
||
try:
|
||
for key in ('sent_date', 'followup_date'):
|
||
if values[key]:
|
||
values[key] = date.fromisoformat(values[key]).isoformat()
|
||
if values['interview_at']:
|
||
when = datetime.fromisoformat(values['interview_at'])
|
||
if when.tzinfo is not None:
|
||
raise ValueError
|
||
values['interview_at'] = when.strftime('%Y-%m-%dT%H:%M')
|
||
except ValueError:
|
||
raise RequestRejected('Date invalide')
|
||
if values['interview_type'] not in ('Présentiel', 'Visio'):
|
||
raise RequestRejected('Type de rendez-vous invalide')
|
||
if values['status'] == 'Entretien':
|
||
if not values['interview_at']:
|
||
raise RequestRejected('Indiquez la date et l’heure de l’entretien')
|
||
if (values['interview_type'] == 'Présentiel'
|
||
and not values['interview_address'].strip()):
|
||
raise RequestRejected('Indiquez l’adresse du rendez-vous')
|
||
|
||
def secure_create(self):
|
||
uid = self.user()
|
||
if not uid:
|
||
return self.json({'error': 'Non connecté'}, 401)
|
||
if not self.can_edit():
|
||
return self.json({'error': 'Lien en lecture seule'}, 403)
|
||
data = self.body()
|
||
if set(data) - APPLICATION_COLUMNS:
|
||
raise RequestRejected('Champ de candidature inconnu')
|
||
settings = get_settings(uid)
|
||
days = int(settings.get('followup_days', 7))
|
||
days = max(0, min(365, days))
|
||
values = {key: '' for key in APPLICATION_COLUMNS}
|
||
values.update({
|
||
'method': 'Mail', 'status': 'Envoyée',
|
||
'sent_date': date.today().isoformat(),
|
||
'followup_date': (date.today() + timedelta(days=days)).isoformat(),
|
||
'interview_type': 'Présentiel',
|
||
})
|
||
values.update(data)
|
||
validate_application(values)
|
||
columns = sorted(APPLICATION_COLUMNS)
|
||
sql = ('INSERT INTO applications(user_id,' + ','.join(columns)
|
||
+ ') VALUES(' + ','.join('?' for _ in range(len(columns) + 1)) + ')')
|
||
with db() as con:
|
||
con.execute(sql, [uid] + [values[key] for key in columns])
|
||
return self.json({'ok': True})
|
||
|
||
def secure_put(self):
|
||
match = re.fullmatch(r'/api/applications/([1-9][0-9]*)',
|
||
urlparse(self.path).path)
|
||
if not match:
|
||
return self.json({'error': 'Introuvable'}, 404)
|
||
uid = self.user()
|
||
if not uid:
|
||
return self.json({'error': 'Non connecté'}, 401)
|
||
if not self.can_edit():
|
||
return self.json({'error': 'Lien en lecture seule'}, 403)
|
||
ident = int(match.group(1))
|
||
changes = self.body()
|
||
if not changes or set(changes) - APPLICATION_COLUMNS:
|
||
raise RequestRejected('Modification invalide')
|
||
with db() as con:
|
||
con.execute('BEGIN IMMEDIATE')
|
||
row = con.execute(
|
||
'SELECT * FROM applications WHERE id=? AND user_id=?',
|
||
(ident, uid)
|
||
).fetchone()
|
||
if not row:
|
||
return self.json({'error': 'Candidature introuvable'}, 404)
|
||
values = dict(row)
|
||
values.update(changes)
|
||
validate_application(values)
|
||
columns = sorted(changes)
|
||
# Identifiants issus exclusivement de la liste blanche constante.
|
||
sql = ('UPDATE applications SET '
|
||
+ ','.join(key + '=?' for key in columns)
|
||
+ ' WHERE id=? AND user_id=?')
|
||
con.execute(sql, [values[key] for key in columns] + [ident, uid])
|
||
return self.json({'ok': True})
|
||
|
||
def secure_delete(self):
|
||
match = re.fullmatch(r'/api/applications/([1-9][0-9]*)',
|
||
urlparse(self.path).path)
|
||
if not match:
|
||
return self.json({'error': 'Introuvable'}, 404)
|
||
uid = self.user()
|
||
if not uid:
|
||
return self.json({'error': 'Non connecté'}, 401)
|
||
if not self.can_edit():
|
||
return self.json({'error': 'Lien en lecture seule'}, 403)
|
||
ident = int(match.group(1))
|
||
with db() as con:
|
||
con.execute('BEGIN IMMEDIATE')
|
||
row = con.execute(
|
||
'SELECT id FROM applications WHERE id=? AND user_id=?',
|
||
(ident, uid)
|
||
).fetchone()
|
||
if not row:
|
||
return self.json({'error': 'Candidature introuvable'}, 404)
|
||
con.execute('DELETE FROM mail_log WHERE application_id=?', (ident,))
|
||
con.execute('DELETE FROM interview_mail_log WHERE application_id=?',
|
||
(ident,))
|
||
con.execute('DELETE FROM applications WHERE id=? AND user_id=?',
|
||
(ident, uid))
|
||
return self.json({'ok': True})
|
||
|
||
_original_post = Handler.do_POST
|
||
_original_get = Handler.do_GET
|
||
_original_page = page
|
||
_original_end_headers = Handler.end_headers
|
||
|
||
def guarded(method):
|
||
def dispatch(self):
|
||
try:
|
||
self.connection.settimeout(15)
|
||
if len(self.path) > 2048:
|
||
raise RequestRejected('Adresse trop longue', 414)
|
||
path = urlparse(self.path).path
|
||
if self.command in ('POST', 'PUT', 'DELETE'):
|
||
# Un site tiers ne peut pas ajouter cet en-tête sans
|
||
# une autorisation CORS, que cette application ne fournit pas.
|
||
if self.headers.get('X-CandiPilot-Request') != '1':
|
||
raise RequestRejected('Requête non autorisée', 403)
|
||
if self.headers.get('Sec-Fetch-Site') == 'cross-site':
|
||
raise RequestRejected('Requête intersite refusée', 403)
|
||
check_rate(self, path)
|
||
data = self.body()
|
||
validate_payload(path, data)
|
||
return method(self)
|
||
except RequestRejected as exc:
|
||
self.close_connection = True
|
||
return self.json({'error': exc.message}, exc.status)
|
||
except (CookieError, ValueError, TypeError, OverflowError):
|
||
self.close_connection = True
|
||
return self.json({'error': 'Données de requête invalides'}, 400)
|
||
except sqlite3.Error:
|
||
self.close_connection = True
|
||
return self.json({'error': 'Base de données indisponible'}, 503)
|
||
except (TimeoutError, ConnectionError, BrokenPipeError):
|
||
self.close_connection = True
|
||
return dispatch
|
||
|
||
def secured_post(self):
|
||
if urlparse(self.path).path == '/api/applications':
|
||
return secure_create(self)
|
||
return _original_post(self)
|
||
|
||
def secured_headers(self):
|
||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||
self.send_header('X-Frame-Options', 'DENY')
|
||
self.send_header('Referrer-Policy', 'no-referrer')
|
||
self.send_header('Cache-Control', 'no-store')
|
||
self.send_header('Content-Security-Policy',
|
||
"frame-ancestors 'none'; object-src 'none'; base-uri 'none'")
|
||
_original_end_headers(self)
|
||
|
||
def page():
|
||
# Adaptation ciblée de la fonction api() existante.
|
||
return _original_page().replace(
|
||
"headers:{'Content-Type':'application/json',",
|
||
"headers:{'X-CandiPilot-Request':'1','Content-Type':'application/json',",
|
||
1
|
||
)
|
||
|
||
Handler.body = secure_body
|
||
Handler.end_headers = secured_headers
|
||
Handler.do_GET = guarded(_original_get)
|
||
Handler.do_POST = guarded(secured_post)
|
||
Handler.do_PUT = guarded(secure_put)
|
||
Handler.do_DELETE = guarded(secure_delete)
|
||
# --- Fin du renforcement ---
|
||
if __name__=='__main__':
|
||
import threading
|
||
init_db()
|
||
init_settings()
|
||
threading.Thread(target=notification_loop,daemon=True).start()
|
||
print('Depuis un autre appareil du même réseau : http://ADRESSE_IP_DU_PC:8000')
|
||
ThreadingHTTPServer(('0.0.0.0',8000),Handler).serve_forever()
|