# LDAP Group-Based Authentication

The KPI Analysis Dashboard now includes comprehensive LDAP authentication with group-based access control. Only users who are members of the specified LDAP group can access the system.

## 🔐 **Security Features**

### **Dual Authentication System**

#### **Primary: LDAP Group-Based Authentication**
- **LDAP Authentication**: Users must authenticate against your company's LDAP/Active Directory
- **Group Membership Verification**: Only users in the authorized group can access the system
- **Enterprise Integration**: Seamless integration with existing directory infrastructure

#### **Fallback: Default Admin Authentication**
- **Development & Testing**: Provides access when LDAP is not available
- **Default Credentials**: Username `admin`, Password `super`
- **Configurable**: Enable/disable fallback authentication in settings
- **Security Note**: Should be disabled in production environments

### **Authentication Priority**
1. **LDAP Authentication** (if configured and available)
2. **Fallback Authentication** (if enabled and LDAP fails)
3. **Access Denied** (if no valid authentication method)
- **LDAP Authentication**: Users must authenticate against your company's LDAP/Active Directory
- **Group Membership Verification**: Only users in the authorized group can access the system
- **JWT Token Management**: Secure session management with automatic token expiration
- **Role-Based Access**: Support for different user roles within the authorized group

### **Authentication Flow**
1. **User Login**: Username and password sent to authentication endpoint
2. **LDAP Verification**: System validates credentials against LDAP server
3. **Group Check**: System verifies user is member of authorized KPI group
4. **Token Generation**: JWT token created for authenticated user
5. **Session Management**: Token used for all subsequent API calls

## ⚙️ **Configuration**

### **Fallback Authentication Settings**

For testing and development when LDAP is not available:

```env
# Fallback Authentication Configuration
ENABLE_FALLBACK_AUTH=true
FALLBACK_ADMIN_USERNAME=admin
FALLBACK_ADMIN_PASSWORD=super
FALLBACK_ADMIN_ROLE=admin
FALLBACK_ADMIN_EMAIL=admin@kpi-system.local
```

**⚠️ Security Warning**: Disable fallback authentication in production by setting `ENABLE_FALLBACK_AUTH=false`

**Default Login Credentials** (when fallback is enabled):
- Username: `admin`
- Password: `super`
- Role: `admin`

### **Required LDAP Settings**

Add these settings to your `.env` file:

```env
# LDAP Server Configuration
LDAP_SERVER=ldap.your-company.com
LDAP_PORT=389
LDAP_USE_SSL=true
LDAP_BASE_DN=DC=your-company,DC=com

# Authentication Binding (Service Account)
LDAP_BIND_DN=CN=service-account,OU=Service Accounts,DC=your-company,DC=com
LDAP_BIND_PASSWORD=your-service-account-password

# Group-Based Access Control
LDAP_GROUP_BASE_DN=DC=your-company,DC=com
LDAP_KPI_GROUP_DN=CN=KPI_Users,OU=Groups,DC=your-company,DC=com
LDAP_KPI_GROUP_NAME=KPI_Users
LDAP_GROUP_MEMBER_ATTRIBUTE=member
LDAP_USER_MEMBER_ATTRIBUTE=memberOf
```

### **Group Configuration Examples**

#### **For Active Directory:**
```env
LDAP_SERVER=dc1.your-company.com
LDAP_BASE_DN=DC=your-company,DC=com
LDAP_KPI_GROUP_DN=CN=KPI_Users,OU=Security Groups,DC=your-company,DC=com
LDAP_USER_MEMBER_ATTRIBUTE=memberOf
```

#### **For OpenLDAP:**
```env
LDAP_SERVER=ldap.your-company.com
LDAP_BASE_DN=ou=people,dc=your-company,dc=com
LDAP_KPI_GROUP_DN=cn=kpi-users,ou=groups,dc=your-company,dc=com
LDAP_GROUP_MEMBER_ATTRIBUTE=member
```

## 🏢 **Group Setup Instructions**

### **Active Directory Setup**

1. **Create Security Group:**
   - Open Active Directory Users and Computers
   - Navigate to the desired Organizational Unit
   - Right-click → New → Group
   - Group name: `KPI_Users`
   - Group scope: Global
   - Group type: Security

2. **Add Users to Group:**
   - Right-click the `KPI_Users` group
   - Properties → Members → Add
   - Add users who need access to KPI system

### **OpenLDAP Setup**

