import { useState, useEffect } from 'react'; import { Authentication } from '../../../scripts/pocketbase/Authentication'; import { Collections, type User } from '../../../schemas/pocketbase/schema'; import { toast } from 'react-hot-toast'; export default function EmailRequestSettings() { const auth = Authentication.getInstance(); const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [requesting, setRequesting] = useState(false); const [resettingPassword, setResettingPassword] = useState(false); const [isOfficer, setIsOfficer] = useState(false); const [createdEmail, setCreatedEmail] = useState(null); const [showPasswordReset, setShowPasswordReset] = useState(false); const [newPassword, setNewPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [passwordError, setPasswordError] = useState(''); // For initial email creation const [initialPassword, setInitialPassword] = useState(''); const [initialConfirmPassword, setInitialConfirmPassword] = useState(''); const [initialPasswordError, setInitialPasswordError] = useState(''); const [showEmailForm, setShowEmailForm] = useState(false); useEffect(() => { const loadUserData = async () => { try { setLoading(true); const currentUser = auth.getCurrentUser(); if (!currentUser) { // Don't show toast on dashboard page for unauthenticated users if (!window.location.pathname.includes('/dashboard')) { toast.error('You must be logged in to access this page'); } return; } setUser(currentUser); // Check if user is an officer const pb = auth.getPocketBase(); try { const officerRecord = await pb.collection('officers').getFirstListItem(`user="${currentUser.id}"`); if (officerRecord) { setIsOfficer(true); } } catch (error) { // Not an officer, which is fine console.log('User is not an officer'); } } catch (error) { console.error('Error loading user data:', error); // Don't show toast on dashboard page for unauthenticated users if (auth.isAuthenticated() || !window.location.pathname.includes('/dashboard')) { toast.error('Failed to load user data. Please try again later.'); } } finally { setLoading(false); } }; loadUserData(); }, []); const toggleEmailForm = () => { setShowEmailForm(!showEmailForm); setInitialPassword(''); setInitialConfirmPassword(''); setInitialPasswordError(''); }; const validateInitialPassword = () => { if (initialPassword.length < 8) { setInitialPasswordError('Password must be at least 8 characters long'); return false; } if (initialPassword !== initialConfirmPassword) { setInitialPasswordError('Passwords do not match'); return false; } setInitialPasswordError(''); return true; }; const handleRequestEmail = async () => { if (!user) return; if (initialPassword && !validateInitialPassword()) { return; } try { setRequesting(true); // Determine what the email will be const emailUsername = user.email.split('@')[0].toLowerCase().replace(/[^a-z0-9]/g, ""); const emailDomain = import.meta.env.PUBLIC_MXROUTE_EMAIL_DOMAIN || 'ieeeucsd.org'; const expectedEmail = `${emailUsername}@${emailDomain}`; // Call the API to create the email account const response = await fetch('/api/create-ieee-email', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ userId: user.id, name: user.name, email: user.email, password: initialPassword || undefined }) }); const result = await response.json(); if (response.ok && result.success) { // Email created successfully setCreatedEmail(result.data.ieeeEmail); // Update the user record to mark email as requested const pb = auth.getPocketBase(); await pb.collection(Collections.USERS).update(user.id, { requested_email: true }); toast.success('IEEE email created successfully!'); setShowEmailForm(false); } else { toast.error(result.message || 'Failed to create email. Please contact the webmaster for assistance.'); } } catch (error) { console.error('Error requesting email:', error); toast.error('Failed to create email. Please try again later.'); } finally { setRequesting(false); } }; const togglePasswordReset = () => { setShowPasswordReset(!showPasswordReset); setNewPassword(''); setConfirmPassword(''); setPasswordError(''); }; const validatePassword = () => { if (newPassword.length < 8) { setPasswordError('Password must be at least 8 characters long'); return false; } if (newPassword !== confirmPassword) { setPasswordError('Passwords do not match'); return false; } setPasswordError(''); return true; }; const handleResetPassword = async () => { if (!user || !user.requested_email) return; if (!validatePassword()) { return; } // Determine the email address const emailAddress = createdEmail || (user ? `${user.email.split('@')[0].toLowerCase().replace(/[^a-z0-9]/g, "")}@ieeeucsd.org` : ''); try { setResettingPassword(true); // Call the API to reset the password const response = await fetch('/api/reset-email-password', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: emailAddress, password: newPassword }) }); const result = await response.json(); if (response.ok && result.success) { toast.success('Password reset successfully!'); setShowPasswordReset(false); setNewPassword(''); setConfirmPassword(''); } else { toast.error(result.message || 'Failed to reset password. Please contact the webmaster for assistance.'); } } catch (error) { console.error('Error resetting password:', error); toast.error('Failed to reset password. Please try again later.'); } finally { setResettingPassword(false); } }; if (loading) { return (
); } if (!isOfficer) { return (

IEEE email addresses are only available to officers. If you are an officer and don't see the option to request an email, please contact the webmaster.

); } if (user?.requested_email || createdEmail) { return (

{createdEmail ? 'Your IEEE Email Address' : 'Email Request Status'}

{createdEmail || (user ? `${user.email.split('@')[0].toLowerCase().replace(/[^a-z0-9]/g, "")}@ieeeucsd.org` : '')}

{initialPassword ? (

Your email has been created with the password you provided.

) : (

Check your personal email for login instructions.

)}

Access Your Email

{!showPasswordReset ? ( ) : (

Reset Your Email Password

Important: After resetting your password, you'll need to update it in any email clients, Gmail integrations, or mobile devices where you've set up this email account.
setNewPassword(e.target.value)} placeholder="Enter new password" />
setConfirmPassword(e.target.value)} placeholder="Confirm new password" />
{passwordError && (
{passwordError}
)}
)} {!showPasswordReset && (

Reset your IEEE email password to a new password of your choice.

)}

