EmailSettings.tsx 17 KB

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