1. **Create Group Entry:**
   ```ldap
   dn: cn=kpi-users,ou=groups,dc=your-company,dc=com
   objectClass: groupOfNames
   cn: kpi-users
   description: Users authorized to access KPI Analysis system
   member: uid=user1,ou=people,dc=your-company,dc=com
   member: uid=user2,ou=people,dc=your-company,dc=com
   ```

2. **Update User Entries:**
   Ensure user entries include the group in their memberOf attribute or use member references.

## 🔧 **Testing Configuration**

### **API Test Endpoint**
Use the built-in test endpoint to verify your configuration:

```
GET /api/auth/test
```

This endpoint returns:
- Connection test results
- Group access verification
- Configuration status
- Troubleshooting information

### **Manual Testing**

1. **Test LDAP Connection:**
   ```bash
   curl http://localhost:8000/api/auth/test
   ```

2. **Test Authentication:**
   ```bash
   # Test with LDAP user (if configured)
   curl -X POST http://localhost:8000/api/auth/login \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "username=your-username&password=your-password"
   
   # Test with fallback admin (if enabled)
   curl -X POST http://localhost:8000/api/auth/login \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "username=admin&password=super"
   ```

## 🛠️ **Implementation Details**

### **Authentication Service**
- **File**: `app/services/ldap_auth_service.py`
- **Features**: 
  - LDAP connection management
  - Multiple group membership checking methods
  - User attribute retrieval
  - Connection pooling and error handling

### **Authorization Middleware**
- **File**: `app/core/auth.py`
- **Features**:
  - JWT token generation and verification
  - User session management
  - FastAPI dependency injection
  - Role-based access control

### **Frontend Integration**
- **File**: `static/js/dashboard.js`
- **Features**:
  - Login form handling
  - Token storage and management
  - Automatic authentication header injection
  - Session validation and logout

### **API Protection**
All protected endpoints now require authentication:
- `/api/files/*`
- `/api/analysis/*`
- `/api/nextcloud/*`
- `/api/reports/*`

## 🚫 **Security Best Practices**

### **Environment Security**
- Never commit `.env` file to version control
- Use strong passwords for service accounts
- Limit LDAP service account permissions
- Regularly rotate credentials

### **Network Security**
- Use LDAPS (LDAP over SSL) in production
- Configure firewall rules for LDAP ports
- Consider LDAP connection timeout settings

### **Application Security**
- JWT tokens expire automatically
- Tokens stored in localStorage (client-side)
- All API calls validated server-side
- Audit logging for authentication events

## 🔍 **Troubleshooting**

### **Common Issues**

#### **"Authentication failed" Errors**
- Verify LDAP server connectivity
- Check username/password accuracy
- Ensure service account permissions

#### **"User not authorized" Errors**
- Verify user is member of KPI group
- Check group DN configuration
- Validate member attribute mappings

#### **"Connection failed" Errors**
- Test LDAP server availability
- Check firewall settings
- Verify SSL/TLS configuration

#### **"Group not found" Errors**
- Verify group DN format
- Check group search permissions
- Confirm group exists in directory

### **Debug Information**

The `/api/auth/test` endpoint provides detailed diagnostic information:
- LDAP connection status
- Group access verification
- Configuration validation
- Error messages and recommendations

### **Log Analysis**

Check application logs for:
- Authentication attempts
- LDAP connection issues
- Group membership verification
- Token validation errors

## 📋 **Configuration Checklist**

- [ ] LDAP server details configured
- [ ] Service account created and tested
- [ ] KPI Users group created
- [ ] Authorized users added to group
- [ ] Group DN configuration verified
- [ ] SSL/TLS settings configured
- [ ] Test endpoint returns success
- [ ] Login functionality tested
- [ ] Role-based access configured
- [ ] Security settings reviewed

## 🎯 **Production Deployment**

### **Security Hardening**
- Use dedicated LDAP service account
- Implement certificate pinning
- Configure session timeout limits
- Enable audit logging
- Regular security updates

### **Performance Optimization**
- Connection pooling for LDAP
- Token caching strategies
- Database optimization
- Load balancing considerations

### **Monitoring and Alerts**
- Authentication failure monitoring
- LDAP server health checks
- Performance metrics tracking
- Security incident alerting

The LDAP group-based authentication system provides enterprise-grade security while maintaining ease of use for authorized users. Only users in your designated KPI group will have access to the system, ensuring proper access control and compliance with organizational security policies.