EmailSettings.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import { useState } from 'react';
  2. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { Mail, Send, Lock, Unlock, AlertTriangle, CheckCircle, Loader2 } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { SMTPSettings, TestSMTPRequest } from '../api/client';
  7. import { Card, CardContent, CardHeader } from './Card';
  8. import { Button } from './Button';
  9. import { useToast } from '../contexts/ToastContext';
  10. import { useEffect } from 'react';
  11. import { useAuth } from '../contexts/AuthContext';
  12. import { NumberInput } from './NumberInput';
  13. const SECURITY_PORT_MAP: Record<string, number> = {
  14. starttls: 587,
  15. ssl: 465,
  16. none: 25,
  17. };
  18. const PORT_SECURITY_MAP: Record<number, string> = {
  19. 587: 'starttls',
  20. 465: 'ssl',
  21. 25: 'none',
  22. };
  23. export function EmailSettings() {
  24. const { t } = useTranslation();
  25. const { showToast } = useToast();
  26. const queryClient = useQueryClient();
  27. const [smtpSettings, setSMTPSettings] = useState<SMTPSettings>({
  28. smtp_host: '',
  29. smtp_port: 587,
  30. smtp_username: '',
  31. smtp_password: '',
  32. smtp_security: 'starttls',
  33. smtp_auth_enabled: true,
  34. smtp_from_email: '',
  35. smtp_from_name: 'BamBuddy',
  36. });
  37. const [testEmail, setTestEmail] = useState('');
  38. // Fetch SMTP settings
  39. const { data: existingSettings, isLoading } = useQuery({
  40. queryKey: ['smtpSettings'],
  41. queryFn: () => api.getSMTPSettings(),
  42. });
  43. // Fetch global auth status
  44. const { authEnabled } = useAuth();
  45. // Fetch advanced auth status
  46. const { data: advancedAuthStatus } = useQuery({
  47. queryKey: ['advancedAuthStatus'],
  48. queryFn: () => api.getAdvancedAuthStatus(),
  49. });
  50. // Load existing settings when fetched
  51. useEffect(() => {
  52. if (existingSettings) {
  53. setSMTPSettings({
  54. ...existingSettings,
  55. smtp_password: '', // Never show password
  56. });
  57. }
  58. }, [existingSettings]);
  59. // The saved password only goes to the server it was entered for.
  60. const smtpPasswordNeedsReentry =
  61. !!existingSettings &&
  62. smtpSettings.smtp_auth_enabled &&
  63. !smtpSettings.smtp_password &&
  64. (smtpSettings.smtp_host !== existingSettings.smtp_host ||
  65. smtpSettings.smtp_port !== existingSettings.smtp_port ||
  66. smtpSettings.smtp_security !== existingSettings.smtp_security);
  67. const handleSecurityChange = (security: 'starttls' | 'ssl' | 'none') => {
  68. setSMTPSettings({
  69. ...smtpSettings,
  70. smtp_security: security,
  71. smtp_port: SECURITY_PORT_MAP[security],
  72. });
  73. };
  74. const handlePortChange = (port: number) => {
  75. const matchedSecurity = PORT_SECURITY_MAP[port];
  76. setSMTPSettings({
  77. ...smtpSettings,
  78. smtp_port: port,
  79. ...(matchedSecurity ? { smtp_security: matchedSecurity as 'starttls' | 'ssl' | 'none' } : {}),
  80. });
  81. };
  82. const handleAuthChange = (enabled: boolean) => {
  83. setSMTPSettings({
  84. ...smtpSettings,
  85. smtp_auth_enabled: enabled,
  86. ...(!enabled ? { smtp_username: '', smtp_password: '' } : {}),
  87. });
  88. };
  89. // Save SMTP settings
  90. const saveMutation = useMutation({
  91. mutationFn: (settings: SMTPSettings) => api.saveSMTPSettings(settings),
  92. onSuccess: () => {
  93. queryClient.invalidateQueries({ queryKey: ['smtpSettings'] });
  94. queryClient.invalidateQueries({ queryKey: ['advancedAuthStatus'] });
  95. showToast(t('settings.email.success.settingsSaved'), 'success');
  96. },
  97. onError: (error: Error) => {
  98. showToast(error.message, 'error');
  99. },
  100. });
  101. // Test SMTP connection
  102. const testMutation = useMutation({
  103. mutationFn: (request: TestSMTPRequest) => api.testSMTP(request),
  104. onSuccess: (data) => {
  105. showToast(data.message, data.success ? 'success' : 'error');
  106. },
  107. onError: (error: Error) => {
  108. showToast(error.message, 'error');
  109. },
  110. });
  111. // Toggle advanced auth
  112. const toggleAdvancedAuthMutation = useMutation({
  113. mutationFn: (enabled: boolean) =>
  114. enabled ? api.enableAdvancedAuth() : api.disableAdvancedAuth(),
  115. onSuccess: (data) => {
  116. queryClient.invalidateQueries({ queryKey: ['advancedAuthStatus'] });
  117. showToast(data.message, 'success');
  118. },
  119. onError: (error: Error) => {
  120. showToast(error.message, 'error');
  121. },
  122. });
  123. const handleSave = () => {
  124. // Validate required fields
  125. if (!smtpSettings.smtp_host || !smtpSettings.smtp_from_email) {
  126. showToast(t('settings.email.errors.requiredFields'), 'error');
  127. return;
  128. }
  129. // Validate auth fields when authentication is enabled
  130. if (smtpSettings.smtp_auth_enabled && (!smtpSettings.smtp_username)) {
  131. showToast(t('settings.email.errors.usernameRequired'), 'error');
  132. return;
  133. }
  134. saveMutation.mutate(smtpSettings);
  135. };
  136. const handleTest = () => {
  137. if (!testEmail) {
  138. showToast(t('settings.email.errors.enterTestEmail'), 'error');
  139. return;
  140. }
  141. // What the form holds, saved or not.
  142. testMutation.mutate({
  143. test_recipient: testEmail,
  144. smtp: smtpSettings,
  145. });
  146. };
  147. const handleToggleAdvancedAuth = () => {
  148. if (!authEnabled) {
  149. showToast(t('settings.email.errors.enableAuthFirst'), 'error');
  150. return;
  151. }
  152. if (!advancedAuthStatus?.advanced_auth_enabled && !advancedAuthStatus?.smtp_configured) {
  153. showToast(t('settings.email.errors.configureSmtpFirst'), 'error');
  154. return;
  155. }
  156. toggleAdvancedAuthMutation.mutate(!advancedAuthStatus?.advanced_auth_enabled);
  157. };
  158. if (isLoading) {
  159. return (
  160. <div className="flex items-center justify-center p-12">
  161. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  162. </div>
  163. );
  164. }
  165. const advancedEnabled = advancedAuthStatus?.advanced_auth_enabled ?? false;
  166. const inputClasses = "w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors";
  167. const disabledInputClasses = "w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";
  168. return (
  169. <div className="space-y-3">
  170. {/* Advanced Authentication Toggle - Always visible */}
  171. <Card id="card-email-advanced-auth">
  172. <CardHeader>
  173. <div className="flex items-center justify-between">
  174. <div className="flex items-center gap-2">
  175. <Mail className="w-5 h-5 text-bambu-green" />
  176. <h2 className="text-lg font-semibold text-white">
  177. {t('settings.email.advancedAuth') || 'Advanced Authentication'}
  178. </h2>
  179. </div>
  180. <Button
  181. onClick={handleToggleAdvancedAuth}
  182. disabled={toggleAdvancedAuthMutation.isPending}
  183. variant={advancedEnabled ? 'danger' : 'primary'}
  184. >
  185. {advancedEnabled ? (
  186. <>
  187. <Unlock className="w-4 h-4" />
  188. {t('settings.email.disable') || 'Disable'}
  189. </>
  190. ) : (
  191. <>
  192. <Lock className="w-4 h-4" />
  193. {t('settings.email.enable') || 'Enable'}
  194. </>
  195. )}
  196. </Button>
  197. </div>
  198. </CardHeader>
  199. <CardContent>
  200. <div className="space-y-3">
  201. {advancedEnabled ? (
  202. <div className="bg-green-50 dark:bg-green-500/10 border border-green-300 dark:border-green-500/30 rounded-lg p-4">
  203. <div className="flex items-start gap-3">
  204. <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400 mt-0.5 flex-shrink-0" />
  205. <div className="space-y-2">
  206. <p className="text-white font-medium">
  207. {t('settings.email.advancedAuthEnabled') || 'Advanced Authentication is enabled'}
  208. </p>
  209. <ul className="text-sm text-green-700 dark:text-green-300 space-y-1 list-disc list-inside">
  210. <li>{t('settings.email.feature1') || 'Passwords are auto-generated and emailed to new users'}</li>
  211. <li>{t('settings.email.feature2') || 'Users can login with username or email'}</li>
  212. <li>{t('settings.email.feature3') || 'Forgot password feature is available'}</li>
  213. <li>{t('settings.email.feature4') || 'Admins can reset user passwords via email'}</li>
  214. </ul>
  215. </div>
  216. </div>
  217. </div>
  218. ) : (
  219. <div className="bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg p-4">
  220. <div className="flex items-start gap-3">
  221. <AlertTriangle className="w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  222. <div className="space-y-2">
  223. <p className="text-white font-medium">
  224. {t('settings.email.advancedAuthDisabled') || 'Advanced Authentication is disabled'}
  225. </p>
  226. <p className="text-sm text-yellow-700 dark:text-yellow-300">
  227. {t('settings.email.advancedAuthDisabledDesc') || 'Enable advanced authentication to activate email-based features for user management.'}
  228. </p>
  229. </div>
  230. </div>
  231. </div>
  232. )}
  233. </div>
  234. </CardContent>
  235. </Card>
  236. {/* SMTP Config + Test SMTP side-by-side on lg+ */}
  237. <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
  238. <div className="lg:col-span-2">
  239. <Card id="card-smtp-config">
  240. <CardHeader>
  241. <h2 className="text-lg font-semibold text-white">
  242. {t('settings.email.smtpSettings') || 'SMTP Configuration'}
  243. </h2>
  244. </CardHeader>
  245. <CardContent>
  246. <div className="space-y-3">
  247. {/* Authentication - at the top */}
  248. <div>
  249. <label className="block text-sm font-medium text-white mb-1">
  250. {t('settings.email.authentication') || 'Authentication'}
  251. </label>
  252. <select
  253. value={smtpSettings.smtp_auth_enabled ? 'true' : 'false'}
  254. onChange={(e) => handleAuthChange(e.target.value === 'true')}
  255. className={inputClasses}
  256. >
  257. <option value="true">{t('settings.email.authOptions.enabled')}</option>
  258. <option value="false">{t('settings.email.authOptions.disabled')}</option>
  259. </select>
  260. </div>
  261. {/* Username / Password - dimmed when auth disabled */}
  262. <div className={`grid grid-cols-1 md:grid-cols-2 gap-4 transition-opacity ${!smtpSettings.smtp_auth_enabled ? 'opacity-40 pointer-events-none' : ''}`}>
  263. <div>
  264. <label className="block text-sm font-medium text-white mb-1">
  265. {t('settings.email.username') || 'Username'}
  266. </label>
  267. <input
  268. type="text"
  269. value={smtpSettings.smtp_username || ''}
  270. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_username: e.target.value })}
  271. placeholder="your.email@gmail.com"
  272. disabled={!smtpSettings.smtp_auth_enabled}
  273. className={smtpSettings.smtp_auth_enabled ? inputClasses : disabledInputClasses}
  274. />
  275. </div>
  276. <div>
  277. <label className="block text-sm font-medium text-white mb-1">
  278. {t('settings.email.password') || 'Password'}
  279. </label>
  280. <input
  281. type="password"
  282. value={smtpSettings.smtp_password || ''}
  283. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_password: e.target.value })}
  284. placeholder={existingSettings ? '••••••••' : 'App password'}
  285. disabled={!smtpSettings.smtp_auth_enabled}
  286. className={smtpSettings.smtp_auth_enabled ? inputClasses : disabledInputClasses}
  287. />
  288. {smtpPasswordNeedsReentry && (
  289. <p className="text-xs mt-1 text-yellow-400">{t('common.secretReenter')}</p>
  290. )}
  291. </div>
  292. </div>
  293. {/* SMTP Server / Port */}
  294. <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
  295. <div>
  296. <label className="block text-sm font-medium text-white mb-1">
  297. {t('settings.email.smtpHost') || 'SMTP Server'} *
  298. </label>
  299. <input
  300. type="text"
  301. value={smtpSettings.smtp_host}
  302. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_host: e.target.value })}
  303. placeholder="smtp.gmail.com"
  304. className={inputClasses}
  305. />
  306. </div>
  307. <div>
  308. <label className="block text-sm font-medium text-white mb-1">
  309. {t('settings.email.smtpPort') || 'SMTP Port'}
  310. </label>
  311. <NumberInput
  312. value={smtpSettings.smtp_port}
  313. onChange={handlePortChange}
  314. min={1}
  315. max={65535}
  316. fallback={587}
  317. placeholder="587"
  318. className={inputClasses}
  319. />
  320. </div>
  321. </div>
  322. {/* Security */}
  323. <div>
  324. <label className="block text-sm font-medium text-white mb-1">
  325. {t('settings.email.security') || 'Security'}
  326. </label>
  327. <select
  328. value={smtpSettings.smtp_security}
  329. onChange={(e) => handleSecurityChange(e.target.value as 'starttls' | 'ssl' | 'none')}
  330. className={inputClasses}
  331. >
  332. <option value="starttls">{t('settings.email.securityOptions.starttls')}</option>
  333. <option value="ssl">{t('settings.email.securityOptions.ssl')}</option>
  334. <option value="none">{t('settings.email.securityOptions.none')}</option>
  335. </select>
  336. </div>
  337. {/* From Email / Name */}
  338. <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
  339. <div>
  340. <label className="block text-sm font-medium text-white mb-1">
  341. {t('settings.email.fromEmail') || 'From Email'} *
  342. </label>
  343. <input
  344. type="email"
  345. value={smtpSettings.smtp_from_email}
  346. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_from_email: e.target.value })}
  347. placeholder="your@email.com"
  348. className={inputClasses}
  349. />
  350. </div>
  351. <div>
  352. <label className="block text-sm font-medium text-white mb-1">
  353. {t('settings.email.fromName') || 'From Name'}
  354. </label>
  355. <input
  356. type="text"
  357. value={smtpSettings.smtp_from_name}
  358. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_from_name: e.target.value })}
  359. placeholder="BamBuddy"
  360. className={inputClasses}
  361. />
  362. </div>
  363. </div>
  364. <div className="flex gap-2">
  365. <Button
  366. onClick={handleSave}
  367. disabled={saveMutation.isPending}
  368. className="flex-1"
  369. >
  370. {saveMutation.isPending ? (
  371. <>
  372. <Loader2 className="w-4 h-4 animate-spin" />
  373. {t('settings.email.saving') || 'Saving...'}
  374. </>
  375. ) : (
  376. t('settings.email.save') || 'Save Settings'
  377. )}
  378. </Button>
  379. </div>
  380. </div>
  381. </CardContent>
  382. </Card>
  383. </div>
  384. {/* Test SMTP */}
  385. <div>
  386. <Card id="card-email-test">
  387. <CardHeader>
  388. <h2 className="text-lg font-semibold text-white">
  389. {t('settings.email.testConnection') || 'Test SMTP Connection'}
  390. </h2>
  391. </CardHeader>
  392. <CardContent>
  393. <div className="space-y-3">
  394. <div>
  395. <label className="block text-sm font-medium text-white mb-1">
  396. {t('settings.email.testRecipient') || 'Test Recipient Email'}
  397. </label>
  398. <input
  399. type="email"
  400. value={testEmail}
  401. onChange={(e) => setTestEmail(e.target.value)}
  402. placeholder="test@example.com"
  403. className={inputClasses}
  404. />
  405. </div>
  406. <Button
  407. onClick={handleTest}
  408. disabled={testMutation.isPending}
  409. variant="secondary"
  410. >
  411. {testMutation.isPending ? (
  412. <>
  413. <Loader2 className="w-4 h-4 animate-spin" />
  414. {t('settings.email.sending') || 'Sending...'}
  415. </>
  416. ) : (
  417. <>
  418. <Send className="w-4 h-4" />
  419. {t('settings.email.sendTest') || 'Send Test Email'}
  420. </>
  421. )}
  422. </Button>
  423. </div>
  424. </CardContent>
  425. </Card>
  426. </div>
  427. </div>
  428. </div>
  429. );
  430. }