Organization User Authentication API

This API endpoint allows organizations to authenticate existing users or create new users using their API key. The endpoint automatically handles user creation and organization membership management.

Endpoint

POST /api/authenticate-organization-user/

Authentication

This endpoint requires API Key authentication. Organizations must include their API key in the request headers.

Headers

http Authorization: Bearer sk_your_api_key_here Content-Type: application/json

Or alternatively:

http X-API-Key: sk_your_api_key_here Content-Type: application/json

Request Body

json { "email": "user@example.com", "first_name": "John", "last_name": "Doe" }

Parameters

| Parameter | Type | Required | Description | | ------------ | ------ | -------- | ------------------------------- | | email | string | Yes | Valid email address of the user | | first_name | string | Yes | User's first name | | last_name | string | Yes | User's last name |

Response

Success Response (200 OK)

json { "user_data": { "id": "123e4567-e89b-12d3-a456-426614174000", "email": "user@example.com", "first_name": "John", "last_name": "Doe", "role": "USER", "provider": "LOCAL", "is_email_verified": true, "date_joined": "2024-01-15T10:30:00Z", "plan": "FREE" }, "tokens": { "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." }, "is_new_user": true, "organization": { "id": "456e7890-e89b-12d3-a456-426614174001", "name": "Acme Corporation", "plan": "TEAM_HIRING" } }

Response Fields

| Field | Type | Description | | ---------------- | ------- | ----------------------------------------------------------- | | user_data | object | Complete user information | | tokens.access | string | JWT access token for API authentication | | tokens.refresh | string | JWT refresh token for token renewal | | is_new_user | boolean | true if user was created, false if user already existed | | organization | object | Organization information |

Behavior

For Existing Users

  1. User exists and is already a member: Returns existing user data and new tokens
  2. User exists but not a member: Adds user to organization and returns user data with tokens
  3. User exists with different organization: Adds user to the new organization (users can belong to multiple organizations)

For New Users

  1. Creates a new user account with the provided information
  2. Automatically adds the user to the organization with USER role
  3. Sets is_email_verified to true (since organization is vouching for the user)
  4. Sends a welcome email in the background
  5. Returns user data and authentication tokens

Error Responses

400 Bad Request

Missing or invalid parameters:

json { "error": "Email is required" }

json { "error": "First name is required" }

json { "error": "Invalid email format" }

401 Unauthorized

Invalid or missing API key:

json { "error": "This endpoint requires API key authentication" }

500 Internal Server Error

Server-side errors:

json { "error": "Failed to create user" }

json { "error": "Failed to generate authentication tokens" }

Security Features

  1. API Key Authentication: Only valid organization API keys can access this endpoint
  2. Automatic Password Generation: New users get secure random passwords
  3. Email Verification: Users created through this endpoint are automatically email verified
  4. HTTP-Only Cookies: JWT tokens are also set as secure HTTP-only cookies
  5. Input Validation: Email format and required fields are validated

Usage Examples

cURL Example

bash curl -X POST \ https://api.skillora.ai/api/authenticate-organization-user/ \ -H 'Authorization: Bearer sk_your_api_key_here' \ -H 'Content-Type: application/json' \ -d '{ "email": "new.employee@company.com", "first_name": "Jane", "last_name": "Smith" }'

Python Example

```python import requests

url = "https://api.skillora.ai/api/authenticate-organization-user/" headers = { "Authorization": "Bearer sk_your_api_key_here", "Content-Type": "application/json" } payload = { "email": "new.employee@company.com", "first_name": "Jane", "last_name": "Smith" }

response = requests.post(url, json=payload, headers=headers) data = response.json()

if response.status_code == 200: print(f"Success! User: {data['user_data']['email']}") print(f"Is new user: {data['is_new_user']}") print(f"Access token: {data['tokens']['access']}") else: print(f"Error: {data.get('error', 'Unknown error')}") ```

JavaScript Example

```javascript const response = await fetch('/api/authenticate-organization-user/', { method: 'POST', headers: { Authorization: 'Bearer sk_your_api_key_here', 'Content-Type': 'application/json', }, body: JSON.stringify({ email: 'new.employee@company.com', first_name: 'Jane', last_name: 'Smith', }), });

const data = await response.json();

if (response.ok) { console.log('Success!', data); // Store tokens for future API calls localStorage.setItem('access_token', data.tokens.access); localStorage.setItem('refresh_token', data.tokens.refresh); } else { console.error('Error:', data.error); } ```

Integration Guide

Step 1: Get API Key

First, create an API key for your organization through the admin panel or API:

bash python manage.py create_api_key <organization_id> "User Authentication Key"

Step 2: Store API Key Securely

Store the API key securely in your application (environment variables, secure configuration, etc.):

bash export API_KEY="sk_your_generated_api_key_here"

Step 3: Implement User Authentication Flow

Use this endpoint in your application's user onboarding or authentication flow:

  1. Collect user's email, first name, and last name
  2. Call the organization-auth endpoint
  3. Handle the response (store tokens, redirect user, etc.)
  4. Use the returned JWT tokens for subsequent API calls

Step 4: Handle Token Refresh

Use the refresh token to get new access tokens when they expire:

bash POST /api/users/jwt/refresh/ { "refresh": "your_refresh_token" }

Testing

Use the provided test script to verify the endpoint works correctly:

bash API_KEY=sk_your_api_key_here python test_organization_auth.py

Rate Limiting

API keys have configurable rate limits. The default is 100 requests per minute. Contact your administrator if you need higher limits.

Best Practices

  1. Secure API Key Storage: Never expose API keys in client-side code
  2. Use HTTPS: Always use HTTPS in production to protect API keys and tokens
  3. Token Storage: Store JWT tokens securely (HTTP-only cookies for web apps)
  4. Error Handling: Implement proper error handling for all possible response codes
  5. Logging: Log authentication events for audit purposes
  6. Token Refresh: Implement automatic token refresh in your application

Troubleshooting

Common Issues

  1. 401 Unauthorized

  2. Check that API key is valid and active

  3. Ensure API key is properly formatted in the Authorization header

  4. 400 Bad Request

  5. Verify all required fields are provided

  6. Check email format is valid

  7. 500 Internal Server Error

  8. Check server logs for detailed error information
  9. Verify database connectivity
  10. Ensure email service is configured correctly

Support

For additional support or questions about this API, please contact your system administrator or refer to the main API documentation.