summaryrefslogtreecommitdiff
path: root/templates/js/admin.js
blob: 4dff5729f129aead9c0847c04e2b5a0c7b5cd90a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * A wrapper for the fetch API that standardizes API calls.
 * It automatically sets the Content-Type for POST requests
 * and handles non-OK responses.
 * @param {string} url The URL to fetch.
 * @param {object} options The options for the fetch call.
 * @returns {Promise<Response>}
 */
async function fetchApi(url, options = {}) {
    options.headers = {
        ...options.headers,
    };

    // Set content type for methods that have a body.
    if (options.method === 'POST' || options.method === 'PUT') {
        options.headers['Content-Type'] = 'application/json';
    }

    const response = await fetch(url, options);

    // Redirect to login if unauthorized.
    if (response.status === 401) {
        window.location.href = LOGIN_PATH;
        // Throw an error to stop further processing
        throw new Error('Unauthorized');
    }

    return response;
}

function updateRole(userId) {
    const role = document.getElementById(`role-${userId}`).value;
    fetchApi(`${API_BASE_PATH}/${userId}/role`, {
        method: 'POST',
        body: JSON.stringify({ role })
    }).then(handleResponse);
}

function deleteUser(userId) {
    if (confirm('Are you sure you want to permanently delete this user?')) {
        fetchApi(`${API_BASE_PATH}/${userId}`, {
            method: 'DELETE'
        }).then(handleResponse);
    }
}

function toggleActive(userId, isActive) {
    const action = isActive ? 'activate' : 'deactivate';
    if (confirm(`Are you sure you want to ${action} this user?`)) {
        fetchApi(`${API_BASE_PATH}/${userId}/status`, {
            method: 'POST',
            body: JSON.stringify({ is_active: isActive })
        }).then(handleResponse);
    }
}

function handleResponse(response) {
    if (response.ok) {
        location.reload();
    } else {
        alert('Operation failed.');
    }
}