# Staff Data Encryption - Setup Guide

## Overview
This guide will help you set up encryption for staff data in your FaceML application. The encryption uses AES-256-GCM, which is industry-standard and provides both confidentiality and data integrity.

## What Gets Encrypted
The following staff data fields are encrypted:
- ✅ Full Name
- ✅ Email Address
- ✅ Phone Number
- ✅ Face Embeddings (biometric data)

## Prerequisites
- Node.js installed
- MySQL database running
- Backend server stopped (important!)

## Step-by-Step Setup

### Step 1: Generate Encryption Key

Run this command to generate a secure encryption key:

```bash
cd backend
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

**Example output:**
```
31ee095f535fd22d3b58379f6f6c75e372729f1777bb12165eee5502ee75653c
```

⚠️ **IMPORTANT:** Save this key securely! You'll need it in the next step.

### Step 2: Add Encryption Key to .env File

1. Open `backend/.env` file
2. Add this line at the end:

```bash
# Encryption Key for Staff Data
ENCRYPTION_KEY=31ee095f535fd22d3b58379f6f6c75e372729f1777bb12165eee5502ee75653c
```

Replace the example key with your generated key from Step 1.

### Step 3: Test Encryption Service

Verify the encryption service works correctly:

```bash
cd backend
node test_encryption.js
```

You should see all tests PASSED:
```
✓ Test 1: PASSED
✓ Test 2: PASSED
✓ Test 3: PASSED
✓ Test 4: PASSED
✓ Test 5: PASSED
✓ Test 6: PASSED
✅ All encryption tests completed!
```

### Step 4: Update Database Schema

Alter the staff table to support encrypted data:

```bash
cd backend/scripts
node alterStaffTable.js
```

Expected output:
```
✓ Connected to database
✓ Staff table altered successfully
✅ Database schema migration completed!
```

### Step 5: Encrypt Existing Data

**⚠️ IMPORTANT: This will encrypt all existing staff data!**

A backup will be created automatically, but ensure you have your own backup first.

```bash
cd backend/scripts
node encryptExistingData.js
```

Expected output:
```
✓ Connected to database
✓ Found X staff record(s)
✓ Backup created: backend/backups/staff_backup_YYYY-MM-DD...json
✓ Encrypted staff ID 1: John Doe
✓ Encrypted staff ID 2: Jane Smith
...
✅ Encryption completed!
  Successfully encrypted: X record(s)
  Errors: 0 record(s)
```

### Step 6: Restart Backend Server

```bash
cd backend
pm2 restart all
# OR if not using PM2:
# npm start
```

### Step 7: Verify Everything Works

1. **Check Database:**
   - Connect to MySQL
   - Run: `SELECT id, full_name, email FROM staff LIMIT 1;`
   - You should see encrypted data (unreadable strings)

2. **Check Application:**
   - Open your Flutter app
   - View staff list
   - Verify names, emails, and phones display correctly
   - Test face recognition attendance

## Backup and Recovery

### Backup Location
Encrypted data backups are stored in:
```
backend/backups/staff_backup_[timestamp].json
```

### Restore from Backup (if needed)

If something goes wrong, you can restore from backup:

1. Stop the backend server
2. Locate your backup file in `backend/backups/`
3. Contact support or manually restore data from the JSON file

## Security Best Practices

### 🔐 Encryption Key Security

1. **Never commit to version control**
   - The `.env` file should be in `.gitignore`
   - Never share your encryption key publicly

2. **Backup the encryption key**
   - Store it in a secure password manager
   - Keep a secure offline backup
   - **If you lose this key, encrypted data is UNRECOVERABLE**

3. **Production environments**
   - Consider using a key management service:
     - AWS KMS (Key Management Service)
     - Azure Key Vault
     - Google Cloud KMS
   - Rotate keys periodically (requires re-encryption)

### 🔒 Access Control

- Encryption key should only be accessible to:
  - Backend server (via .env)
  - System administrators
  - Secure backup systems

### 📋 Compliance

This encryption implementation helps with:
- GDPR compliance (data protection)
- HIPAA compliance (if applicable)
- PCI DSS (if storing payment-related data)
- General data privacy regulations

## Troubleshooting

### Issue: "ENCRYPTION_KEY not found in environment variables"
**Solution:** Make sure you added the ENCRYPTION_KEY to your `.env` file

### Issue: "Failed to decrypt data"
**Solution:** 
- Check if the encryption key in `.env` is correct
- Verify the data was encrypted with the same key
- Check if the encrypted data format is correct (should contain `:` separators)

### Issue: Face recognition not working
**Solution:**
- Check backend logs for decryption errors
- Verify face embeddings are being decrypted correctly
- Test with a new staff registration

### Issue: "Staff code already exists" when registering
**Solution:** This is normal - staff codes must be unique. Use a different code.

## Testing New Staff Registration

1. Open Flutter app
2. Register a new staff member
3. Check database - data should be encrypted
4. View staff list - data should display correctly
5. Test face recognition attendance

## Performance Impact

- **Encryption overhead:** Minimal (~1-5ms per operation)
- **Database size:** Encrypted data is slightly larger (~30-50% increase)
- **Application speed:** No noticeable impact on user experience

## Support

If you encounter any issues:
1. Check the troubleshooting section above
2. Review backend logs: `pm2 logs` or check `backend/server.log`
3. Verify all steps were completed correctly
4. Check that the encryption key is correctly set in `.env`

## Summary Checklist

- [ ] Generated encryption key
- [ ] Added ENCRYPTION_KEY to .env file
- [ ] Tested encryption service
- [ ] Updated database schema
- [ ] Encrypted existing data
- [ ] Verified backup was created
- [ ] Restarted backend server
- [ ] Tested staff list display
- [ ] Tested new staff registration
- [ ] Tested face recognition
- [ ] Backed up encryption key securely

✅ Once all items are checked, your staff data is fully encrypted and secure!
