> ## Documentation Index
> Fetch the complete documentation index at: https://docs.scanova.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Update User Role

> Update the role/access level of an existing user. This allows you to change a user's permissions without removing and re-adding them.

## Overview

Updates the role/access level of an existing user in your account. This allows you to change a user's permissions without removing and re-adding them.

## Purpose

### **Role Management**

* **Change User Permissions**: Update user access levels
* **Role Transitions**: Promote or demote users
* **Permission Updates**: Modify user capabilities
* **Access Control**: Adjust user access as needed

### **User Administration**

* **Flexible Management**: Change roles without re-inviting
* **Permission Adjustments**: Fine-tune user access
* **Role Changes**: Handle role transitions smoothly
* **Access Updates**: Update user permissions dynamically

## Path Parameters

| Parameter        | Type    | Required | Description                     | Example |
| ---------------- | ------- | -------- | ------------------------------- | ------- |
| `shared-user-id` | integer | Yes      | ID of the shared user to update | `479`   |

## Request Body (Form Data)

| Field          | Type   | Required | Description         | Example |
| -------------- | ------ | -------- | ------------------- | ------- |
| `access_level` | string | Yes      | New access level ID | `"2"`   |

## Access Level Options

### **Default Roles**

* **Manager (ID: 1)**: Can create, edit, and manage QR codes
* **Admin (ID: 2)**: Full access including user management
* **Viewer (ID: 3)**: Read-only access to QR codes and analytics

### **Custom Roles**

* **Custom IDs**: Use custom role IDs created in your account
* **Specific Permissions**: Custom roles with tailored permissions
* **Flexible Access**: Create roles for specific use cases

## Examples

### **Promote User to Admin**

```bash theme={null}
curl -X PATCH "https://management.scanova.io/multi-users/479/" \
  -H "Authorization: YOUR_API_KEY" \
  -F "access_level=2"
```

### **Change User to Viewer Role**

```bash theme={null}
curl -X PATCH "https://management.scanova.io/multi-users/479/" \
  -H "Authorization: YOUR_API_KEY" \
  -F "access_level=3"
```

### **Assign Custom Role**

```bash theme={null}
curl -X PATCH "https://management.scanova.io/multi-users/479/" \
  -H "Authorization: YOUR_API_KEY" \
  -F "access_level=135"
```

## Response

### **Success Response (200 OK)**

```json theme={null}
{
  "id": 479,
  "shared_user": {
    "id": 1452,
    "first_name": "Jon Doe",
    "last_name": "",
    "full_name": "Jon Doe",
    "email": "jon.doe@scanova.io",
    "is_shared": true,
    "date_joined": "2023-09-11T16:28:22.113793+05:30",
    "is_social_signup": false,
    "is_sso_login": false,
    "has_usable_password": true,
    "language": "en",
    "last_login": null,
    "first_login": false,
    "enforce_mfa": false,
    "mfa_enabled": false,
    "mfa_status": "Disabled"
  },
  "access_level": {
    "id": 2,
    "name": "Admin",
    "permissions": [
      {
        "id": 22,
        "code": "QR_CODE_CAN_ADD",
        "name": "Can Add QR Code",
        "description": "Can add QR Code",
        "is_boolean": true
      },
      {
        "id": 25,
        "code": "QR_CODE_CAN_DELETE",
        "name": "Can Delete QR Code",
        "description": "Can delete QR code",
        "is_boolean": true
      },
      {
        "id": 18,
        "code": "SHARED_USER_CAN_VIEW",
        "name": "Can view shared user",
        "description": "Can view user",
        "is_boolean": true
      },
      {
        "id": 19,
        "code": "SHARED_USER_CAN_ADD",
        "name": "Can add shared user",
        "description": "Can add user",
        "is_boolean": true
      }
    ],
    "is_custom": false
  },
  "invitation_sent_on": "2023-09-11T16:28:22.227002+05:30",
  "invitation_accepted_on": null,
  "is_invitation_sent": true,
  "is_invitation_accepted": false,
  "created": "2023-09-11T16:28:22.223671+05:30",
  "modified": "2023-09-11T16:39:24.748614+05:30",
  "tags": []
}
```

## Role Change Scenarios

### **Promotion Scenarios**

* **Viewer → Manager**: Give user ability to create and edit QR codes
* **Manager → Admin**: Give user full access including user management
* **Any Role → Custom**: Assign specific custom role

### **Demotion Scenarios**

* **Admin → Manager**: Remove user management capabilities
* **Manager → Viewer**: Make user read-only
* **Any Role → Custom**: Assign more restrictive custom role

### **Lateral Changes**

* **Manager → Different Manager**: Change to different manager role
* **Custom → Custom**: Switch between custom roles
* **Any Role → Equivalent**: Change to equivalent role with different permissions

## Integration Examples

### **JavaScript - Role Update Form**

