# @ufdevsllc/auth-me - Quick Start Guide

## 🚀 Get Started in 5 Minutes

### Step 1: Install the Package

```bash
npm install @ufdevsllc/auth-me
```

### Step 2: Basic Import and Test

Create a file called `test-auth-me.js`:

```javascript
const authMe = require('@ufdevsllc/auth-me');

console.log('✅ Package imported successfully');
console.log('📊 System Info:', authMe.getSystemInfo());
console.log('🆔 Source ID:', authMe.getCurrentSourceId());
console.log('🔧 Initialized:', authMe.isInitialized());
```

Run it:
```bash
node test-auth-me.js
```

### Step 3: Express.js Integration (Optional)

If you're using Express.js, create `express-test.js`:

```javascript
const express = require('express');
const authMe = require('@ufdevsllc/auth-me');

const app = express();
const monitor = new authMe.ExpressMonitor();

app.get('/', (req, res) => {
    res.json({
        message: 'Hello from auth-me!',
        systemInfo: authMe.getSystemInfo(),
        sourceId: authMe.getCurrentSourceId()
    });
});

app.listen(3000, () => {
    console.log('🌐 Server running on http://localhost:3000');
});
```

## 📋 What You Get Out of the Box

### ✅ Working Features (No Setup Required)

```javascript
const authMe = require('@ufdevsllc/auth-me');

// System information
const systemInfo = authMe.getSystemInfo();

// Unique source ID for your deployment
const sourceId = authMe.getCurrentSourceId();

// Environment fingerprinting
const binding = authMe.generateEnvironmentBinding();
const isValid = authMe.validateEnvironmentBinding(binding);

// Initialization status
const initialized = authMe.isInitialized();

// Component instances
const dbManager = new authMe.DatabaseManager();
const monitor = new authMe.ExpressMonitor();
```

### 🔒 Secure Features (Require Initialization)

These features require proper initialization with a valid license:

```javascript
// These will throw "must be initialized" errors initially:
// authMe.getDeploymentFingerprint()
// authMe.getTokenInfo()
// authMe.getEnhancedSecurityFeatures()
// authMe.getDataMirrorStatus()
// authMe.getEnhancedStatus()
```

## 🛡️ Error Handling Pattern

Always wrap secure features in try-catch:

```javascript
function safeGetSecureFeature() {
    try {
        return authMe.getEnhancedSecurityFeatures();
    } catch (error) {
        if (error.message.includes('initialized')) {
            return { error: 'Requires initialization' };
        }
        throw error; // Re-throw unexpected errors
    }
}
```

## 📊 Health Check Function

Create a simple health check:

```javascript
function healthCheck() {
    return {
        packageLoaded: true,
        initialized: authMe.isInitialized(),
        systemInfo: authMe.getSystemInfo(),
        sourceId: authMe.getCurrentSourceId(),
        timestamp: new Date().toISOString()
    };
}

console.log('Health Check:', healthCheck());
```

## 🌐 Complete Express Example

```javascript
const express = require('express');
const authMe = require('@ufdevsllc/auth-me');

const app = express();
app.use(express.json());

// Health endpoint
app.get('/health', (req, res) => {
    res.json({
        status: 'healthy',
        initialized: authMe.isInitialized(),
        sourceId: authMe.getCurrentSourceId(),
        timestamp: new Date().toISOString()
    });
});

// System info endpoint
app.get('/system', (req, res) => {
    res.json(authMe.getSystemInfo());
});

// Secure status endpoint with error handling
app.get('/secure', (req, res) => {
    const status = { initialized: authMe.isInitialized() };
    
    try {
        status.secureFeatures = authMe.getEnhancedSecurityFeatures();
    } catch (error) {
        status.secureError = 'Requires initialization';
    }
    
    res.json(status);
});

// Error handling
app.use((error, req, res, next) => {
    res.status(500).json({
        error: 'Internal server error',
        timestamp: new Date().toISOString()
    });
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`🚀 Server running on port ${port}`);
    console.log('📍 Endpoints:');
    console.log('  GET /health - Health check');
    console.log('  GET /system - System information');
    console.log('  GET /secure - Secure features (may require init)');
});
```

## 🔍 Testing Your Setup

Create `validate-setup.js`:

```javascript
const authMe = require('@ufdevsllc/auth-me');

console.log('🧪 Validating auth-me setup...\n');

// Test 1: Package import
console.log('✅ Package imported successfully');

// Test 2: Basic functionality
const systemInfo = authMe.getSystemInfo();
console.log('✅ System info accessible:', !!systemInfo);

// Test 3: Source ID generation
const sourceId = authMe.getCurrentSourceId();
console.log('✅ Source ID generated:', sourceId.startsWith('SRC-'));

// Test 4: Component availability
const components = ['SecureGuard', 'ChainTracker', 'ModelCloner', 'URLProtector'];
const available = components.filter(comp => !!authMe[comp]);
console.log(`✅ Components available: ${available.length}/${components.length}`);

// Test 5: Instance creation
try {
    const dbManager = new authMe.DatabaseManager();
    const monitor = new authMe.ExpressMonitor();
    console.log('✅ Component instances created successfully');
} catch (error) {
    console.log('❌ Component instantiation failed:', error.message);
}

// Test 6: Secure features (expected to fail without initialization)
try {
    authMe.getEnhancedSecurityFeatures();
    console.log('⚠️  Secure features accessible (unexpected)');
} catch (error) {
    if (error.message.includes('initialized')) {
        console.log('✅ Secure features properly protected');
    } else {
        console.log('❌ Unexpected error:', error.message);
    }
}

console.log('\n🎉 Setup validation complete!');
console.log('📚 Check IMPORTING_AND_USAGE_GUIDE.md for detailed usage');
```

Run the validation:
```bash
node validate-setup.js
```

## 📚 Next Steps

1. **Read the Full Guide**: Check out [IMPORTING_AND_USAGE_GUIDE.md](IMPORTING_AND_USAGE_GUIDE.md)
2. **Explore Examples**: See [EXAMPLES_COLLECTION.md](EXAMPLES_COLLECTION.md)
3. **Production Setup**: For production use, you'll need proper initialization
4. **Database Integration**: Use DatabaseManager for data persistence
5. **Monitoring**: Implement the ExpressMonitor for request tracking

## 🆘 Common Issues

### Issue: "SecureGuard must be initialized"
**This is normal!** Secure features require proper initialization. Use basic features or handle the error gracefully.

### Issue: Package not found
```bash
# Make sure you installed it correctly
npm list @ufdevsllc/auth-me

# If not found, reinstall
npm install @ufdevsllc/auth-me
```

### Issue: Import errors
```javascript
// ✅ Correct import
const authMe = require('@ufdevsllc/auth-me');

// ❌ Incorrect import
import authMe from '@ufdevsllc/auth-me'; // This package uses CommonJS
```

## 📞 Support

- **Documentation**: Check the included markdown files
- **Examples**: See EXAMPLES_COLLECTION.md for comprehensive examples
- **Validation**: Run the test project in the `test-project/` folder

---

**You're ready to go!** 🎉 The package is working correctly when you see the "must be initialized" messages for secure features - that's the security system working as designed.