Setting Up Your IEEE Email in Gmail

First Step: Set Up Sending From Your IEEE Email

  1. Go to settings (gear icon) → Accounts and Import
  2. In the section that says Send mail as:, select Reply from the same address the message was sent to
  3. In that same section, select Add another email address
  4. For the Name, put your actual name (e.g. Charles Nguyen) if this is your personal ieeeucsd.org or put the department name (e.g. IEEEUCSD Webmaster)
  5. For the Email address, put the email that was provided for you
  6. Make sure the Treat as an alias button is selected. Go to the next step
  7. For the SMTP Server, put mail.ieeeucsd.org
  8. For the username, put in your FULL ieeeucsd email address
  9. For the password, put in the email's password
  10. For the port, put in 587
  11. Make sure you select Secured connection with TLS
  12. Go back to mail.ieeeucsd.org and verify the email that Google has sent you

Second Step: Set Up Receiving Your IEEE Email

  1. Go to settings (gear icon) → Accounts and Import
  2. In the section that says Check mail from other accounts:, select Add a mail account
  3. Put in the ieeeucsd email and hit next
  4. Make sure Import emails from my other account (POP3) is selected, then hit next
  5. For the username, put in your full ieeeucsd.org email
  6. For the password, put in your ieeeucsd.org password
  7. For the POP Server, put in mail.ieeeucsd.org
  8. For the Port, put in 995
  9. Select Leave a copy of retrieved message on the server
  10. Select Always use a secure connection (SSL) when retrieving mail
  11. Select Label incoming messages
  12. Then hit Add Account

If you have any questions or need help with your IEEE email, please contact webmaster@ieeeucsd.org

); } return (
{!showEmailForm ? ( <>

As an IEEE officer, you're eligible for an official IEEE UCSD email address. This email can be used for all IEEE-related communications and provides a professional identity when representing the organization.

Benefits of an IEEE email:

  • Professional communication with sponsors and partners
  • Consistent branding for IEEE UCSD
  • Separation between personal and IEEE communications
  • Access to IEEE UCSD shared resources

Your IEEE Email Address

When you request an email, you'll receive:

{user?.email ? `${user.email.split('@')[0].toLowerCase().replace(/[^a-z0-9]/g, "")}@ieeeucsd.org` : 'Loading...'}

By requesting an email, you agree to use it responsibly and in accordance with IEEE UCSD policies.

) : (

Create Your IEEE Email

Your email address will be:

{user?.email ? `${user.email.split('@')[0].toLowerCase().replace(/[^a-z0-9]/g, "")}@ieeeucsd.org` : 'Loading...'}

setInitialPassword(e.target.value)} placeholder="Enter password (min. 8 characters)" />
setInitialConfirmPassword(e.target.value)} placeholder="Confirm password" />
{initialPasswordError && (
{initialPasswordError}
)}

Leave the password fields empty if you want a secure random password to be generated and sent to your personal email.

)}
); }