```javascript theme={null}
async function updateUserRole(userId, newAccessLevel) {
  try {
    const formData = new FormData();
    formData.append('access_level', newAccessLevel);
    
    const response = await fetch(`https://management.scanova.io/multi-users/${userId}/`, {
      method: 'PATCH',
      headers: {
        'Authorization': 'YOUR_API_KEY'
      },
      body: formData
    });
    
    if (response.ok) {
      const updatedUser = await response.json();
      console.log('User role updated successfully:', updatedUser);
      
      // Show success message
      showMessage(`User ${updatedUser.shared_user.full_name} role updated to ${updatedUser.access_level.name}!`);
      
      // Refresh user list
      refreshUserList();
      
      return updatedUser;
    } else {
      const error = await response.json();
      throw new Error(error.detail || 'Failed to update user role');
    }
  } catch (error) {
    console.error('Error updating user role:', error);
    showMessage('Error updating user role: ' + error.message, 'error');
    return null;
  }
}

// Usage
updateUserRole(479, '2'); // Promote to Admin
```

### **Python - Role Management System**

```python theme={null}
import requests

def update_user_role(user_id, new_access_level):
    url = f"https://management.scanova.io/multi-users/{user_id}/"
    headers = {"Authorization": "YOUR_API_KEY"}
    
    data = {
        'access_level': str(new_access_level)
    }
    
    try:
        response = requests.patch(url, headers=headers, data=data)
        response.raise_for_status()
        
        user = response.json()
        print(f"User {user['shared_user']['full_name']} role updated successfully!")
        print(f"New role: {user['access_level']['name']}")
        print(f"New permissions: {len(user['access_level']['permissions'])} permissions")
        
        return user
        
    except requests.exceptions.RequestException as e:
        print(f"Error updating user role: {e}")
        return None

def promote_user(user_id):
    """Promote user to Admin role"""
    return update_user_role(user_id, 2)

def demote_user(user_id):
    """Demote user to Viewer role"""
    return update_user_role(user_id, 3)

def make_manager(user_id):
    """Make user a Manager"""
    return update_user_role(user_id, 1)

# Usage
user_id = 479

# Promote to Admin
promote_user(user_id)

# Demote to Viewer
demote_user(user_id)

# Make Manager
make_manager(user_id)
```

### **PHP - Role Update Interface**

```php theme={null}
<?php
function updateUserRole($userId, $newAccessLevel) {
    $url = "https://management.scanova.io/multi-users/{$userId}/";
    $headers = [
        "Authorization: YOUR_API_KEY"
    ];
    
    $data = [
        'access_level' => (string)$newAccessLevel
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $user = json_decode($response, true);
        echo "User {$user['shared_user']['full_name']} role updated successfully!<br>";
        echo "New role: {$user['access_level']['name']}<br>";
        return $user;
    } else {
        echo "Error updating user role: " . $response;
        return null;
    }
}

// Handle form submission
if ($_POST['submit']) {
    $userId = $_POST['user_id'];
    $newAccessLevel = $_POST['access_level'];
    
    $result = updateUserRole($userId, $newAccessLevel);
}

// HTML Form
?>
<form method="POST">
    <label>User ID: <input type="number" name="user_id" required></label><br>
    <label>New Role: 
        <select name="access_level" required>
            <option value="1">Manager</option>
            <option value="2">Admin</option>
            <option value="3">Viewer</option>
        </select>
    </label><br>
    <input type="submit" name="submit" value="Update Role">
