# Microsoft OAuth Authentication Setup

This document explains how to set up Microsoft Office 365 OAuth authentication for the Laravel application. This setup is designed to be replicated across multiple client projects.

## Multi-Client Setup Strategy

This setup is designed for development agencies or consultants who need to deploy the same authentication system across multiple client projects. The recommended approach is to:

1. **Use your development account** to create all Azure AD applications
2. **Follow a standardized naming convention** for each client
3. **Document the process** for easy replication
4. **Maintain a master configuration** for each client

### Naming Convention

For each client, use this naming pattern:
- **Application Name**: `{ClientName} CRM System` (e.g., "Firmly CRM System")
- **Redirect URI**: `https://{clientdomain.com}/microsoft/callback`
- **Environment Variables**: `{CLIENT}_MICROSOFT_CLIENT_ID`, etc.

### Client Configuration Template

For each new client, you'll need:
1. Azure AD application registration
2. Environment variables in the client's `.env` file
3. Domain-specific redirect URI configuration

## Prerequisites

1. A Microsoft Azure account
2. An Azure Active Directory (Azure AD) application registered
3. Laravel application with Laravel Socialite installed

## Azure AD Application Setup

### 1. Register a New Application

1. Go to the [Azure Portal](https://portal.azure.com)
2. Navigate to **Azure Active Directory** > **App registrations**
3. Click **New registration**
4. Fill in the application details:
   - **Name**: Your application name (e.g., "CRM System")
   - **Supported account types**: Choose based on your needs:
     - `Accounts in this organizational directory only` (for single tenant)
     - `Accounts in any organizational directory` (for multi-tenant)
   - **Redirect URI**: 
     - Type: Web
     - URI: `https://firmly.webiton.pt/microsoft/callback`
5. Click **Register**

### 2. Configure Authentication

1. In your registered application, go to **Authentication**
2. Add the redirect URI: `https://firmly.webiton.pt/microsoft/callback`
3. Under **Implicit grant and hybrid flows**, enable:
   - Access tokens
   - ID tokens
4. Save the changes

### 3. Create Client Secret

1. Go to **Certificates & secrets**
2. Click **New client secret**
3. Add a description and choose expiration
4. **Copy the secret value immediately** (you won't be able to see it again)
w0v8Q~STVrDXf6pE3mCUutLs8skNEB~XZ2YfEbn.
0c77542e-31fb-4bb2-819d-78568140c3bd

### 4. Configure API Permissions

1. Go to **API permissions**
2. Click **Add a permission**
3. Select **Microsoft Graph**
4. Choose **Delegated permissions**
5. Select the following permissions:
   - `User.Read` (to read user profile)
   - `email` (to get user email)
   - `profile` (to get user profile)
6. Click **Add permissions**
7. Click **Grant admin consent** (if you're an admin)

## Environment Configuration

Add the following variables to your `.env` file:

### For Single Client Setup

```env
# Microsoft OAuth Configuration
MICROSOFT_CLIENT_ID=your_client_id_here
MICROSOFT_CLIENT_SECRET=your_client_secret_here
MICROSOFT_REDIRECT_URI=https://firmly.webiton.pt/microsoft/callback
MICROSOFT_TENANT_ID=your_tenant_id_here
```

### For Multi-Client Setup (Recommended)

If you're managing multiple clients, use client-specific environment variables:

```env
# Firmly Client Configuration
FIRMLY_MICROSOFT_CLIENT_ID=your_firmly_client_id_here
FIRMLY_MICROSOFT_CLIENT_SECRET=your_firmly_client_secret_here
FIRMLY_MICROSOFT_REDIRECT_URI=https://firmly.webiton.pt/microsoft/callback
FIRMLY_MICROSOFT_TENANT_ID=your_tenant_id_here

# Future Client Configuration
CLIENT2_MICROSOFT_CLIENT_ID=your_client2_id_here
CLIENT2_MICROSOFT_CLIENT_SECRET=your_client2_secret_here
CLIENT2_MICROSOFT_REDIRECT_URI=https://client2.com/microsoft/callback
CLIENT2_MICROSOFT_TENANT_ID=your_tenant_id_here
```

```env
# Microsoft OAuth Configuration
MICROSOFT_CLIENT_ID=your_client_id_here
MICROSOFT_CLIENT_SECRET=your_client_secret_here
MICROSOFT_REDIRECT_URI=https://firmly.webiton.pt/microsoft/callback
MICROSOFT_TENANT_ID=your_tenant_id_here
```

### Configuration Details

- **MICROSOFT_CLIENT_ID**: The Application (client) ID from your Azure AD app
- **MICROSOFT_CLIENT_SECRET**: The client secret you created
- **MICROSOFT_REDIRECT_URI**: Your callback URL (must match what's configured in Azure)
- **MICROSOFT_TENANT_ID**: Your Azure AD tenant ID (use 'common' for multi-tenant)

## Application Features

### 1. User Authentication Flow

1. Users visit the login page
2. They can choose to login with Microsoft
3. They're redirected to Microsoft's OAuth page
4. After successful authentication, they're redirected back to your app
5. The system checks if the user exists in your database
6. If the user exists and is active, they're logged in
7. If the user doesn't exist, they see an error message

### 2. User Management

- **Individual Invitations**: Send Microsoft login invitations to specific users
- **Bulk Invitations**: Send invitations to multiple users at once
- **User Status Tracking**: See which users have connected their Microsoft accounts

### 3. Security Features

- Only users who exist in your system can authenticate
- Only active users can log in
- Microsoft account connection is tracked
- Failed authentication attempts are logged

## Routes

- `GET /microsoft/login` - Microsoft login page
- `GET /microsoft/redirect` - Redirect to Microsoft OAuth
- `GET /microsoft/callback` - Handle OAuth callback
- `GET /microsoft/invitations` - Send Microsoft login invitations (Admin only)

## Usage

### For Administrators

1. Create users in the system through the user management interface
2. Send Microsoft login invitations to users via `/microsoft/invitations`
3. Monitor which users have connected their Microsoft accounts

### For Users

1. Receive email invitation with login link
2. Click the link to go to Microsoft login page
3. Authenticate with Microsoft credentials
4. Access the application

## Troubleshooting

### Common Issues

1. **"Invalid redirect URI" error**
   - Ensure the redirect URI in Azure matches your application's callback URL
   - Check that the protocol (http/https) matches

2. **"User not found" error**
   - Make sure the user exists in your database
   - Check that the email address matches exactly

3. **"Account not active" error**
   - Ensure the user's status is set to 'active' in your system

4. **"Authentication failed" error**
   - Check your Azure AD application configuration
   - Verify client ID and secret are correct
   - Ensure API permissions are granted

### Debug Mode

To enable debug logging, add to your `.env`:

```env
LOG_LEVEL=debug
```

## Security Considerations

1. **HTTPS Required**: Always use HTTPS in production
2. **Secret Management**: Store client secrets securely
3. **Token Security**: Access tokens are handled securely by Laravel Socialite
4. **User Validation**: Always validate users exist in your system
5. **Error Handling**: Don't expose sensitive information in error messages

## Testing

### Local Development

For local development, you can use:
- Redirect URI: `http://localhost:8000/microsoft/callback`
- Make sure to update this in both your `.env` and Azure AD app configuration

### Production

For production:
- Use HTTPS URLs
- Update redirect URIs in Azure AD
- Ensure proper domain configuration

## Multi-Client Replication Process

### Step 1: Create Azure AD Application for New Client

1. Go to [Azure Portal](https://portal.azure.com) with your development account
2. Navigate to **Azure Active Directory** > **App registrations**
3. Click **New registration**
4. Use the naming convention:
   - **Name**: `{ClientName} CRM System` (e.g., "Acme Corp CRM System")
   - **Redirect URI**: `https://{clientdomain.com}/microsoft/callback`
5. Follow the same configuration steps as outlined above

### Step 2: Update Environment Configuration

1. Add client-specific environment variables to the new project's `.env` file
2. Update the `config/services.php` file if needed for client-specific configuration
3. Test the authentication flow

### Step 3: Documentation

1. Create a client-specific configuration file
2. Document any client-specific customizations
3. Maintain a master list of all client applications

### Client Management Checklist

For each new client, ensure you have:
- [ ] Azure AD application created with proper naming
- [ ] Environment variables configured
- [ ] Redirect URI set correctly
- [ ] API permissions granted
- [ ] Test authentication working
- [ ] Documentation updated

## Support

If you encounter issues:

1. Check the Laravel logs: `storage/logs/laravel.log`
2. Verify Azure AD application configuration
3. Test with a simple user account first
4. Ensure all environment variables are set correctly
5. Check client-specific configuration if using multi-client setup 