Error 403 when accepting enrollment invitations via API

GAb192381928ab
Community Novice

Hello!

I am in the process of developing a feature to facilitate the acceptance of multiple enrollments for students on our platform. We offer a large number of courses and to simplify the lives of our students, I am creating a modal window that lists all the courses pending acceptance. The goal is to allow the student to accept all of them quickly and efficiently.

The code I am using uses the API to search for pending enrollments and then accepts the enrollments selected by the students. Authentication is done through the CSRF token, which is captured from cookies and included in the GET and POST requests.

However, I am facing a problem when trying to execute the POST request to accept the enrollments. I am receiving a 403 (Forbidden) error, indicating that the action is not authorized. The error message details that the status is "unauthorized", which suggests that there is a problem with the authorization, even after including the CSRF token in the request headers.

 

function getCSRFToken() {
    const match = document.cookie.match('(^|;)\\s*_csrf_token=([^;]*)');
    return match ? decodeURIComponent(match[2]) : null;
}

async function fetchEnrollmentId(courseId) {
    try {
        const csrfToken = getCSRFToken();
        if (!csrfToken) {
            throw new Error('Token CSRF não encontrado.');
        }

        const response = await fetch(`/api/v1/courses/${courseId}/enrollments?state[]=invited`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrfToken // Inclui o token CSRF no cabeçalho
            },
            credentials: 'include'
        });

        if (!response.ok) {
            throw new Error('Erro ao buscar matrículas');
        }

        const enrollments = await response.json();
        console.log('Matrículas encontradas:', enrollments);

        // Captura o primeiro enrollment_id encontrado com estado "invited"
        const enrollment = enrollments.find(enroll => enroll.enrollment_state === 'invited');
        return enrollment ? enrollment.id : null;
    } catch (error) {
        console.error('Erro ao buscar matrícula:', error);
    }
}

// Exemplo de uso para o curso com ID 658
fetchEnrollmentId('658').then(enrollmentId => {
    if (enrollmentId) {
        console.log(`Enrollment ID encontrado: ${enrollmentId}`);
        // Aqui você pode chamar a função acceptCourse para aceitar a matrícula
        acceptCourse('658', enrollmentId);
    } else {
        console.log('Nenhuma matrícula pendente encontrada.');
    }
});

// Função simples para aceitar o curso
async function acceptCourse(courseId, enrollmentId) {
    console.log(`Iniciando acceptCourse para o curso ID: ${courseId} e matrícula ID: ${enrollmentId}`);
    try {
        const csrfToken = getCSRFToken();
        if (!csrfToken) {
            throw new Error('Token CSRF não encontrado.');
        }

        const response = await fetch(`/api/v1/courses/${courseId}/enrollments/${enrollmentId}/accept`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrfToken // Inclui o token CSRF no cabeçalho
            },
            credentials: 'include'
        });

        if (response.ok) {
            console.log(`Curso com ID: ${courseId} e matrícula ID: ${enrollmentId} aceitos com sucesso!`);
        } else {
            console.log(`Erro: Não foi possível aceitar a matrícula. Status: ${response.status}`);
            const errorData = await response.json();
            console.log('Detalhes do erro:', errorData);
        }
    } catch (error) {
        console.error('Erro ao tentar aceitar a matrícula:', error);
    }
}

 

 
Note: The code is being tested through the browser's devtools console. It has already been tested on student and administrator users and the error remains the same.

Note2: Please forgive any errors that may be in the code, as I am not a dev and I am at the limit of my knowledge developing solutions for my platform together with GPT and seeking support in the documentation.

Labels (1)
0 Likes