</form>
```

## Error Handling

### **Common Errors**

#### **Invalid Access Level**

```json theme={null}
{
  "access_level": ["Invalid access level ID."]
}
```

#### **User Not Found**

```json theme={null}
{
  "detail": "Not found."
}
```

#### **Missing Access Level**

```json theme={null}
{
  "access_level": ["This field is required."]
}
```

## Best Practices

### **Role Management**

* **Review Before Change**: Understand current and new permissions
* **Communicate Changes**: Inform users of role changes
* **Document Changes**: Keep records of role changes
* **Regular Reviews**: Periodically review user roles

### **Security Considerations**

* **Principle of Least Privilege**: Give users minimum required access
* **Role Validation**: Ensure new roles are appropriate
* **Change Monitoring**: Monitor role changes for security
* **Access Auditing**: Regular access audits

### **User Experience**

* **Clear Communication**: Explain role changes to users
* **Smooth Transitions**: Handle role changes gracefully
* **Permission Clarity**: Ensure users understand their new permissions
* **Support**: Provide support during role transitions

<Note>
  When you update a user's role, the changes take effect immediately. The user will have the new permissions the next time they access the account.
</Note>

<Warning>
  Be careful when promoting users to Admin role, as they will have full access to your account including the ability to add and remove other users.
</Warning>

<Info>
  You can use custom role IDs instead of the default role IDs (1, 2, 3) to assign users to custom roles you've created in your account.
</Info>


## OpenAPI

````yaml PATCH /multi-users/{shared-user-id}/
openapi: 3.0.0
info:
  title: Scanova API - User Management
  description: >-
    User management endpoints for managing shared users, roles, and permissions
    in your Scanova account. These endpoints allow you to invite users, assign
    roles, and manage access levels.
  version: 1.0.0
servers:
  - url: https://management.scanova.io
    description: Scanova Management API Server
security:
  - apiKeyAuth: []
paths:
  /multi-users/{shared-user-id}/:
    patch:
      tags:
        - User Management
      summary: Update User Role
      description: >-
        Update the role/access level of an existing user. This allows you to
        change a user's permissions without removing and re-adding them.
      parameters:
        - name: shared-user-id
          in: path
          required: true
          description: ID of the shared user
          schema:
            type: integer
          example: 479
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - access_level
              properties:
                access_level:
                  type: string
                  description: >-
                    New access level ID for the user. Pre-defined access levels:
                    Manager (1), Admin (2), Viewer (3)
                  example: '2'
            examples:
              promote_to_admin:
                summary: Promote user to Admin
                value:
                  access_level: '2'
              demote_to_viewer:
                summary: Change user to Viewer role
                value:
                  access_level: '3'
      responses:
        '200':
          description: User role updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SharedUser'
        '400':
          description: Bad request - Invalid access level
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationErrorResponse'
        '401':
          description: Unauthorized - Invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AuthenticationErrorResponse'
        '404':
          description: User not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - apiKeyAuth: []
components:
  schemas:
    SharedUser:
      type: object
      properties:
        id:
          type: integer
          description: Shared user relationship ID
          example: 479
        shared_user:
          $ref: '#/components/schemas/User'
        access_level:
          $ref: '#/components/schemas/AccessLevel'
        invitation_sent_on:
          type: string
          format: date-time
          nullable: true
          description: When the invitation was sent
          example: '2023-09-11T16:28:22.227002+05:30'
        invitation_accepted_on:
          type: string
          format: date-time
          nullable: true
          description: When the invitation was accepted
          example: null
        is_invitation_sent:
          type: boolean
          description: Whether invitation has been sent
          example: true
        is_invitation_accepted:
          type: boolean
          description: Whether invitation has been accepted
          example: false
        created:
          type: string
          format: date-time
          description: When the user was added
          example: '2023-09-11T16:28:22.223671+05:30'
        modified:
          type: string
          format: date-time
          description: When the user was last modified
          example: '2023-09-11T16:28:22.227109+05:30'
        tags:
          type: array
          items:
            $ref: '#/components/schemas/UserTag'
          description: Tags assigned to the user
    ValidationErrorResponse:
      type: object
      properties:
        field_name:
          type: array
          items:
            type: string
          example:
            - This field is required.
    AuthenticationErrorResponse:
      type: object
      properties:
        detail:
          type: string
          example: Authentication credentials were not provided.
    ErrorResponse:
      type: object
      properties:
        detail:
          type: string
          example: Not found.
    User:
      type: object
      properties:
        id:
          type: integer
          description: User ID
          example: 1452
        first_name:
          type: string
          description: User's first name
          example: Jon
        last_name:
          type: string
          description: User's last name
          example: Doe
        full_name:
          type: string
          description: User's full name
          example: Jon Doe
        email:
          type: string
          format: email
          description: User's email address
          example: jon.doe@scanova.io
        is_shared:
          type: boolean
          description: Whether this is a shared user
          example: true
        date_joined:
          type: string
          format: date-time
          description: When the user joined
          example: '2023-09-11T16:28:22.113793+05:30'
        is_social_signup:
          type: boolean
          description: Whether user signed up via social login
          example: false
        is_sso_login:
          type: boolean
          description: Whether user uses SSO login
          example: false
        has_usable_password:
          type: boolean
          description: Whether user has a usable password
          example: true
        language:
          type: string
          description: User's preferred language
          example: en
        last_login:
          type: string
          format: date-time
          nullable: true
          description: User's last login time
          example: null
        first_login:
          type: boolean
          description: Whether this is the user's first login
          example: false
        enforce_mfa:
          type: boolean
          description: Whether MFA is enforced for this user
          example: false
        mfa_enabled:
          type: boolean
          description: Whether MFA is enabled for this user
          example: false
        mfa_status:
          type: string
          description: MFA status
          example: Disabled
    AccessLevel:
      type: object
      properties:
        id:
          type: integer
          description: Access level ID
          example: 1
        name:
          type: string
          description: Access level name
          example: Manager
        permissions:
          type: array
          items:
            $ref: '#/components/schemas/Permission'
          description: List of permissions for this access level
        is_custom:
          type: boolean
          description: Whether this is a custom role or default role
          example: false
    UserTag:
      type: object
      properties:
        id:
          type: integer
          description: Tag ID
          example: 2950
        name:
          type: string
          description: Tag name
          example: SOCIAL ALL FIELDS
    Permission:
      type: object
      properties:
        id:
          type: integer
          description: Permission ID
          example: 22
        code:
          type: string
          description: Permission code
          example: QR_CODE_CAN_ADD
        name:
          type: string
          description: Permission name
          example: Can Add QR Code
        description:
          type: string
          description: Permission description
          example: Can add QR Code
        is_boolean:
          type: boolean
          description: Whether this is a boolean permission
          example: true
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        API key authentication. Enter your API key directly in the Authorization
        header.

````